Merge "Clone fence inside QueueBufferInput on retrieval."
diff --git a/camera/Android.mk b/camera/Android.mk
index c9c98e9..91d87ed 100644
--- a/camera/Android.mk
+++ b/camera/Android.mk
@@ -65,11 +65,11 @@
 	system/media/camera/include \
 	system/media/private/camera/include \
 	frameworks/native/include/media/openmax \
-	frameworks/av/include/camera
+	$(LOCAL_PATH)/include/camera
 
 LOCAL_EXPORT_C_INCLUDE_DIRS := \
 	system/media/camera/include \
-	frameworks/av/include/camera
+	$(LOCAL_PATH)/include/camera
 
 LOCAL_CFLAGS += -Werror -Wall -Wextra
 
diff --git a/include/camera/Camera.h b/camera/include/camera/Camera.h
similarity index 100%
rename from include/camera/Camera.h
rename to camera/include/camera/Camera.h
diff --git a/include/camera/CameraBase.h b/camera/include/camera/CameraBase.h
similarity index 100%
rename from include/camera/CameraBase.h
rename to camera/include/camera/CameraBase.h
diff --git a/include/camera/CameraMetadata.h b/camera/include/camera/CameraMetadata.h
similarity index 100%
rename from include/camera/CameraMetadata.h
rename to camera/include/camera/CameraMetadata.h
diff --git a/include/camera/CameraParameters.h b/camera/include/camera/CameraParameters.h
similarity index 100%
rename from include/camera/CameraParameters.h
rename to camera/include/camera/CameraParameters.h
diff --git a/include/camera/CameraParameters2.h b/camera/include/camera/CameraParameters2.h
similarity index 100%
rename from include/camera/CameraParameters2.h
rename to camera/include/camera/CameraParameters2.h
diff --git a/include/camera/CameraUtils.h b/camera/include/camera/CameraUtils.h
similarity index 100%
rename from include/camera/CameraUtils.h
rename to camera/include/camera/CameraUtils.h
diff --git a/include/camera/CaptureResult.h b/camera/include/camera/CaptureResult.h
similarity index 100%
rename from include/camera/CaptureResult.h
rename to camera/include/camera/CaptureResult.h
diff --git a/include/camera/ICameraRecordingProxy.h b/camera/include/camera/ICameraRecordingProxy.h
similarity index 100%
rename from include/camera/ICameraRecordingProxy.h
rename to camera/include/camera/ICameraRecordingProxy.h
diff --git a/include/camera/ICameraRecordingProxyListener.h b/camera/include/camera/ICameraRecordingProxyListener.h
similarity index 100%
rename from include/camera/ICameraRecordingProxyListener.h
rename to camera/include/camera/ICameraRecordingProxyListener.h
diff --git a/include/camera/ICameraServiceProxy.h b/camera/include/camera/ICameraServiceProxy.h
similarity index 100%
rename from include/camera/ICameraServiceProxy.h
rename to camera/include/camera/ICameraServiceProxy.h
diff --git a/include/camera/VendorTagDescriptor.h b/camera/include/camera/VendorTagDescriptor.h
similarity index 100%
rename from include/camera/VendorTagDescriptor.h
rename to camera/include/camera/VendorTagDescriptor.h
diff --git a/include/camera/android/hardware/ICamera.h b/camera/include/camera/android/hardware/ICamera.h
similarity index 100%
rename from include/camera/android/hardware/ICamera.h
rename to camera/include/camera/android/hardware/ICamera.h
diff --git a/include/camera/android/hardware/ICameraClient.h b/camera/include/camera/android/hardware/ICameraClient.h
similarity index 100%
rename from include/camera/android/hardware/ICameraClient.h
rename to camera/include/camera/android/hardware/ICameraClient.h
diff --git a/include/camera/camera2/CaptureRequest.h b/camera/include/camera/camera2/CaptureRequest.h
similarity index 100%
rename from include/camera/camera2/CaptureRequest.h
rename to camera/include/camera/camera2/CaptureRequest.h
diff --git a/include/camera/camera2/OutputConfiguration.h b/camera/include/camera/camera2/OutputConfiguration.h
similarity index 100%
rename from include/camera/camera2/OutputConfiguration.h
rename to camera/include/camera/camera2/OutputConfiguration.h
diff --git a/include/camera/camera2/SubmitInfo.h b/camera/include/camera/camera2/SubmitInfo.h
similarity index 100%
rename from include/camera/camera2/SubmitInfo.h
rename to camera/include/camera/camera2/SubmitInfo.h
diff --git a/include/camera/ndk/NdkCameraCaptureSession.h b/camera/include/camera/ndk/NdkCameraCaptureSession.h
similarity index 100%
rename from include/camera/ndk/NdkCameraCaptureSession.h
rename to camera/include/camera/ndk/NdkCameraCaptureSession.h
diff --git a/include/camera/ndk/NdkCameraDevice.h b/camera/include/camera/ndk/NdkCameraDevice.h
similarity index 100%
rename from include/camera/ndk/NdkCameraDevice.h
rename to camera/include/camera/ndk/NdkCameraDevice.h
diff --git a/include/camera/ndk/NdkCameraError.h b/camera/include/camera/ndk/NdkCameraError.h
similarity index 100%
rename from include/camera/ndk/NdkCameraError.h
rename to camera/include/camera/ndk/NdkCameraError.h
diff --git a/include/camera/ndk/NdkCameraManager.h b/camera/include/camera/ndk/NdkCameraManager.h
similarity index 100%
rename from include/camera/ndk/NdkCameraManager.h
rename to camera/include/camera/ndk/NdkCameraManager.h
diff --git a/include/camera/ndk/NdkCameraMetadata.h b/camera/include/camera/ndk/NdkCameraMetadata.h
similarity index 100%
rename from include/camera/ndk/NdkCameraMetadata.h
rename to camera/include/camera/ndk/NdkCameraMetadata.h
diff --git a/include/camera/ndk/NdkCameraMetadataTags.h b/camera/include/camera/ndk/NdkCameraMetadataTags.h
similarity index 100%
rename from include/camera/ndk/NdkCameraMetadataTags.h
rename to camera/include/camera/ndk/NdkCameraMetadataTags.h
diff --git a/include/camera/ndk/NdkCaptureRequest.h b/camera/include/camera/ndk/NdkCaptureRequest.h
similarity index 100%
rename from include/camera/ndk/NdkCaptureRequest.h
rename to camera/include/camera/ndk/NdkCaptureRequest.h
diff --git a/drm/libmediadrm/Android.mk b/drm/libmediadrm/Android.mk
index 8e3cc40..7176582 100644
--- a/drm/libmediadrm/Android.mk
+++ b/drm/libmediadrm/Android.mk
@@ -6,12 +6,24 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= \
+LOCAL_AIDL_INCLUDES := \
+    frameworks/base/media/java
+
+LOCAL_SRC_FILES := \
+    ../../../base/media/java/android/media/ICas.aidl \
+    ../../../base/media/java/android/media/ICasListener.aidl \
+    ../../../base/media/java/android/media/IDescrambler.aidl \
+    ../../../base/media/java/android/media/IMediaCasService.aidl \
+
+LOCAL_SRC_FILES += \
+    CasImpl.cpp \
+    DescramblerImpl.cpp \
     DrmSessionManager.cpp \
     ICrypto.cpp \
     IDrm.cpp \
     IDrmClient.cpp \
     IMediaDrmService.cpp \
+    MediaCasDefs.cpp \
     SharedLibrary.cpp
 ifneq ($(DISABLE_TREBLE_DRM), true)
 LOCAL_SRC_FILES += \
diff --git a/drm/libmediadrm/CasImpl.cpp b/drm/libmediadrm/CasImpl.cpp
new file mode 100644
index 0000000..de15244
--- /dev/null
+++ b/drm/libmediadrm/CasImpl.cpp
@@ -0,0 +1,201 @@
+
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+//#define LOG_NDEBUG 0
+#define LOG_TAG "CasImpl"
+
+#include <android/media/ICasListener.h>
+#include <media/cas/CasAPI.h>
+#include <media/CasImpl.h>
+#include <media/SharedLibrary.h>
+#include <utils/Log.h>
+
+namespace android {
+
+static Status getBinderStatus(status_t err) {
+    if (err == OK) {
+        return Status::ok();
+    }
+    if (err == BAD_VALUE) {
+        return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
+    }
+    if (err == INVALID_OPERATION) {
+        return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
+    }
+    return Status::fromServiceSpecificError(err);
+}
+
+static String8 sessionIdToString(const CasSessionId &sessionId) {
+    String8 result;
+    for (size_t i = 0; i < sessionId.size(); i++) {
+        result.appendFormat("%02x ", sessionId[i]);
+    }
+    if (result.isEmpty()) {
+        result.append("(null)");
+    }
+    return result;
+}
+
+CasImpl::CasImpl(const sp<ICasListener> &listener)
+    : mPlugin(NULL), mListener(listener) {
+    ALOGV("CTOR: mPlugin=%p", mPlugin);
+}
+
+CasImpl::~CasImpl() {
+    ALOGV("DTOR: mPlugin=%p", mPlugin);
+    release();
+}
+
+//static
+void CasImpl::OnEvent(
+        void *appData,
+        int32_t event,
+        int32_t arg,
+        uint8_t *data,
+        size_t size) {
+    if (appData == NULL) {
+        ALOGE("Invalid appData!");
+        return;
+    }
+    CasImpl *casImpl = static_cast<CasImpl *>(appData);
+    casImpl->onEvent(event, arg, data, size);
+}
+
+void CasImpl::init(const sp<SharedLibrary>& library, CasPlugin *plugin) {
+    mLibrary = library;
+    mPlugin = plugin;
+}
+
+void CasImpl::onEvent(
+        int32_t event, int32_t arg, uint8_t *data, size_t size) {
+    if (mListener == NULL) {
+        return;
+    }
+
+    std::unique_ptr<CasData> eventData;
+    if (data != NULL && size > 0) {
+        eventData.reset(new CasData(data, data + size));
+    }
+
+    mListener->onEvent(event, arg, eventData);
+}
+
+Status CasImpl::setPrivateData(const CasData& pvtData) {
+    ALOGV("setPrivateData");
+    return getBinderStatus(mPlugin->setPrivateData(pvtData));
+}
+
+Status CasImpl::openSession(int32_t program_number, CasSessionId* sessionId) {
+    ALOGV("openSession: program_number=%d", program_number);
+
+    status_t err = mPlugin->openSession(program_number, sessionId);
+
+    ALOGV("openSession: session opened for program_number=%d, sessionId=%s",
+            program_number, sessionIdToString(*sessionId).string());
+
+    return getBinderStatus(err);
+}
+
+Status CasImpl::openSessionForStream(
+        int32_t program_number,
+        int32_t elementary_PID,
+        CasSessionId* sessionId) {
+    ALOGV("openSession: program_number=%d, elementary_PID=%d",
+            program_number, elementary_PID);
+
+    status_t err = mPlugin->openSession(
+            program_number, elementary_PID, sessionId);
+
+    ALOGV("openSession: session opened for "
+            "program_number=%d, elementary_PID=%d, sessionId=%s",
+            program_number, elementary_PID,
+            sessionIdToString(*sessionId).string());
+
+    return getBinderStatus(err);
+}
+
+Status CasImpl::setSessionPrivateData(
+        const CasSessionId &sessionId, const CasData& pvtData) {
+    ALOGV("setSessionPrivateData: sessionId=%s",
+            sessionIdToString(sessionId).string());
+
+    return getBinderStatus(mPlugin->setSessionPrivateData(sessionId, pvtData));
+}
+
+Status CasImpl::closeSession(const CasSessionId &sessionId) {
+    ALOGV("closeSession: sessionId=%s",
+            sessionIdToString(sessionId).string());
+
+    return getBinderStatus(mPlugin->closeSession(sessionId));
+}
+
+Status CasImpl::processEcm(const CasSessionId &sessionId, const ParcelableCasData& ecm) {
+    ALOGV("processEcm: sessionId=%s",
+            sessionIdToString(sessionId).string());
+
+    return getBinderStatus(mPlugin->processEcm(sessionId, ecm));
+}
+
+Status CasImpl::processEmm(const ParcelableCasData& emm) {
+    ALOGV("processEmm");
+
+    return getBinderStatus(mPlugin->processEmm(emm));
+}
+
+Status CasImpl::sendEvent(
+        int32_t event, int32_t arg, const ::std::unique_ptr<CasData> &eventData) {
+    ALOGV("sendEvent");
+
+    status_t err;
+    if (eventData == nullptr) {
+        err = mPlugin->sendEvent(event, arg, CasData());
+    } else {
+        err = mPlugin->sendEvent(event, arg, *eventData);
+    }
+    return getBinderStatus(err);
+}
+
+Status CasImpl::provision(const String16& provisionString) {
+    ALOGV("provision: provisionString=%s", String8(provisionString).string());
+
+    return getBinderStatus(mPlugin->provision(String8(provisionString)));
+}
+
+Status CasImpl::refreshEntitlements(
+        int32_t refreshType, const ::std::unique_ptr<CasData> &refreshData) {
+    ALOGV("refreshEntitlements");
+
+    status_t err;
+    if (refreshData == nullptr) {
+        err = mPlugin->refreshEntitlements(refreshType, CasData());
+    } else {
+        err = mPlugin->refreshEntitlements(refreshType, *refreshData);
+    }
+    return getBinderStatus(err);
+}
+
+Status CasImpl::release() {
+    ALOGV("release: mPlugin=%p", mPlugin);
+
+    if (mPlugin != NULL) {
+        delete mPlugin;
+        mPlugin = NULL;
+    }
+    return Status::ok();
+}
+
+} // namespace android
+
diff --git a/drm/libmediadrm/DescramblerImpl.cpp b/drm/libmediadrm/DescramblerImpl.cpp
new file mode 100644
index 0000000..94e09e2
--- /dev/null
+++ b/drm/libmediadrm/DescramblerImpl.cpp
@@ -0,0 +1,107 @@
+
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+//#define LOG_NDEBUG 0
+#define LOG_TAG "DescramblerImpl"
+
+#include <media/cas/DescramblerAPI.h>
+#include <media/DescramblerImpl.h>
+#include <media/SharedLibrary.h>
+#include <utils/Log.h>
+#include <binder/IMemory.h>
+
+namespace android {
+
+static Status getBinderStatus(status_t err) {
+    if (err == OK) {
+        return Status::ok();
+    }
+    if (err == BAD_VALUE) {
+        return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
+    }
+    if (err == INVALID_OPERATION) {
+        return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
+    }
+    return Status::fromServiceSpecificError(err);
+}
+
+static String8 sessionIdToString(const CasSessionId &sessionId) {
+    String8 result;
+    for (size_t i = 0; i < sessionId.size(); i++) {
+        result.appendFormat("%02x ", sessionId[i]);
+    }
+    if (result.isEmpty()) {
+        result.append("(null)");
+    }
+    return result;
+}
+
+DescramblerImpl::DescramblerImpl(
+        const sp<SharedLibrary>& library, DescramblerPlugin *plugin) :
+        mLibrary(library), mPlugin(plugin) {
+    ALOGV("CTOR: mPlugin=%p", mPlugin);
+}
+
+DescramblerImpl::~DescramblerImpl() {
+    ALOGV("DTOR: mPlugin=%p", mPlugin);
+    release();
+}
+
+Status DescramblerImpl::setMediaCasSession(const CasSessionId& sessionId) {
+    ALOGV("setMediaCasSession: sessionId=%s",
+            sessionIdToString(sessionId).string());
+
+    return getBinderStatus(mPlugin->setMediaCasSession(sessionId));
+}
+
+Status DescramblerImpl::requiresSecureDecoderComponent(
+        const String16& mime, bool *result) {
+    *result = mPlugin->requiresSecureDecoderComponent(String8(mime));
+
+    return getBinderStatus(OK);
+}
+
+Status DescramblerImpl::descramble(
+        const DescrambleInfo& info, int32_t *result) {
+    ALOGV("descramble");
+
+    *result = mPlugin->descramble(
+            info.dstType != DescrambleInfo::kDestinationTypeVmPointer,
+            info.scramblingControl,
+            info.numSubSamples,
+            info.subSamples,
+            info.srcMem->pointer(),
+            info.srcOffset,
+            info.dstType == DescrambleInfo::kDestinationTypeVmPointer ?
+                    info.srcMem->pointer() : info.dstPtr,
+            info.dstOffset,
+            NULL);
+
+    return getBinderStatus(*result >= 0 ? OK : *result);
+}
+
+Status DescramblerImpl::release() {
+    ALOGV("release: mPlugin=%p", mPlugin);
+
+    if (mPlugin != NULL) {
+        delete mPlugin;
+        mPlugin = NULL;
+    }
+    return Status::ok();
+}
+
+} // namespace android
+
diff --git a/drm/libmediadrm/MediaCasDefs.cpp b/drm/libmediadrm/MediaCasDefs.cpp
new file mode 100644
index 0000000..9c2ba38
--- /dev/null
+++ b/drm/libmediadrm/MediaCasDefs.cpp
@@ -0,0 +1,184 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+//#define LOG_NDEBUG 0
+#define LOG_TAG "MediaCas"
+
+#include <media/MediaCasDefs.h>
+#include <utils/Log.h>
+#include <binder/IMemory.h>
+
+namespace android {
+namespace media {
+
+///////////////////////////////////////////////////////////////////////////////
+namespace MediaCas {
+
+status_t ParcelableCasData::readFromParcel(const Parcel* parcel) {
+    return parcel->readByteVector(this);
+}
+
+status_t ParcelableCasData::writeToParcel(Parcel* parcel) const  {
+    return parcel->writeByteVector(*this);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+status_t ParcelableCasPluginDescriptor::readFromParcel(const Parcel* /*parcel*/) {
+    ALOGE("CAPluginDescriptor::readFromParcel() shouldn't be called");
+    return INVALID_OPERATION;
+}
+
+status_t ParcelableCasPluginDescriptor::writeToParcel(Parcel* parcel) const {
+    status_t err = parcel->writeInt32(mCASystemId);
+    if (err != NO_ERROR) {
+        return err;
+    }
+    return parcel->writeString16(mName);
+}
+
+} // namespace MediaCas
+///////////////////////////////////////////////////////////////////////////////
+
+namespace MediaDescrambler {
+
+DescrambleInfo::DescrambleInfo() {}
+
+DescrambleInfo::~DescrambleInfo() {}
+
+status_t DescrambleInfo::readFromParcel(const Parcel* parcel) {
+    status_t err = parcel->readInt32((int32_t*)&dstType);
+    if (err != OK) {
+        return err;
+    }
+    if (dstType != kDestinationTypeNativeHandle
+            && dstType != kDestinationTypeVmPointer) {
+        return BAD_VALUE;
+    }
+
+    err = parcel->readInt32((int32_t*)&scramblingControl);
+    if (err != OK) {
+        return err;
+    }
+
+    err = parcel->readUint32((uint32_t*)&numSubSamples);
+    if (err != OK) {
+        return err;
+    }
+    if (numSubSamples > 0xffff) {
+        return BAD_VALUE;
+    }
+
+    subSamples = new DescramblerPlugin::SubSample[numSubSamples];
+    if (subSamples == NULL) {
+        return NO_MEMORY;
+    }
+
+    for (size_t i = 0; i < numSubSamples; i++) {
+        err = parcel->readUint32(&subSamples[i].mNumBytesOfClearData);
+        if (err != OK) {
+            return err;
+        }
+        err = parcel->readUint32(&subSamples[i].mNumBytesOfEncryptedData);
+        if (err != OK) {
+            return err;
+        }
+    }
+
+    srcMem = interface_cast<IMemory>(parcel->readStrongBinder());
+    if (srcMem == NULL) {
+        return BAD_VALUE;
+    }
+
+    err = parcel->readInt32(&srcOffset);
+    if (err != OK) {
+        return err;
+    }
+
+    native_handle_t *nativeHandle = NULL;
+    if (dstType == kDestinationTypeNativeHandle) {
+        nativeHandle = parcel->readNativeHandle();
+        dstPtr = static_cast<void *>(nativeHandle);
+    } else {
+        dstPtr = NULL;
+    }
+
+    err = parcel->readInt32(&dstOffset);
+    if (err != OK) {
+        return err;
+    }
+
+    return OK;
+}
+
+status_t DescrambleInfo::writeToParcel(Parcel* parcel) const {
+    if (dstType != kDestinationTypeNativeHandle
+            && dstType != kDestinationTypeVmPointer) {
+        return BAD_VALUE;
+    }
+
+    status_t err = parcel->writeInt32((int32_t)dstType);
+    if (err != OK) {
+        return err;
+    }
+
+    err = parcel->writeInt32(scramblingControl);
+    if (err != OK) {
+        return err;
+    }
+
+    err = parcel->writeUint32(numSubSamples);
+    if (err != OK) {
+        return err;
+    }
+
+    for (size_t i = 0; i < numSubSamples; i++) {
+        err = parcel->writeUint32(subSamples[i].mNumBytesOfClearData);
+        if (err != OK) {
+            return err;
+        }
+        err = parcel->writeUint32(subSamples[i].mNumBytesOfEncryptedData);
+        if (err != OK) {
+            return err;
+        }
+    }
+
+    err = parcel->writeStrongBinder(IInterface::asBinder(srcMem));
+    if (err != OK) {
+        return err;
+    }
+
+    err = parcel->writeInt32(srcOffset);
+    if (err != OK) {
+        return err;
+    }
+
+    if (dstType == kDestinationTypeNativeHandle) {
+        parcel->writeNativeHandle(static_cast<native_handle_t *>(dstPtr));
+    }
+
+    err = parcel->writeInt32(dstOffset);
+    if (err != OK) {
+        return err;
+    }
+
+    return OK;
+}
+
+} // namespace MediaDescrambler
+
+} // namespace media
+} // namespace android
+
diff --git a/drm/libmediadrm/SharedLibrary.cpp b/drm/libmediadrm/SharedLibrary.cpp
index 74b3a71..bebafa8 100644
--- a/drm/libmediadrm/SharedLibrary.cpp
+++ b/drm/libmediadrm/SharedLibrary.cpp
@@ -43,6 +43,9 @@
         if (!mLibHandle) {
             return NULL;
         }
+        // Clear last error before we load the symbol again,
+        // in case the caller didn't retrieve it.
+        (void)dlerror();
         return dlsym(mLibHandle, symbol);
     }
 
diff --git a/include/camera b/include/camera
new file mode 120000
index 0000000..00848e3
--- /dev/null
+++ b/include/camera
@@ -0,0 +1 @@
+../camera/include/camera/
\ No newline at end of file
diff --git a/include/cpustats b/include/cpustats
new file mode 120000
index 0000000..4a02d41
--- /dev/null
+++ b/include/cpustats
@@ -0,0 +1 @@
+../media/libcpustats/include/cpustats/
\ No newline at end of file
diff --git a/include/media/AVSyncSettings.h b/include/media/AVSyncSettings.h
new file mode 120000
index 0000000..4b48419
--- /dev/null
+++ b/include/media/AVSyncSettings.h
@@ -0,0 +1 @@
+../../media/libmedia/include/AVSyncSettings.h
\ No newline at end of file
diff --git a/include/media/AudioBufferProvider.h b/include/media/AudioBufferProvider.h
new file mode 120000
index 0000000..dd7e234
--- /dev/null
+++ b/include/media/AudioBufferProvider.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioBufferProvider.h
\ No newline at end of file
diff --git a/include/media/AudioEffect.h b/include/media/AudioEffect.h
new file mode 120000
index 0000000..343749c
--- /dev/null
+++ b/include/media/AudioEffect.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioEffect.h
\ No newline at end of file
diff --git a/include/media/AudioIoDescriptor.h b/include/media/AudioIoDescriptor.h
new file mode 120000
index 0000000..057129b
--- /dev/null
+++ b/include/media/AudioIoDescriptor.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioIoDescriptor.h
\ No newline at end of file
diff --git a/include/media/AudioMixer.h b/include/media/AudioMixer.h
new file mode 120000
index 0000000..a2d0791
--- /dev/null
+++ b/include/media/AudioMixer.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioMixer.h
\ No newline at end of file
diff --git a/include/media/AudioParameter.h b/include/media/AudioParameter.h
new file mode 120000
index 0000000..6b6fe3b
--- /dev/null
+++ b/include/media/AudioParameter.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioParameter.h
\ No newline at end of file
diff --git a/include/media/AudioPolicy.h b/include/media/AudioPolicy.h
new file mode 120000
index 0000000..49ee572
--- /dev/null
+++ b/include/media/AudioPolicy.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioPolicy.h
\ No newline at end of file
diff --git a/include/media/AudioPolicyHelper.h b/include/media/AudioPolicyHelper.h
new file mode 120000
index 0000000..a0302e2
--- /dev/null
+++ b/include/media/AudioPolicyHelper.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioPolicyHelper.h
\ No newline at end of file
diff --git a/include/media/AudioRecord.h b/include/media/AudioRecord.h
new file mode 120000
index 0000000..d5a5c36
--- /dev/null
+++ b/include/media/AudioRecord.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioRecord.h
\ No newline at end of file
diff --git a/include/media/AudioResampler.h b/include/media/AudioResampler.h
new file mode 120000
index 0000000..50e12f4
--- /dev/null
+++ b/include/media/AudioResampler.h
@@ -0,0 +1 @@
+../../media/libaudioprocessing/include/AudioResampler.h
\ No newline at end of file
diff --git a/include/media/AudioResamplerPublic.h b/include/media/AudioResamplerPublic.h
new file mode 120000
index 0000000..309c23d
--- /dev/null
+++ b/include/media/AudioResamplerPublic.h
@@ -0,0 +1 @@
+../../media/libaudioprocessing/include/AudioResamplerPublic.h
\ No newline at end of file
diff --git a/include/media/AudioSystem.h b/include/media/AudioSystem.h
new file mode 120000
index 0000000..0b7179f
--- /dev/null
+++ b/include/media/AudioSystem.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioSystem.h
\ No newline at end of file
diff --git a/include/media/AudioTimestamp.h b/include/media/AudioTimestamp.h
new file mode 120000
index 0000000..f266780
--- /dev/null
+++ b/include/media/AudioTimestamp.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioTimestamp.h
\ No newline at end of file
diff --git a/include/media/AudioTrack.h b/include/media/AudioTrack.h
new file mode 120000
index 0000000..fddb075
--- /dev/null
+++ b/include/media/AudioTrack.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/AudioTrack.h
\ No newline at end of file
diff --git a/include/media/BufferProviders.h b/include/media/BufferProviders.h
new file mode 120000
index 0000000..a1fd855
--- /dev/null
+++ b/include/media/BufferProviders.h
@@ -0,0 +1 @@
+../../media/libmedia/include/BufferProviders.h
\ No newline at end of file
diff --git a/include/media/BufferingSettings.h b/include/media/BufferingSettings.h
new file mode 120000
index 0000000..fb4ec97
--- /dev/null
+++ b/include/media/BufferingSettings.h
@@ -0,0 +1 @@
+../../media/libmedia/include/BufferingSettings.h
\ No newline at end of file
diff --git a/include/media/CasImpl.h b/include/media/CasImpl.h
new file mode 100644
index 0000000..80c901e
--- /dev/null
+++ b/include/media/CasImpl.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef CAS_IMPL_H_
+#define CAS_IMPL_H_
+
+#include <media/stagefright/foundation/ABase.h>
+#include <android/media/BnCas.h>
+
+namespace android {
+namespace media {
+class ICasListener;
+}
+using namespace media;
+using namespace MediaCas;
+using binder::Status;
+class CasPlugin;
+class SharedLibrary;
+
+class CasImpl : public BnCas {
+public:
+    CasImpl(const sp<ICasListener> &listener);
+    virtual ~CasImpl();
+
+    static void OnEvent(
+            void *appData,
+            int32_t event,
+            int32_t arg,
+            uint8_t *data,
+            size_t size);
+
+    void init(const sp<SharedLibrary>& library, CasPlugin *plugin);
+    void onEvent(
+            int32_t event,
+            int32_t arg,
+            uint8_t *data,
+            size_t size);
+
+    // ICas inherits
+
+    virtual Status setPrivateData(
+            const CasData& pvtData) override;
+
+    virtual Status openSession(
+            int32_t program_number, CasSessionId* _aidl_return) override;
+
+    virtual Status openSessionForStream(
+            int32_t program_number,
+            int32_t elementary_PID,
+            CasSessionId* _aidl_return) override;
+
+    virtual Status closeSession(const CasSessionId& sessionId) override;
+
+    virtual Status setSessionPrivateData(
+            const CasSessionId& sessionId,
+            const CasData& pvtData) override;
+
+    virtual Status processEcm(
+            const CasSessionId& sessionId, const ParcelableCasData& ecm) override;
+
+    virtual Status processEmm(const ParcelableCasData& emm) override;
+
+    virtual Status sendEvent(
+            int32_t event, int32_t arg, const ::std::unique_ptr<CasData> &eventData) override;
+
+    virtual Status provision(const String16& provisionString) override;
+
+    virtual Status refreshEntitlements(
+            int32_t refreshType, const ::std::unique_ptr<CasData> &refreshData) override;
+
+    virtual Status release() override;
+
+private:
+    sp<SharedLibrary> mLibrary;
+    CasPlugin *mPlugin;
+    sp<ICasListener> mListener;
+
+    DISALLOW_EVIL_CONSTRUCTORS(CasImpl);
+};
+
+} // namespace android
+
+#endif // CAS_IMPL_H_
diff --git a/include/media/CharacterEncodingDetector.h b/include/media/CharacterEncodingDetector.h
new file mode 120000
index 0000000..f23ed4c
--- /dev/null
+++ b/include/media/CharacterEncodingDetector.h
@@ -0,0 +1 @@
+../../media/libmedia/include/CharacterEncodingDetector.h
\ No newline at end of file
diff --git a/include/media/Crypto.h b/include/media/Crypto.h
new file mode 120000
index 0000000..778f6fe
--- /dev/null
+++ b/include/media/Crypto.h
@@ -0,0 +1 @@
+../../media/libmedia/include/Crypto.h
\ No newline at end of file
diff --git a/include/media/CryptoHal.h b/include/media/CryptoHal.h
new file mode 120000
index 0000000..81f31f5
--- /dev/null
+++ b/include/media/CryptoHal.h
@@ -0,0 +1 @@
+../../media/libmedia/include/CryptoHal.h
\ No newline at end of file
diff --git a/include/media/DescramblerImpl.h b/include/media/DescramblerImpl.h
new file mode 100644
index 0000000..c1c79b3
--- /dev/null
+++ b/include/media/DescramblerImpl.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef DESCRAMBLER_IMPL_H_
+#define DESCRAMBLER_IMPL_H_
+
+#include <media/stagefright/foundation/ABase.h>
+#include <android/media/BnDescrambler.h>
+
+namespace android {
+using namespace media;
+using namespace MediaDescrambler;
+using binder::Status;
+class DescramblerPlugin;
+class SharedLibrary;
+
+class DescramblerImpl : public BnDescrambler {
+public:
+    DescramblerImpl(const sp<SharedLibrary>& library, DescramblerPlugin *plugin);
+    virtual ~DescramblerImpl();
+
+    virtual Status setMediaCasSession(
+            const CasSessionId& sessionId) override;
+
+    virtual Status requiresSecureDecoderComponent(
+            const String16& mime, bool *result) override;
+
+    virtual Status descramble(
+            const DescrambleInfo& descrambleInfo, int32_t *result) override;
+
+    virtual Status release() override;
+
+private:
+    sp<SharedLibrary> mLibrary;
+    DescramblerPlugin *mPlugin;
+
+    DISALLOW_EVIL_CONSTRUCTORS(DescramblerImpl);
+};
+
+} // namespace android
+
+#endif // DESCRAMBLER_IMPL_H_
diff --git a/include/media/Drm.h b/include/media/Drm.h
new file mode 120000
index 0000000..d9bfa5c
--- /dev/null
+++ b/include/media/Drm.h
@@ -0,0 +1 @@
+../../media/libmedia/include/Drm.h
\ No newline at end of file
diff --git a/include/media/DrmHal.h b/include/media/DrmHal.h
new file mode 120000
index 0000000..21ba37b
--- /dev/null
+++ b/include/media/DrmHal.h
@@ -0,0 +1 @@
+../../media/libmedia/include/DrmHal.h
\ No newline at end of file
diff --git a/include/media/DrmSessionClientInterface.h b/include/media/DrmSessionClientInterface.h
new file mode 120000
index 0000000..72090a3
--- /dev/null
+++ b/include/media/DrmSessionClientInterface.h
@@ -0,0 +1 @@
+../../media/libmedia/include/DrmSessionClientInterface.h
\ No newline at end of file
diff --git a/include/media/DrmSessionManager.h b/include/media/DrmSessionManager.h
new file mode 120000
index 0000000..47200f7
--- /dev/null
+++ b/include/media/DrmSessionManager.h
@@ -0,0 +1 @@
+../../media/libmedia/include/DrmSessionManager.h
\ No newline at end of file
diff --git a/include/media/EffectsFactoryApi.h b/include/media/EffectsFactoryApi.h
new file mode 120000
index 0000000..2431dfb
--- /dev/null
+++ b/include/media/EffectsFactoryApi.h
@@ -0,0 +1 @@
+../../media/libeffects/factory/include/EffectsFactoryApi.h
\ No newline at end of file
diff --git a/include/media/ExtendedAudioBufferProvider.h b/include/media/ExtendedAudioBufferProvider.h
new file mode 120000
index 0000000..9497be1
--- /dev/null
+++ b/include/media/ExtendedAudioBufferProvider.h
@@ -0,0 +1 @@
+../../media/libmedia/include/ExtendedAudioBufferProvider.h
\ No newline at end of file
diff --git a/include/media/IAudioFlinger.h b/include/media/IAudioFlinger.h
new file mode 120000
index 0000000..310fd0d
--- /dev/null
+++ b/include/media/IAudioFlinger.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/IAudioFlinger.h
\ No newline at end of file
diff --git a/include/media/IAudioFlingerClient.h b/include/media/IAudioFlingerClient.h
new file mode 120000
index 0000000..d27389e
--- /dev/null
+++ b/include/media/IAudioFlingerClient.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/IAudioFlingerClient.h
\ No newline at end of file
diff --git a/include/media/IAudioPolicyService.h b/include/media/IAudioPolicyService.h
new file mode 120000
index 0000000..8ef16e2
--- /dev/null
+++ b/include/media/IAudioPolicyService.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/IAudioPolicyService.h
\ No newline at end of file
diff --git a/include/media/IAudioPolicyServiceClient.h b/include/media/IAudioPolicyServiceClient.h
new file mode 120000
index 0000000..26f6790
--- /dev/null
+++ b/include/media/IAudioPolicyServiceClient.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/IAudioPolicyServiceClient.h
\ No newline at end of file
diff --git a/include/media/IAudioRecord.h b/include/media/IAudioRecord.h
new file mode 120000
index 0000000..520d44e
--- /dev/null
+++ b/include/media/IAudioRecord.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/IAudioRecord.h
\ No newline at end of file
diff --git a/include/media/IAudioTrack.h b/include/media/IAudioTrack.h
new file mode 120000
index 0000000..afa6bf4
--- /dev/null
+++ b/include/media/IAudioTrack.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/IAudioTrack.h
\ No newline at end of file
diff --git a/include/media/ICrypto.h b/include/media/ICrypto.h
new file mode 120000
index 0000000..53c547a
--- /dev/null
+++ b/include/media/ICrypto.h
@@ -0,0 +1 @@
+../../media/libmedia/include/ICrypto.h
\ No newline at end of file
diff --git a/include/media/IDataSource.h b/include/media/IDataSource.h
new file mode 120000
index 0000000..7ac813f
--- /dev/null
+++ b/include/media/IDataSource.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IDataSource.h
\ No newline at end of file
diff --git a/include/media/IDrm.h b/include/media/IDrm.h
new file mode 120000
index 0000000..eb2f0ec
--- /dev/null
+++ b/include/media/IDrm.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IDrm.h
\ No newline at end of file
diff --git a/include/media/IDrmClient.h b/include/media/IDrmClient.h
new file mode 120000
index 0000000..4d8b50c
--- /dev/null
+++ b/include/media/IDrmClient.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IDrmClient.h
\ No newline at end of file
diff --git a/include/media/IEffect.h b/include/media/IEffect.h
new file mode 120000
index 0000000..72d715d
--- /dev/null
+++ b/include/media/IEffect.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/IEffect.h
\ No newline at end of file
diff --git a/include/media/IEffectClient.h b/include/media/IEffectClient.h
new file mode 120000
index 0000000..0614d8a
--- /dev/null
+++ b/include/media/IEffectClient.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/IEffectClient.h
\ No newline at end of file
diff --git a/include/media/IHDCP.h b/include/media/IHDCP.h
new file mode 120000
index 0000000..f1e112e
--- /dev/null
+++ b/include/media/IHDCP.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IHDCP.h
\ No newline at end of file
diff --git a/include/media/IMediaAnalyticsService.h b/include/media/IMediaAnalyticsService.h
new file mode 120000
index 0000000..97915e4
--- /dev/null
+++ b/include/media/IMediaAnalyticsService.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaAnalyticsService.h
\ No newline at end of file
diff --git a/include/media/IMediaCodecList.h b/include/media/IMediaCodecList.h
new file mode 120000
index 0000000..2e30503
--- /dev/null
+++ b/include/media/IMediaCodecList.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaCodecList.h
\ No newline at end of file
diff --git a/include/media/IMediaCodecService.h b/include/media/IMediaCodecService.h
new file mode 120000
index 0000000..5103277
--- /dev/null
+++ b/include/media/IMediaCodecService.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaCodecService.h
\ No newline at end of file
diff --git a/include/media/IMediaDeathNotifier.h b/include/media/IMediaDeathNotifier.h
new file mode 120000
index 0000000..74b1656
--- /dev/null
+++ b/include/media/IMediaDeathNotifier.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaDeathNotifier.h
\ No newline at end of file
diff --git a/include/media/IMediaDrmService.h b/include/media/IMediaDrmService.h
new file mode 120000
index 0000000..6efbc48
--- /dev/null
+++ b/include/media/IMediaDrmService.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaDrmService.h
\ No newline at end of file
diff --git a/include/media/IMediaExtractor.h b/include/media/IMediaExtractor.h
new file mode 120000
index 0000000..c17c4eb
--- /dev/null
+++ b/include/media/IMediaExtractor.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaExtractor.h
\ No newline at end of file
diff --git a/include/media/IMediaExtractorService.h b/include/media/IMediaExtractorService.h
new file mode 120000
index 0000000..1e6e8b4
--- /dev/null
+++ b/include/media/IMediaExtractorService.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaExtractorService.h
\ No newline at end of file
diff --git a/include/media/IMediaHTTPConnection.h b/include/media/IMediaHTTPConnection.h
new file mode 120000
index 0000000..9e544fe
--- /dev/null
+++ b/include/media/IMediaHTTPConnection.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaHTTPConnection.h
\ No newline at end of file
diff --git a/include/media/IMediaHTTPService.h b/include/media/IMediaHTTPService.h
new file mode 120000
index 0000000..6312e06
--- /dev/null
+++ b/include/media/IMediaHTTPService.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaHTTPService.h
\ No newline at end of file
diff --git a/include/media/IMediaLogService.h b/include/media/IMediaLogService.h
new file mode 120000
index 0000000..7a822dd
--- /dev/null
+++ b/include/media/IMediaLogService.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaLogService.h
\ No newline at end of file
diff --git a/include/media/IMediaMetadataRetriever.h b/include/media/IMediaMetadataRetriever.h
new file mode 120000
index 0000000..c2dd811
--- /dev/null
+++ b/include/media/IMediaMetadataRetriever.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaMetadataRetriever.h
\ No newline at end of file
diff --git a/include/media/IMediaPlayer.h b/include/media/IMediaPlayer.h
new file mode 120000
index 0000000..a38baf4
--- /dev/null
+++ b/include/media/IMediaPlayer.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaPlayer.h
\ No newline at end of file
diff --git a/include/media/IMediaPlayerClient.h b/include/media/IMediaPlayerClient.h
new file mode 120000
index 0000000..1c27dee
--- /dev/null
+++ b/include/media/IMediaPlayerClient.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaPlayerClient.h
\ No newline at end of file
diff --git a/include/media/IMediaPlayerService.h b/include/media/IMediaPlayerService.h
new file mode 120000
index 0000000..08a6a98
--- /dev/null
+++ b/include/media/IMediaPlayerService.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaPlayerService.h
\ No newline at end of file
diff --git a/include/media/IMediaRecorder.h b/include/media/IMediaRecorder.h
new file mode 120000
index 0000000..c8b8b29
--- /dev/null
+++ b/include/media/IMediaRecorder.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaRecorder.h
\ No newline at end of file
diff --git a/include/media/IMediaRecorderClient.h b/include/media/IMediaRecorderClient.h
new file mode 120000
index 0000000..ab703aa
--- /dev/null
+++ b/include/media/IMediaRecorderClient.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaRecorderClient.h
\ No newline at end of file
diff --git a/include/media/IMediaSource.h b/include/media/IMediaSource.h
new file mode 120000
index 0000000..1c3d8fe
--- /dev/null
+++ b/include/media/IMediaSource.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IMediaSource.h
\ No newline at end of file
diff --git a/include/media/IOMX.h b/include/media/IOMX.h
new file mode 120000
index 0000000..989d9b2
--- /dev/null
+++ b/include/media/IOMX.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IOMX.h
\ No newline at end of file
diff --git a/include/media/IRemoteDisplay.h b/include/media/IRemoteDisplay.h
new file mode 120000
index 0000000..5aa58b9
--- /dev/null
+++ b/include/media/IRemoteDisplay.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IRemoteDisplay.h
\ No newline at end of file
diff --git a/include/media/IRemoteDisplayClient.h b/include/media/IRemoteDisplayClient.h
new file mode 120000
index 0000000..2d212e7
--- /dev/null
+++ b/include/media/IRemoteDisplayClient.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IRemoteDisplayClient.h
\ No newline at end of file
diff --git a/include/media/IResourceManagerClient.h b/include/media/IResourceManagerClient.h
new file mode 120000
index 0000000..1531ae2
--- /dev/null
+++ b/include/media/IResourceManagerClient.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IResourceManagerClient.h
\ No newline at end of file
diff --git a/include/media/IResourceManagerService.h b/include/media/IResourceManagerService.h
new file mode 120000
index 0000000..007aecb
--- /dev/null
+++ b/include/media/IResourceManagerService.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IResourceManagerService.h
\ No newline at end of file
diff --git a/include/media/IStreamSource.h b/include/media/IStreamSource.h
new file mode 120000
index 0000000..90dbbf2
--- /dev/null
+++ b/include/media/IStreamSource.h
@@ -0,0 +1 @@
+../../media/libmedia/include/IStreamSource.h
\ No newline at end of file
diff --git a/include/media/JetPlayer.h b/include/media/JetPlayer.h
new file mode 120000
index 0000000..cabfb79
--- /dev/null
+++ b/include/media/JetPlayer.h
@@ -0,0 +1 @@
+../../media/libmedia/include/JetPlayer.h
\ No newline at end of file
diff --git a/include/media/LinearMap.h b/include/media/LinearMap.h
new file mode 120000
index 0000000..3e89686
--- /dev/null
+++ b/include/media/LinearMap.h
@@ -0,0 +1 @@
+../../media/libmedia/include/LinearMap.h
\ No newline at end of file
diff --git a/include/media/MediaAnalyticsItem.h b/include/media/MediaAnalyticsItem.h
new file mode 120000
index 0000000..71957a5
--- /dev/null
+++ b/include/media/MediaAnalyticsItem.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MediaAnalyticsItem.h
\ No newline at end of file
diff --git a/include/media/MediaCasDefs.h b/include/media/MediaCasDefs.h
new file mode 100644
index 0000000..8c5a967
--- /dev/null
+++ b/include/media/MediaCasDefs.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef MEDIA_CAS_DEFS_H_
+#define MEDIA_CAS_DEFS_H_
+
+#include <binder/Parcel.h>
+#include <media/cas/CasAPI.h>
+#include <media/cas/DescramblerAPI.h>
+#include <media/stagefright/foundation/ABase.h>
+
+namespace android {
+class IMemory;
+namespace media {
+
+namespace MediaCas {
+class ParcelableCasData : public CasData,
+                          public Parcelable {
+public:
+    ParcelableCasData() {}
+    ParcelableCasData(const uint8_t *data, size_t size) :
+        CasData(data, data + size) {}
+    virtual ~ParcelableCasData() {}
+    status_t readFromParcel(const Parcel* parcel) override;
+    status_t writeToParcel(Parcel* parcel) const override;
+
+private:
+    DISALLOW_EVIL_CONSTRUCTORS(ParcelableCasData);
+};
+
+class ParcelableCasPluginDescriptor : public Parcelable {
+public:
+    ParcelableCasPluginDescriptor(int32_t CA_system_id, const char *name)
+        : mCASystemId(CA_system_id), mName(name) {}
+
+    ParcelableCasPluginDescriptor() : mCASystemId(0) {}
+
+    ParcelableCasPluginDescriptor(ParcelableCasPluginDescriptor&& desc) = default;
+
+    virtual ~ParcelableCasPluginDescriptor() {}
+
+    status_t readFromParcel(const Parcel* parcel) override;
+    status_t writeToParcel(Parcel* parcel) const override;
+
+private:
+    int32_t mCASystemId;
+    String16 mName;
+    DISALLOW_EVIL_CONSTRUCTORS(ParcelableCasPluginDescriptor);
+};
+}
+
+namespace MediaDescrambler {
+class DescrambleInfo : public Parcelable {
+public:
+    enum DestinationType {
+        kDestinationTypeVmPointer,    // non-secure
+        kDestinationTypeNativeHandle  // secure
+    };
+
+    DestinationType dstType;
+    DescramblerPlugin::ScramblingControl scramblingControl;
+    size_t numSubSamples;
+    DescramblerPlugin::SubSample *subSamples;
+    sp<IMemory> srcMem;
+    int32_t srcOffset;
+    void *dstPtr;
+    int32_t dstOffset;
+
+    DescrambleInfo();
+    virtual ~DescrambleInfo();
+    status_t readFromParcel(const Parcel* parcel) override;
+    status_t writeToParcel(Parcel* parcel) const override;
+
+private:
+
+    DISALLOW_EVIL_CONSTRUCTORS(DescrambleInfo);
+};
+}
+
+} // namespace media
+} // namespace android
+
+
+#endif // MEDIA_CAS_DEFS_H_
diff --git a/include/media/MediaCodecBuffer.h b/include/media/MediaCodecBuffer.h
new file mode 120000
index 0000000..60b7e70
--- /dev/null
+++ b/include/media/MediaCodecBuffer.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MediaCodecBuffer.h
\ No newline at end of file
diff --git a/include/media/MediaCodecInfo.h b/include/media/MediaCodecInfo.h
new file mode 120000
index 0000000..22b10bb
--- /dev/null
+++ b/include/media/MediaCodecInfo.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MediaCodecInfo.h
\ No newline at end of file
diff --git a/include/media/MediaDefs.h b/include/media/MediaDefs.h
new file mode 120000
index 0000000..993729d
--- /dev/null
+++ b/include/media/MediaDefs.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MediaDefs.h
\ No newline at end of file
diff --git a/include/media/MediaMetadataRetrieverInterface.h b/include/media/MediaMetadataRetrieverInterface.h
new file mode 120000
index 0000000..a09f9bb
--- /dev/null
+++ b/include/media/MediaMetadataRetrieverInterface.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MediaMetadataRetrieverInterface.h
\ No newline at end of file
diff --git a/include/media/MediaPlayerInterface.h b/include/media/MediaPlayerInterface.h
new file mode 120000
index 0000000..9b2e1c7
--- /dev/null
+++ b/include/media/MediaPlayerInterface.h
@@ -0,0 +1 @@
+../../media/libmediaplayerservice/include/MediaPlayerInterface.h
\ No newline at end of file
diff --git a/include/media/MediaProfiles.h b/include/media/MediaProfiles.h
new file mode 120000
index 0000000..86958e4
--- /dev/null
+++ b/include/media/MediaProfiles.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MediaProfiles.h
\ No newline at end of file
diff --git a/include/media/MediaRecorderBase.h b/include/media/MediaRecorderBase.h
new file mode 120000
index 0000000..6080258
--- /dev/null
+++ b/include/media/MediaRecorderBase.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MediaRecorderBase.h
\ No newline at end of file
diff --git a/include/media/MediaResource.h b/include/media/MediaResource.h
new file mode 120000
index 0000000..aaf931a
--- /dev/null
+++ b/include/media/MediaResource.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MediaResource.h
\ No newline at end of file
diff --git a/include/media/MediaResourcePolicy.h b/include/media/MediaResourcePolicy.h
new file mode 120000
index 0000000..d56b09f
--- /dev/null
+++ b/include/media/MediaResourcePolicy.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MediaResourcePolicy.h
\ No newline at end of file
diff --git a/include/media/MemoryLeakTrackUtil.h b/include/media/MemoryLeakTrackUtil.h
new file mode 120000
index 0000000..cfeac14
--- /dev/null
+++ b/include/media/MemoryLeakTrackUtil.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MemoryLeakTrackUtil.h
\ No newline at end of file
diff --git a/include/media/Metadata.h b/include/media/Metadata.h
new file mode 120000
index 0000000..4a5893d
--- /dev/null
+++ b/include/media/Metadata.h
@@ -0,0 +1 @@
+../../media/libmedia/include/Metadata.h
\ No newline at end of file
diff --git a/include/media/MidiDeviceInfo.h b/include/media/MidiDeviceInfo.h
new file mode 120000
index 0000000..55ac9f5
--- /dev/null
+++ b/include/media/MidiDeviceInfo.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MidiDeviceInfo.h
\ No newline at end of file
diff --git a/include/media/MidiIoWrapper.h b/include/media/MidiIoWrapper.h
new file mode 120000
index 0000000..a3fe892
--- /dev/null
+++ b/include/media/MidiIoWrapper.h
@@ -0,0 +1 @@
+../../media/libmedia/include/MidiIoWrapper.h
\ No newline at end of file
diff --git a/include/media/Modulo.h b/include/media/Modulo.h
new file mode 120000
index 0000000..58f31a4
--- /dev/null
+++ b/include/media/Modulo.h
@@ -0,0 +1 @@
+../../media/libmedia/include/Modulo.h
\ No newline at end of file
diff --git a/include/media/OMXBuffer.h b/include/media/OMXBuffer.h
new file mode 120000
index 0000000..9defe79
--- /dev/null
+++ b/include/media/OMXBuffer.h
@@ -0,0 +1 @@
+../../media/libmedia/include/OMXBuffer.h
\ No newline at end of file
diff --git a/include/media/OMXFenceParcelable.h b/include/media/OMXFenceParcelable.h
new file mode 120000
index 0000000..2e996dd
--- /dev/null
+++ b/include/media/OMXFenceParcelable.h
@@ -0,0 +1 @@
+../../media/libmedia/include/OMXFenceParcelable.h
\ No newline at end of file
diff --git a/include/media/PluginLoader.h b/include/media/PluginLoader.h
new file mode 120000
index 0000000..f67f2c4
--- /dev/null
+++ b/include/media/PluginLoader.h
@@ -0,0 +1 @@
+../../media/libmedia/include/PluginLoader.h
\ No newline at end of file
diff --git a/include/media/RecordBufferConverter.h b/include/media/RecordBufferConverter.h
new file mode 120000
index 0000000..b9ee8df
--- /dev/null
+++ b/include/media/RecordBufferConverter.h
@@ -0,0 +1 @@
+../../media/libmedia/include/RecordBufferConverter.h
\ No newline at end of file
diff --git a/include/media/RingBuffer.h b/include/media/RingBuffer.h
new file mode 120000
index 0000000..84f4943
--- /dev/null
+++ b/include/media/RingBuffer.h
@@ -0,0 +1 @@
+../../media/libmedia/include/RingBuffer.h
\ No newline at end of file
diff --git a/include/media/SharedLibrary.h b/include/media/SharedLibrary.h
new file mode 120000
index 0000000..a2a040f
--- /dev/null
+++ b/include/media/SharedLibrary.h
@@ -0,0 +1 @@
+../../media/libmedia/include/SharedLibrary.h
\ No newline at end of file
diff --git a/include/media/SingleStateQueue.h b/include/media/SingleStateQueue.h
new file mode 120000
index 0000000..7dda0d8
--- /dev/null
+++ b/include/media/SingleStateQueue.h
@@ -0,0 +1 @@
+../../media/libmedia/include/SingleStateQueue.h
\ No newline at end of file
diff --git a/include/media/StringArray.h b/include/media/StringArray.h
new file mode 120000
index 0000000..5061652
--- /dev/null
+++ b/include/media/StringArray.h
@@ -0,0 +1 @@
+../../media/libmedia/include/StringArray.h
\ No newline at end of file
diff --git a/include/media/ToneGenerator.h b/include/media/ToneGenerator.h
new file mode 120000
index 0000000..f00ee2d
--- /dev/null
+++ b/include/media/ToneGenerator.h
@@ -0,0 +1 @@
+../../media/libaudioclient/include/ToneGenerator.h
\ No newline at end of file
diff --git a/include/media/TypeConverter.h b/include/media/TypeConverter.h
new file mode 120000
index 0000000..9109aaa
--- /dev/null
+++ b/include/media/TypeConverter.h
@@ -0,0 +1 @@
+../../media/libmedia/include/TypeConverter.h
\ No newline at end of file
diff --git a/include/media/Visualizer.h b/include/media/Visualizer.h
new file mode 120000
index 0000000..fca8b86
--- /dev/null
+++ b/include/media/Visualizer.h
@@ -0,0 +1 @@
+../../media/libmedia/include/Visualizer.h
\ No newline at end of file
diff --git a/include/media/VolumeShaper.h b/include/media/VolumeShaper.h
index acb22ab..f5a74d8 100644
--- a/include/media/VolumeShaper.h
+++ b/include/media/VolumeShaper.h
@@ -17,6 +17,7 @@
 #ifndef ANDROID_VOLUME_SHAPER_H
 #define ANDROID_VOLUME_SHAPER_H
 
+#include <cmath>
 #include <list>
 #include <math.h>
 #include <sstream>
@@ -94,6 +95,14 @@
             , mId(-1) {
         }
 
+        Configuration(const Configuration &configuration)
+            : Interpolator<S, T>(*static_cast<const Interpolator<S, T> *>(&configuration))
+            , mType(configuration.mType)
+            , mOptionFlags(configuration.mOptionFlags)
+            , mDurationMs(configuration.mDurationMs)
+            , mId(configuration.mId) {
+        }
+
         Type getType() const {
             return mType;
         }
@@ -281,18 +290,28 @@
             FLAG_TERMINATE = (1 << 1),
             FLAG_JOIN      = (1 << 2),
             FLAG_DELAY     = (1 << 3),
+            FLAG_CREATE_IF_NECESSARY = (1 << 4),
 
-            FLAG_ALL       = (FLAG_REVERSE | FLAG_TERMINATE | FLAG_JOIN | FLAG_DELAY),
+            FLAG_ALL       = (FLAG_REVERSE | FLAG_TERMINATE | FLAG_JOIN | FLAG_DELAY
+                            | FLAG_CREATE_IF_NECESSARY),
         };
 
         Operation()
-            : mFlags(FLAG_NONE)
-            , mReplaceId(-1) {
+            : Operation(FLAG_NONE, -1 /* replaceId */) {
         }
 
         explicit Operation(Flag flags, int replaceId)
+            : Operation(flags, replaceId, std::numeric_limits<S>::quiet_NaN() /* xOffset */) {
+        }
+
+        Operation(const Operation &operation)
+            : Operation(operation.mFlags, operation.mReplaceId, operation.mXOffset) {
+        }
+
+        explicit Operation(Flag flags, int replaceId, S xOffset)
             : mFlags(flags)
-            , mReplaceId(replaceId) {
+            , mReplaceId(replaceId)
+            , mXOffset(xOffset) {
         }
 
         int32_t getReplaceId() const {
@@ -303,6 +322,14 @@
             mReplaceId = replaceId;
         }
 
+        S getXOffset() const {
+            return mXOffset;
+        }
+
+        void setXOffset(S xOffset) {
+            mXOffset = xOffset;
+        }
+
         Flag getFlags() const {
             return mFlags;
         }
@@ -319,13 +346,15 @@
         status_t writeToParcel(Parcel *parcel) const {
             if (parcel == nullptr) return BAD_VALUE;
             return parcel->writeInt32((int32_t)mFlags)
-                    ?: parcel->writeInt32(mReplaceId);
+                    ?: parcel->writeInt32(mReplaceId)
+                    ?: parcel->writeFloat(mXOffset);
         }
 
         status_t readFromParcel(const Parcel &parcel) {
             int32_t flags;
             return parcel.readInt32(&flags)
                     ?: parcel.readInt32(&mReplaceId)
+                    ?: parcel.readFloat(&mXOffset)
                     ?: setFlags((Flag)flags);
         }
 
@@ -333,12 +362,14 @@
             std::stringstream ss;
             ss << "mFlags: " << mFlags << std::endl;
             ss << "mReplaceId: " << mReplaceId << std::endl;
+            ss << "mXOffset: " << mXOffset << std::endl;
             return ss.str();
         }
 
     private:
         Flag mFlags;
         int32_t mReplaceId;
+        S mXOffset;
     }; // Operation
 
     // must match with VolumeShaper.java in frameworks/base
@@ -446,14 +477,6 @@
         return convertTimespecToUs(tv);
     }
 
-    Translate<S> mXTranslate;
-    Translate<T> mYTranslate;
-    sp<VolumeShaper::Configuration> mConfiguration;
-    sp<VolumeShaper::Operation> mOperation;
-    int64_t mStartFrame;
-    T mLastVolume;
-    S mXOffset;
-
     // TODO: Since we pass configuration and operation as shared pointers
     // there is a potential risk that the caller may modify these after
     // delivery.  Currently, we don't require copies made here.
@@ -464,7 +487,8 @@
         , mOperation(operation)         // ditto
         , mStartFrame(-1)
         , mLastVolume(T(1))
-        , mXOffset(0.f) {
+        , mLastXOffset(0.f)
+        , mDelayXOffset(std::numeric_limits<S>::quiet_NaN()) {
         if (configuration.get() != nullptr
                 && (getFlags() & VolumeShaper::Operation::FLAG_DELAY) == 0) {
             mLastVolume = configuration->first().second;
@@ -476,9 +500,11 @@
                         / (mConfiguration->getDurationMs() * 0.001 * sampleRate);
         const double minScale = 1. / INT64_MAX;
         scale = std::max(scale, minScale);
-        VS_LOG("update position: scale %lf  frameCount:%lld, sampleRate:%lf",
-                scale, (long long) startFrame, sampleRate);
-        mXTranslate.setOffset(startFrame - mConfiguration->first().first / scale);
+        const S xOffset = std::isnan(mDelayXOffset) ? mConfiguration->first().first : mDelayXOffset;
+        VS_LOG("update position: scale %lf  frameCount:%lld, sampleRate:%lf, xOffset:%f",
+                scale, (long long) startFrame, sampleRate, xOffset);
+
+        mXTranslate.setOffset(startFrame - xOffset / scale);
         mXTranslate.setScale(scale);
         VS_LOG("translate: %s", mXTranslate.toString().c_str());
     }
@@ -490,20 +516,19 @@
     }
 
     sp<VolumeShaper::State> getState() const {
-        return new VolumeShaper::State(mLastVolume, mXOffset);
+        return new VolumeShaper::State(mLastVolume, mLastXOffset);
     }
 
-    std::pair<T, bool> getVolume(int64_t trackFrameCount, double trackSampleRate) {
-        if (mConfiguration.get() == nullptr || mConfiguration->empty()) {
-            ALOGE("nonexistent VolumeShaper, removing");
-            mLastVolume = T(1);
-            mXOffset = 0.f;
-            return std::make_pair(T(1), true);
-        }
+    void setDelayXOffset(S xOffset) {
+        mDelayXOffset = xOffset;
+    }
+
+    std::pair<T /* volume */, bool /* active */> getVolume(
+            int64_t trackFrameCount, double trackSampleRate) {
         if ((getFlags() & VolumeShaper::Operation::FLAG_DELAY) != 0) {
             VS_LOG("delayed VolumeShaper, ignoring");
             mLastVolume = T(1);
-            mXOffset = 0.;
+            mLastXOffset = 0.;
             return std::make_pair(T(1), false);
         }
         const bool clockTime = (mConfiguration->getOptionFlags()
@@ -524,7 +549,7 @@
             x = 1.f - x;
             VS_LOG("reversing to %f", x);
             if (x < mConfiguration->first().first) {
-                mXOffset = 1.f;
+                mLastXOffset = 1.f;
                 const T volume = mConfiguration->adjustVolume(
                         mConfiguration->first().second);  // persist last value
                 VS_LOG("persisting volume %f", volume);
@@ -532,18 +557,18 @@
                 return std::make_pair(volume, false);
             }
             if (x > mConfiguration->last().first) {
-                mXOffset = 0.f;
+                mLastXOffset = 0.f;
                 mLastVolume = 1.f;
-                return std::make_pair(T(1), false); // too early
+                return std::make_pair(T(1), true); // too early
             }
         } else {
             if (x < mConfiguration->first().first) {
-                mXOffset = 0.f;
+                mLastXOffset = 0.f;
                 mLastVolume = 1.f;
-                return std::make_pair(T(1), false); // too early
+                return std::make_pair(T(1), true); // too early
             }
             if (x > mConfiguration->last().first) {
-                mXOffset = 1.f;
+                mLastXOffset = 1.f;
                 const T volume = mConfiguration->adjustVolume(
                         mConfiguration->last().second);  // persist last value
                 VS_LOG("persisting volume %f", volume);
@@ -551,21 +576,19 @@
                 return std::make_pair(volume, false);
             }
         }
-        mXOffset = x;
+        mLastXOffset = x;
         // x contains the location on the volume curve to use.
         const T unscaledVolume = mConfiguration->findY(x);
-        const T volumeChange = mYTranslate(unscaledVolume);
-        const T volume = mConfiguration->adjustVolume(volumeChange);
+        const T volume = mConfiguration->adjustVolume(unscaledVolume); // handle log scale
         VS_LOG("volume: %f  unscaled: %f", volume, unscaledVolume);
         mLastVolume = volume;
-        return std::make_pair(volume, false);
+        return std::make_pair(volume, true);
     }
 
     std::string toString() const {
         std::stringstream ss;
         ss << "StartFrame: " << mStartFrame << std::endl;
         ss << mXTranslate.toString().c_str();
-        ss << mYTranslate.toString().c_str();
         if (mConfiguration.get() == nullptr) {
             ss << "VolumeShaper::Configuration: nullptr" << std::endl;
         } else {
@@ -580,6 +603,14 @@
         }
         return ss.str();
     }
+
+    Translate<S> mXTranslate; // x axis translation from frames (in usec for clock time)
+    sp<VolumeShaper::Configuration> mConfiguration;
+    sp<VolumeShaper::Operation> mOperation;
+    int64_t mStartFrame; // starting frame, non-negative when started (in usec for clock time)
+    T mLastVolume;       // last computed interpolated volume (y-axis)
+    S mLastXOffset;      // last computed interpolated xOffset/time (x-axis)
+    S mDelayXOffset;     // delay xOffset on first volumeshaper start.
 }; // VolumeShaper
 
 // VolumeHandler combines the volume factors of multiple VolumeShapers and handles
@@ -589,14 +620,22 @@
     using S = float;
     using T = float;
 
+    // A volume handler which just keeps track of active VolumeShapers does not need sampleRate.
+    VolumeHandler()
+        : VolumeHandler(0 /* sampleRate */) {
+    }
+
     explicit VolumeHandler(uint32_t sampleRate)
         : mSampleRate((double)sampleRate)
-        , mLastFrame(0) {
+        , mLastFrame(0)
+        , mVolumeShaperIdCounter(VolumeShaper::kSystemIdMax) {
     }
 
     VolumeShaper::Status applyVolumeShaper(
             const sp<VolumeShaper::Configuration> &configuration,
             const sp<VolumeShaper::Operation> &operation) {
+        VS_LOG("applyVolumeShaper:configuration: %s", configuration->toString().c_str());
+        VS_LOG("applyVolumeShaper:operation: %s", operation->toString().c_str());
         AutoMutex _l(mLock);
         if (configuration == nullptr) {
             ALOGE("null configuration");
@@ -614,34 +653,6 @@
         VS_LOG("applyVolumeShaper id: %d", id);
 
         switch (configuration->getType()) {
-        case VolumeShaper::Configuration::TYPE_ID: {
-            VS_LOG("trying to find id: %d", id);
-            auto it = findId_l(id);
-            if (it == mVolumeShapers.end()) {
-                VS_LOG("couldn't find id: %d\n%s", id, this->toString().c_str());
-                return VolumeShaper::Status(INVALID_OPERATION);
-            }
-            if ((it->getFlags() & VolumeShaper::Operation::FLAG_TERMINATE) != 0) {
-                VS_LOG("terminate id: %d", id);
-                mVolumeShapers.erase(it);
-                break;
-            }
-            if ((it->getFlags() & VolumeShaper::Operation::FLAG_REVERSE) !=
-                    (operation->getFlags() & VolumeShaper::Operation::FLAG_REVERSE)) {
-                const S x = it->mXTranslate((T)mLastFrame);
-                VS_LOG("translation: %f", x);
-                // reflect position
-                S target = 1.f - x;
-                if (target < it->mConfiguration->first().first) {
-                    VS_LOG("clamp to start - begin immediately");
-                    target = 0.;
-                }
-                VS_LOG("target: %f", target);
-                it->mXTranslate.setOffset(it->mXTranslate.getOffset()
-                        + (x - target) / it->mXTranslate.getScale());
-            }
-            it->mOperation = operation; // replace the operation
-        } break;
         case VolumeShaper::Configuration::TYPE_SCALE: {
             const int replaceId = operation->getReplaceId();
             if (replaceId >= 0) {
@@ -661,15 +672,65 @@
                     }
                     (void)mVolumeShapers.erase(replaceIt);
                 }
+                operation->setReplaceId(-1);
             }
             // check if we have another of the same id.
             auto oldIt = findId_l(id);
             if (oldIt != mVolumeShapers.end()) {
+                if ((operation->getFlags()
+                        & VolumeShaper::Operation::FLAG_CREATE_IF_NECESSARY) != 0) {
+                    // TODO: move the case to a separate function.
+                    goto HANDLE_TYPE_ID; // no need to create, take over existing id.
+                }
                 ALOGW("duplicate id, removing old %d", id);
                 (void)mVolumeShapers.erase(oldIt);
             }
             // create new VolumeShaper
             mVolumeShapers.emplace_back(configuration, operation);
+        }
+        // fall through to handle the operation
+        HANDLE_TYPE_ID:
+        case VolumeShaper::Configuration::TYPE_ID: {
+            VS_LOG("trying to find id: %d", id);
+            auto it = findId_l(id);
+            if (it == mVolumeShapers.end()) {
+                VS_LOG("couldn't find id: %d", id);
+                return VolumeShaper::Status(INVALID_OPERATION);
+            }
+            if ((it->getFlags() & VolumeShaper::Operation::FLAG_TERMINATE) != 0) {
+                VS_LOG("terminate id: %d", id);
+                mVolumeShapers.erase(it);
+                break;
+            }
+            const bool clockTime = (it->mConfiguration->getOptionFlags()
+                    & VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME) != 0;
+            if ((it->getFlags() & VolumeShaper::Operation::FLAG_REVERSE) !=
+                    (operation->getFlags() & VolumeShaper::Operation::FLAG_REVERSE)) {
+                const int64_t frameCount = clockTime ? VolumeShaper::getNowUs() : mLastFrame;
+                const S x = it->mXTranslate((T)frameCount);
+                VS_LOG("reverse translation: %f", x);
+                // reflect position
+                S target = 1.f - x;
+                if (target < it->mConfiguration->first().first) {
+                    VS_LOG("clamp to start - begin immediately");
+                    target = 0.;
+                }
+                VS_LOG("target reverse: %f", target);
+                it->mXTranslate.setOffset(it->mXTranslate.getOffset()
+                        + (x - target) / it->mXTranslate.getScale());
+            }
+            const S xOffset = operation->getXOffset();
+            if (!std::isnan(xOffset)) {
+                const int64_t frameCount = clockTime ? VolumeShaper::getNowUs() : mLastFrame;
+                const S x = it->mXTranslate((T)frameCount);
+                VS_LOG("xOffset translation: %f", x);
+                const S target = xOffset; // offset
+                VS_LOG("xOffset target x offset: %f", target);
+                it->mXTranslate.setOffset(it->mXTranslate.getOffset()
+                        + (x - target) / it->mXTranslate.getScale());
+                it->setDelayXOffset(xOffset);
+            }
+            it->mOperation = operation; // replace the operation
         } break;
         }
         return VolumeShaper::Status(id);
@@ -679,26 +740,25 @@
         AutoMutex _l(mLock);
         auto it = findId_l(id);
         if (it == mVolumeShapers.end()) {
+            VS_LOG("cannot find state for id: %d", id);
             return nullptr;
         }
         return it->getState();
     }
 
-    T getVolume(int64_t trackFrameCount) {
+    std::pair<T /* volume */, bool /* active */> getVolume(int64_t trackFrameCount) {
         AutoMutex _l(mLock);
         mLastFrame = trackFrameCount;
         T volume(1);
+        size_t activeCount = 0;
         for (auto it = mVolumeShapers.begin(); it != mVolumeShapers.end();) {
             std::pair<T, bool> shaperVolume =
                     it->getVolume(trackFrameCount, mSampleRate);
             volume *= shaperVolume.first;
-            if (shaperVolume.second) {
-                it = mVolumeShapers.erase(it);
-                continue;
-            }
+            activeCount += shaperVolume.second;
             ++it;
         }
-        return volume;
+        return std::make_pair(volume, activeCount != 0);
     }
 
     std::string toString() const {
@@ -712,6 +772,48 @@
         return ss.str();
     }
 
+    void forall(const std::function<VolumeShaper::Status (
+            const sp<VolumeShaper::Configuration> &configuration,
+            const sp<VolumeShaper::Operation> &operation)> &lambda) {
+        AutoMutex _l(mLock);
+        for (const auto &shaper : mVolumeShapers) {
+            VS_LOG("forall applying lambda");
+            (void)lambda(shaper.mConfiguration, shaper.mOperation);
+        }
+    }
+
+    void reset() {
+        AutoMutex _l(mLock);
+        mVolumeShapers.clear();
+        mLastFrame = -1;
+        // keep mVolumeShaperIdCounter as is.
+    }
+
+    // Sets the configuration id if necessary - This is based on the counter
+    // internal to the VolumeHandler.
+    void setIdIfNecessary(const sp<VolumeShaper::Configuration> &configuration) {
+        if (configuration->getType() == VolumeShaper::Configuration::TYPE_SCALE) {
+            const int id = configuration->getId();
+            if (id == -1) {
+                // Reassign to a unique id, skipping system ids.
+                AutoMutex _l(mLock);
+                while (true) {
+                    if (mVolumeShaperIdCounter == INT32_MAX) {
+                        mVolumeShaperIdCounter = VolumeShaper::kSystemIdMax;
+                    } else {
+                        ++mVolumeShaperIdCounter;
+                    }
+                    if (findId_l(mVolumeShaperIdCounter) != mVolumeShapers.end()) {
+                        continue; // collision with an existing id.
+                    }
+                    configuration->setId(mVolumeShaperIdCounter);
+                    ALOGD("setting id to %d", mVolumeShaperIdCounter);
+                    break;
+                }
+            }
+        }
+    }
+
 private:
     std::list<VolumeShaper>::iterator findId_l(int32_t id) {
         std::list<VolumeShaper>::iterator it = mVolumeShapers.begin();
@@ -726,6 +828,7 @@
     mutable Mutex mLock;
     double mSampleRate; // in samples (frames) per second
     int64_t mLastFrame; // logging purpose only
+    int32_t mVolumeShaperIdCounter; // a counter to return a unique volume shaper id.
     std::list<VolumeShaper> mVolumeShapers; // list provides stable iterators on erase
 }; // VolumeHandler
 
diff --git a/include/media/audiohal b/include/media/audiohal
new file mode 120000
index 0000000..37e2c39
--- /dev/null
+++ b/include/media/audiohal
@@ -0,0 +1 @@
+../../media/libaudiohal/include
\ No newline at end of file
diff --git a/include/media/convert.h b/include/media/convert.h
new file mode 120000
index 0000000..3e09482
--- /dev/null
+++ b/include/media/convert.h
@@ -0,0 +1 @@
+../../media/libmedia/include/convert.h
\ No newline at end of file
diff --git a/include/media/mediametadataretriever.h b/include/media/mediametadataretriever.h
new file mode 120000
index 0000000..1992b05
--- /dev/null
+++ b/include/media/mediametadataretriever.h
@@ -0,0 +1 @@
+../../media/libmedia/include/mediametadataretriever.h
\ No newline at end of file
diff --git a/include/media/mediaplayer.h b/include/media/mediaplayer.h
new file mode 120000
index 0000000..2b1d298
--- /dev/null
+++ b/include/media/mediaplayer.h
@@ -0,0 +1 @@
+../../media/libmedia/include/mediaplayer.h
\ No newline at end of file
diff --git a/include/media/mediarecorder.h b/include/media/mediarecorder.h
new file mode 120000
index 0000000..08c826f
--- /dev/null
+++ b/include/media/mediarecorder.h
@@ -0,0 +1 @@
+../../media/libmedia/include/mediarecorder.h
\ No newline at end of file
diff --git a/include/media/mediascanner.h b/include/media/mediascanner.h
new file mode 120000
index 0000000..42c3507
--- /dev/null
+++ b/include/media/mediascanner.h
@@ -0,0 +1 @@
+../../media/libmedia/include/mediascanner.h
\ No newline at end of file
diff --git a/include/media/nbaio b/include/media/nbaio
new file mode 120000
index 0000000..67d0ba6
--- /dev/null
+++ b/include/media/nbaio
@@ -0,0 +1 @@
+../../media/libnbaio/include
\ No newline at end of file
diff --git a/include/media/stagefright b/include/media/stagefright
new file mode 120000
index 0000000..ae324a8
--- /dev/null
+++ b/include/media/stagefright
@@ -0,0 +1 @@
+../../media/libstagefright/include
\ No newline at end of file
diff --git a/media/libaaudio/examples/write_sine/src/write_sine.cpp b/media/libaaudio/examples/write_sine/src/write_sine.cpp
index 9e6268a..511fe94 100644
--- a/media/libaaudio/examples/write_sine/src/write_sine.cpp
+++ b/media/libaaudio/examples/write_sine/src/write_sine.cpp
@@ -59,8 +59,8 @@
     const aaudio_sharing_mode_t requestedSharingMode = AAUDIO_SHARING_MODE_EXCLUSIVE;
     aaudio_sharing_mode_t actualSharingMode = AAUDIO_SHARING_MODE_SHARED;
 
-    AAudioStreamBuilder aaudioBuilder = nullptr;
-    AAudioStream aaudioStream = nullptr;
+    AAudioStreamBuilder *aaudioBuilder = nullptr;
+    AAudioStream *aaudioStream = nullptr;
     aaudio_stream_state_t state = AAUDIO_STREAM_STATE_UNINITIALIZED;
     int32_t framesPerBurst = 0;
     int32_t framesToPlay = 0;
diff --git a/media/libaaudio/examples/write_sine/src/write_sine_threaded.cpp b/media/libaaudio/examples/write_sine/src/write_sine_threaded.cpp
index cc7ba5a..40e5016 100644
--- a/media/libaaudio/examples/write_sine/src/write_sine_threaded.cpp
+++ b/media/libaaudio/examples/write_sine/src/write_sine_threaded.cpp
@@ -217,8 +217,8 @@
     }
 
 private:
-    AAudioStreamBuilder   mBuilder = nullptr;
-    AAudioStream          mStream = nullptr;
+    AAudioStreamBuilder  *mBuilder = nullptr;
+    AAudioStream         *mStream = nullptr;
     float                *mOutputBuffer = nullptr;
     int16_t              *mConversionBuffer = nullptr;
 
diff --git a/media/libaaudio/include/aaudio/AAudio.h b/media/libaaudio/include/aaudio/AAudio.h
index 43b5205..921248a 100644
--- a/media/libaaudio/include/aaudio/AAudio.h
+++ b/media/libaaudio/include/aaudio/AAudio.h
@@ -27,11 +27,8 @@
 extern "C" {
 #endif
 
-typedef struct AAudioStreamStruct * AAudioStream;
-typedef struct AAudioStreamBuilderStruct *  AAudioStreamBuilder;
-
-#define AAUDIO_STREAM_NONE         ((AAudioStream)nullptr)
-#define AAUDIO_STREAM_BUILDER_NONE ((AAudioStreamBuilder)nullptr)
+typedef struct AAudioStreamStruct         AAudioStream;
+typedef struct AAudioStreamBuilderStruct  AAudioStreamBuilder;
 
 #ifndef AAUDIO_API
 #define AAUDIO_API /* export this symbol */
@@ -77,7 +74,7 @@
  *
  * AAudioStreamBuilder_delete() must be called when you are done using the builder.
  */
-AAUDIO_API aaudio_result_t AAudio_createStreamBuilder(AAudioStreamBuilder *builder);
+AAUDIO_API aaudio_result_t AAudio_createStreamBuilder(AAudioStreamBuilder** builder);
 
 /**
  * Request an audio device identified device using an ID.
@@ -88,7 +85,7 @@
  * @param builder reference provided by AAudio_createStreamBuilder()
  * @param deviceId device identifier or AAUDIO_DEVICE_UNSPECIFIED
  */
-AAUDIO_API void AAudioStreamBuilder_setDeviceId(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setDeviceId(AAudioStreamBuilder* builder,
                                                      int32_t deviceId);
 
 /**
@@ -103,7 +100,7 @@
  * Default is AAUDIO_UNSPECIFIED.
 
  */
-AAUDIO_API void AAudioStreamBuilder_setSampleRate(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setSampleRate(AAudioStreamBuilder* builder,
                                                        int32_t sampleRate);
 
 /**
@@ -115,14 +112,14 @@
  *
  * Note, this quantity is sometimes referred to as "channel count".
  */
-AAUDIO_API void AAudioStreamBuilder_setSamplesPerFrame(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setSamplesPerFrame(AAudioStreamBuilder* builder,
                                                    int32_t samplesPerFrame);
 
 /**
  * Request a sample data format, for example AAUDIO_FORMAT_PCM_I16.
  * The application should query for the actual format after the stream is opened.
  */
-AAUDIO_API void AAudioStreamBuilder_setFormat(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setFormat(AAudioStreamBuilder* builder,
                                                    aaudio_audio_format_t format);
 
 /**
@@ -133,7 +130,7 @@
  * @param builder reference provided by AAudio_createStreamBuilder()
  * @param sharingMode AAUDIO_SHARING_MODE_LEGACY or AAUDIO_SHARING_MODE_EXCLUSIVE
  */
-AAUDIO_API void AAudioStreamBuilder_setSharingMode(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setSharingMode(AAudioStreamBuilder* builder,
                                                         aaudio_sharing_mode_t sharingMode);
 
 /**
@@ -142,7 +139,7 @@
  * @param builder reference provided by AAudio_createStreamBuilder()
  * @param direction AAUDIO_DIRECTION_OUTPUT or AAUDIO_DIRECTION_INPUT
  */
-AAUDIO_API void AAudioStreamBuilder_setDirection(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setDirection(AAudioStreamBuilder* builder,
                                                             aaudio_direction_t direction);
 
 /**
@@ -154,7 +151,7 @@
  * @param builder reference provided by AAudio_createStreamBuilder()
  * @param frames the desired buffer capacity in frames or AAUDIO_UNSPECIFIED
  */
-AAUDIO_API void AAudioStreamBuilder_setBufferCapacityInFrames(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setBufferCapacityInFrames(AAudioStreamBuilder* builder,
                                                                  int32_t frames);
 
 /**
@@ -167,8 +164,8 @@
  * @param stream pointer to a variable to receive the new stream reference
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStreamBuilder_openStream(AAudioStreamBuilder builder,
-                                                     AAudioStream *stream);
+AAUDIO_API aaudio_result_t  AAudioStreamBuilder_openStream(AAudioStreamBuilder* builder,
+                                                     AAudioStream** stream);
 
 /**
  * Delete the resources associated with the StreamBuilder.
@@ -176,7 +173,7 @@
  * @param builder reference provided by AAudio_createStreamBuilder()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStreamBuilder_delete(AAudioStreamBuilder builder);
+AAUDIO_API aaudio_result_t  AAudioStreamBuilder_delete(AAudioStreamBuilder* builder);
 
 // ============================================================
 // Stream Control
@@ -188,7 +185,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_close(AAudioStream stream);
+AAUDIO_API aaudio_result_t  AAudioStream_close(AAudioStream* stream);
 
 /**
  * Asynchronously request to start playing the stream. For output streams, one should
@@ -199,7 +196,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_requestStart(AAudioStream stream);
+AAUDIO_API aaudio_result_t  AAudioStream_requestStart(AAudioStream* stream);
 
 /**
  * Asynchronous request for the stream to pause.
@@ -210,7 +207,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_requestPause(AAudioStream stream);
+AAUDIO_API aaudio_result_t  AAudioStream_requestPause(AAudioStream* stream);
 
 /**
  * Asynchronous request for the stream to flush.
@@ -222,7 +219,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_requestFlush(AAudioStream stream);
+AAUDIO_API aaudio_result_t  AAudioStream_requestFlush(AAudioStream* stream);
 
 /**
  * Asynchronous request for the stream to stop.
@@ -232,7 +229,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_requestStop(AAudioStream stream);
+AAUDIO_API aaudio_result_t  AAudioStream_requestStop(AAudioStream* stream);
 
 /**
  * Query the current state of the client, eg. AAUDIO_STREAM_STATE_PAUSING
@@ -245,7 +242,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @param state pointer to a variable that will be set to the current state
  */
-AAUDIO_API aaudio_stream_state_t AAudioStream_getState(AAudioStream stream);
+AAUDIO_API aaudio_stream_state_t AAudioStream_getState(AAudioStream* stream);
 
 /**
  * Wait until the current state no longer matches the input state.
@@ -267,7 +264,7 @@
  * @param timeoutNanoseconds Maximum number of nanoseconds to wait for completion.
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t AAudioStream_waitForStateChange(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_waitForStateChange(AAudioStream* stream,
                                             aaudio_stream_state_t inputState,
                                             aaudio_stream_state_t *nextState,
                                             int64_t timeoutNanoseconds);
@@ -294,7 +291,7 @@
  * @param timeoutNanoseconds Maximum number of nanoseconds to wait for completion.
  * @return The number of frames actually read or a negative error.
  */
-AAUDIO_API aaudio_result_t AAudioStream_read(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_read(AAudioStream* stream,
                                void *buffer,
                                int32_t numFrames,
                                int64_t timeoutNanoseconds);
@@ -317,7 +314,7 @@
  * @param timeoutNanoseconds Maximum number of nanoseconds to wait for completion.
  * @return The number of frames actually written or a negative error.
  */
-AAUDIO_API aaudio_result_t AAudioStream_write(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_write(AAudioStream* stream,
                                const void *buffer,
                                int32_t numFrames,
                                int64_t timeoutNanoseconds);
@@ -327,7 +324,7 @@
 // High priority audio threads
 // ============================================================
 
-typedef void *(aaudio_audio_thread_proc_t)(void *);
+typedef void *(*aaudio_audio_thread_proc_t)(void *);
 
 /**
  * Create a thread associated with a stream. The thread has special properties for
@@ -348,9 +345,9 @@
  * @param arg an argument that will be passed to your thread entry point
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t AAudioStream_createThread(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_createThread(AAudioStream* stream,
                                      int64_t periodNanoseconds,
-                                     aaudio_audio_thread_proc_t *threadProc,
+                                     aaudio_audio_thread_proc_t threadProc,
                                      void *arg);
 
 /**
@@ -361,7 +358,7 @@
  * @param timeoutNanoseconds Maximum number of nanoseconds to wait for completion.
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t AAudioStream_joinThread(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_joinThread(AAudioStream* stream,
                                    void **returnArg,
                                    int64_t timeoutNanoseconds);
 
@@ -385,7 +382,7 @@
  * @param requestedFrames requested number of frames that can be filled without blocking
  * @return actual buffer size in frames or a negative error
  */
-AAUDIO_API aaudio_result_t AAudioStream_setBufferSizeInFrames(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_setBufferSizeInFrames(AAudioStream* stream,
                                                       int32_t requestedFrames);
 
 /**
@@ -394,7 +391,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return buffer size in frames.
  */
-AAUDIO_API int32_t AAudioStream_getBufferSizeInFrames(AAudioStream stream);
+AAUDIO_API int32_t AAudioStream_getBufferSizeInFrames(AAudioStream* stream);
 
 /**
  * Query the number of frames that the application should read or write at
@@ -409,7 +406,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return burst size
  */
-AAUDIO_API int32_t AAudioStream_getFramesPerBurst(AAudioStream stream);
+AAUDIO_API int32_t AAudioStream_getFramesPerBurst(AAudioStream* stream);
 
 /**
  * Query maximum buffer capacity in frames.
@@ -417,7 +414,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return  the buffer capacity in frames
  */
-AAUDIO_API int32_t AAudioStream_getBufferCapacityInFrames(AAudioStream stream);
+AAUDIO_API int32_t AAudioStream_getBufferCapacityInFrames(AAudioStream* stream);
 
 /**
  * An XRun is an Underrun or an Overrun.
@@ -431,13 +428,13 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return the underrun or overrun count
  */
-AAUDIO_API int32_t AAudioStream_getXRunCount(AAudioStream stream);
+AAUDIO_API int32_t AAudioStream_getXRunCount(AAudioStream* stream);
 
 /**
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return actual sample rate
  */
-AAUDIO_API int32_t AAudioStream_getSampleRate(AAudioStream stream);
+AAUDIO_API int32_t AAudioStream_getSampleRate(AAudioStream* stream);
 
 /**
  * The samplesPerFrame is also known as channelCount.
@@ -445,34 +442,32 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return actual samples per frame
  */
-AAUDIO_API int32_t AAudioStream_getSamplesPerFrame(AAudioStream stream);
+AAUDIO_API int32_t AAudioStream_getSamplesPerFrame(AAudioStream* stream);
 
 /**
  * @param stream reference provided by AAudioStreamBuilder_openStream()
- * @param deviceId pointer to variable to receive the actual device ID
- * @return AAUDIO_OK or a negative error.
+ * @return actual device ID
  */
-AAUDIO_API int32_t AAudioStream_getDeviceId(AAudioStream stream,
-                                                    int32_t *deviceId);
+AAUDIO_API int32_t AAudioStream_getDeviceId(AAudioStream* stream);
 
 /**
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return actual data format
  */
-AAUDIO_API aaudio_audio_format_t AAudioStream_getFormat(AAudioStream stream);
+AAUDIO_API aaudio_audio_format_t AAudioStream_getFormat(AAudioStream* stream);
 
 /**
  * Provide actual sharing mode.
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return  actual sharing mode
  */
-AAUDIO_API aaudio_sharing_mode_t AAudioStream_getSharingMode(AAudioStream stream);
+AAUDIO_API aaudio_sharing_mode_t AAudioStream_getSharingMode(AAudioStream* stream);
 
 /**
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return direction
  */
-AAUDIO_API aaudio_direction_t AAudioStream_getDirection(AAudioStream stream);
+AAUDIO_API aaudio_direction_t AAudioStream_getDirection(AAudioStream* stream);
 
 /**
  * Passes back the number of frames that have been written since the stream was created.
@@ -484,7 +479,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return frames written
  */
-AAUDIO_API int64_t AAudioStream_getFramesWritten(AAudioStream stream);
+AAUDIO_API int64_t AAudioStream_getFramesWritten(AAudioStream* stream);
 
 /**
  * Passes back the number of frames that have been read since the stream was created.
@@ -496,7 +491,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return frames read
  */
-AAUDIO_API int64_t AAudioStream_getFramesRead(AAudioStream stream);
+AAUDIO_API int64_t AAudioStream_getFramesRead(AAudioStream* stream);
 
 /**
  * Passes back the time at which a particular frame was presented.
@@ -520,7 +515,7 @@
  * @param timeNanoseconds pointer to a variable to receive the time
  * @return AAUDIO_OK or a negative error
  */
-AAUDIO_API aaudio_result_t AAudioStream_getTimestamp(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_getTimestamp(AAudioStream* stream,
                                       clockid_t clockid,
                                       int64_t *framePosition,
                                       int64_t *timeNanoseconds);
diff --git a/media/libaaudio/src/core/AAudioAudio.cpp b/media/libaaudio/src/core/AAudioAudio.cpp
index 1208f66..52bad70 100644
--- a/media/libaaudio/src/core/AAudioAudio.cpp
+++ b/media/libaaudio/src/core/AAudioAudio.cpp
@@ -90,49 +90,49 @@
 
 #undef AAUDIO_CASE_ENUM
 
-static AudioStream *convertAAudioStreamToAudioStream(AAudioStream stream)
+static AudioStream *convertAAudioStreamToAudioStream(AAudioStream* stream)
 {
-    return (AudioStream *) stream;
+    return (AudioStream*) stream;
 }
 
-static AudioStreamBuilder *convertAAudioBuilderToStreamBuilder(AAudioStreamBuilder builder)
+static AudioStreamBuilder *convertAAudioBuilderToStreamBuilder(AAudioStreamBuilder* builder)
 {
-    return (AudioStreamBuilder *) builder;
+    return (AudioStreamBuilder*) builder;
 }
 
-AAUDIO_API aaudio_result_t AAudio_createStreamBuilder(AAudioStreamBuilder *builder)
+AAUDIO_API aaudio_result_t AAudio_createStreamBuilder(AAudioStreamBuilder** builder)
 {
     ALOGD("AAudio_createStreamBuilder(): check sHandleTracker.isInitialized ()");
     AudioStreamBuilder *audioStreamBuilder =  new AudioStreamBuilder();
     if (audioStreamBuilder == nullptr) {
         return AAUDIO_ERROR_NO_MEMORY;
     }
-    *builder = (AAudioStreamBuilder) audioStreamBuilder;
+    *builder = (AAudioStreamBuilder*) audioStreamBuilder;
     return AAUDIO_OK;
 }
 
-AAUDIO_API void AAudioStreamBuilder_setDeviceId(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setDeviceId(AAudioStreamBuilder* builder,
                                                      int32_t deviceId)
 {
     AudioStreamBuilder *streamBuilder = convertAAudioBuilderToStreamBuilder(builder);;
     streamBuilder->setDeviceId(deviceId);
 }
 
-AAUDIO_API void AAudioStreamBuilder_setSampleRate(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setSampleRate(AAudioStreamBuilder* builder,
                                               int32_t sampleRate)
 {
     AudioStreamBuilder *streamBuilder = convertAAudioBuilderToStreamBuilder(builder);;
     streamBuilder->setSampleRate(sampleRate);
 }
 
-AAUDIO_API void AAudioStreamBuilder_setSamplesPerFrame(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setSamplesPerFrame(AAudioStreamBuilder* builder,
                                                    int32_t samplesPerFrame)
 {
     AudioStreamBuilder *streamBuilder = convertAAudioBuilderToStreamBuilder(builder);;
     streamBuilder->setSamplesPerFrame(samplesPerFrame);
 }
 
-AAUDIO_API void AAudioStreamBuilder_setDirection(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setDirection(AAudioStreamBuilder* builder,
                                              aaudio_direction_t direction)
 {
     AudioStreamBuilder *streamBuilder = convertAAudioBuilderToStreamBuilder(builder);;
@@ -140,21 +140,21 @@
 }
 
 
-AAUDIO_API void AAudioStreamBuilder_setFormat(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setFormat(AAudioStreamBuilder* builder,
                                                    aaudio_audio_format_t format)
 {
     AudioStreamBuilder *streamBuilder = convertAAudioBuilderToStreamBuilder(builder);;
     streamBuilder->setFormat(format);
 }
 
-AAUDIO_API void AAudioStreamBuilder_setSharingMode(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setSharingMode(AAudioStreamBuilder* builder,
                                                         aaudio_sharing_mode_t sharingMode)
 {
     AudioStreamBuilder *streamBuilder = convertAAudioBuilderToStreamBuilder(builder);;
     streamBuilder->setSharingMode(sharingMode);
 }
 
-AAUDIO_API void AAudioStreamBuilder_setBufferCapacityInFrames(AAudioStreamBuilder builder,
+AAUDIO_API void AAudioStreamBuilder_setBufferCapacityInFrames(AAudioStreamBuilder* builder,
                                                         int32_t frames)
 {
     AudioStreamBuilder *streamBuilder = convertAAudioBuilderToStreamBuilder(builder);;
@@ -162,27 +162,27 @@
 }
 
 static aaudio_result_t  AAudioInternal_openStream(AudioStreamBuilder *streamBuilder,
-                                              AAudioStream *streamPtr)
+                                              AAudioStream** streamPtr)
 {
     AudioStream *audioStream = nullptr;
     aaudio_result_t result = streamBuilder->build(&audioStream);
     if (result != AAUDIO_OK) {
         return result;
     } else {
-        *streamPtr = (AAudioStream) audioStream;
+        *streamPtr = (AAudioStream*) audioStream;
         return AAUDIO_OK;
     }
 }
 
-AAUDIO_API aaudio_result_t  AAudioStreamBuilder_openStream(AAudioStreamBuilder builder,
-                                                     AAudioStream *streamPtr)
+AAUDIO_API aaudio_result_t  AAudioStreamBuilder_openStream(AAudioStreamBuilder* builder,
+                                                     AAudioStream** streamPtr)
 {
     ALOGD("AAudioStreamBuilder_openStream(): builder = %p", builder);
     AudioStreamBuilder *streamBuilder = COMMON_GET_FROM_BUILDER_OR_RETURN(streamPtr);
     return AAudioInternal_openStream(streamBuilder, streamPtr);
 }
 
-AAUDIO_API aaudio_result_t  AAudioStreamBuilder_delete(AAudioStreamBuilder builder)
+AAUDIO_API aaudio_result_t  AAudioStreamBuilder_delete(AAudioStreamBuilder* builder)
 {
     AudioStreamBuilder *streamBuilder = convertAAudioBuilderToStreamBuilder(builder);
     if (streamBuilder != nullptr) {
@@ -192,7 +192,7 @@
     return AAUDIO_ERROR_INVALID_HANDLE;
 }
 
-AAUDIO_API aaudio_result_t  AAudioStream_close(AAudioStream stream)
+AAUDIO_API aaudio_result_t  AAudioStream_close(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     ALOGD("AAudioStream_close(%p)", stream);
@@ -204,35 +204,35 @@
     return AAUDIO_ERROR_INVALID_HANDLE;
 }
 
-AAUDIO_API aaudio_result_t  AAudioStream_requestStart(AAudioStream stream)
+AAUDIO_API aaudio_result_t  AAudioStream_requestStart(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     ALOGD("AAudioStream_requestStart(%p)", stream);
     return audioStream->requestStart();
 }
 
-AAUDIO_API aaudio_result_t  AAudioStream_requestPause(AAudioStream stream)
+AAUDIO_API aaudio_result_t  AAudioStream_requestPause(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     ALOGD("AAudioStream_requestPause(%p)", stream);
     return audioStream->requestPause();
 }
 
-AAUDIO_API aaudio_result_t  AAudioStream_requestFlush(AAudioStream stream)
+AAUDIO_API aaudio_result_t  AAudioStream_requestFlush(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     ALOGD("AAudioStream_requestFlush(%p)", stream);
     return audioStream->requestFlush();
 }
 
-AAUDIO_API aaudio_result_t  AAudioStream_requestStop(AAudioStream stream)
+AAUDIO_API aaudio_result_t  AAudioStream_requestStop(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     ALOGD("AAudioStream_requestStop(%p)", stream);
     return audioStream->requestStop();
 }
 
-AAUDIO_API aaudio_result_t AAudioStream_waitForStateChange(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_waitForStateChange(AAudioStream* stream,
                                             aaudio_stream_state_t inputState,
                                             aaudio_stream_state_t *nextState,
                                             int64_t timeoutNanoseconds)
@@ -246,7 +246,7 @@
 // Stream - non-blocking I/O
 // ============================================================
 
-AAUDIO_API aaudio_result_t AAudioStream_read(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_read(AAudioStream* stream,
                                void *buffer,
                                int32_t numFrames,
                                int64_t timeoutNanoseconds)
@@ -267,7 +267,7 @@
     return result;
 }
 
-AAUDIO_API aaudio_result_t AAudioStream_write(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_write(AAudioStream* stream,
                                const void *buffer,
                                int32_t numFrames,
                                int64_t timeoutNanoseconds)
@@ -292,15 +292,15 @@
 // Miscellaneous
 // ============================================================
 
-AAUDIO_API aaudio_result_t AAudioStream_createThread(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_createThread(AAudioStream* stream,
                                      int64_t periodNanoseconds,
-                                     aaudio_audio_thread_proc_t *threadProc, void *arg)
+                                     aaudio_audio_thread_proc_t threadProc, void *arg)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->createThread(periodNanoseconds, threadProc, arg);
 }
 
-AAUDIO_API aaudio_result_t AAudioStream_joinThread(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_joinThread(AAudioStream* stream,
                                    void **returnArg,
                                    int64_t timeoutNanoseconds)
 {
@@ -312,92 +312,92 @@
 // Stream - queries
 // ============================================================
 
-AAUDIO_API int32_t AAudioStream_getSampleRate(AAudioStream stream)
+AAUDIO_API int32_t AAudioStream_getSampleRate(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getSampleRate();
 }
 
-AAUDIO_API int32_t AAudioStream_getSamplesPerFrame(AAudioStream stream)
+AAUDIO_API int32_t AAudioStream_getSamplesPerFrame(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getSamplesPerFrame();
 }
 
-AAUDIO_API aaudio_stream_state_t AAudioStream_getState(AAudioStream stream)
+AAUDIO_API aaudio_stream_state_t AAudioStream_getState(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getState();
 }
 
-AAUDIO_API aaudio_audio_format_t AAudioStream_getFormat(AAudioStream stream)
+AAUDIO_API aaudio_audio_format_t AAudioStream_getFormat(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getFormat();
 }
 
-AAUDIO_API aaudio_result_t AAudioStream_setBufferSizeInFrames(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_setBufferSizeInFrames(AAudioStream* stream,
                                                 int32_t requestedFrames)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->setBufferSize(requestedFrames);
 }
 
-AAUDIO_API int32_t AAudioStream_getBufferSizeInFrames(AAudioStream stream)
+AAUDIO_API int32_t AAudioStream_getBufferSizeInFrames(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getBufferSize();
 }
 
-AAUDIO_API aaudio_direction_t AAudioStream_getDirection(AAudioStream stream)
+AAUDIO_API aaudio_direction_t AAudioStream_getDirection(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getDirection();
 }
 
-AAUDIO_API int32_t AAudioStream_getFramesPerBurst(AAudioStream stream)
+AAUDIO_API int32_t AAudioStream_getFramesPerBurst(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getFramesPerBurst();
 }
 
-AAUDIO_API int32_t AAudioStream_getBufferCapacityInFrames(AAudioStream stream)
+AAUDIO_API int32_t AAudioStream_getBufferCapacityInFrames(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getBufferCapacity();
 }
 
-AAUDIO_API int32_t AAudioStream_getXRunCount(AAudioStream stream)
+AAUDIO_API int32_t AAudioStream_getXRunCount(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getXRunCount();
 }
 
-AAUDIO_API int32_t AAudioStream_getDeviceId(AAudioStream stream)
+AAUDIO_API int32_t AAudioStream_getDeviceId(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getDeviceId();
 }
 
-AAUDIO_API aaudio_sharing_mode_t AAudioStream_getSharingMode(AAudioStream stream)
+AAUDIO_API aaudio_sharing_mode_t AAudioStream_getSharingMode(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getSharingMode();
 }
 
-AAUDIO_API int64_t AAudioStream_getFramesWritten(AAudioStream stream)
+AAUDIO_API int64_t AAudioStream_getFramesWritten(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getFramesWritten();
 }
 
-AAUDIO_API int64_t AAudioStream_getFramesRead(AAudioStream stream)
+AAUDIO_API int64_t AAudioStream_getFramesRead(AAudioStream* stream)
 {
     AudioStream *audioStream = convertAAudioStreamToAudioStream(stream);
     return audioStream->getFramesRead();
 }
 
-AAUDIO_API aaudio_result_t AAudioStream_getTimestamp(AAudioStream stream,
+AAUDIO_API aaudio_result_t AAudioStream_getTimestamp(AAudioStream* stream,
                                       clockid_t clockid,
                                       int64_t *framePosition,
                                       int64_t *timeNanoseconds)
diff --git a/media/libaaudio/src/core/AudioStream.cpp b/media/libaaudio/src/core/AudioStream.cpp
index c4962ee..b054d94 100644
--- a/media/libaaudio/src/core/AudioStream.cpp
+++ b/media/libaaudio/src/core/AudioStream.cpp
@@ -121,7 +121,7 @@
 }
 
 aaudio_result_t AudioStream::createThread(int64_t periodNanoseconds,
-                                     aaudio_audio_thread_proc_t *threadProc,
+                                     aaudio_audio_thread_proc_t threadProc,
                                      void* threadArg)
 {
     if (mHasThread) {
diff --git a/media/libaaudio/src/core/AudioStream.h b/media/libaaudio/src/core/AudioStream.h
index f5f9d28..af0593d 100644
--- a/media/libaaudio/src/core/AudioStream.h
+++ b/media/libaaudio/src/core/AudioStream.h
@@ -84,7 +84,7 @@
     }
 
     virtual aaudio_result_t createThread(int64_t periodNanoseconds,
-                                       aaudio_audio_thread_proc_t *threadProc,
+                                       aaudio_audio_thread_proc_t threadProc,
                                        void *threadArg);
 
     virtual aaudio_result_t joinThread(void **returnArg, int64_t timeoutNanoseconds);
@@ -267,7 +267,7 @@
     // These are set by the application thread and then read by the audio pthread.
     std::atomic<int64_t>   mPeriodNanoseconds; // for tuning SCHED_FIFO threads
     // TODO make atomic?
-    aaudio_audio_thread_proc_t* mThreadProc = nullptr;
+    aaudio_audio_thread_proc_t mThreadProc = nullptr;
     void*                  mThreadArg = nullptr;
     aaudio_result_t        mThreadRegistrationResult = AAUDIO_OK;
 
diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp
index 03dce0c..ad130e0 100644
--- a/media/libaudioclient/Android.bp
+++ b/media/libaudioclient/Android.bp
@@ -26,6 +26,8 @@
         "libaudioutils",
     ],
     export_shared_lib_headers: ["libbinder"],
+    local_include_dirs: ["include"],
+    export_include_dirs: ["include"],
     // for memory heap analysis
     static_libs: [
         "libc_malloc_debug_backtrace",
diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp
index d35cfe3..f878be9 100644
--- a/media/libaudioclient/AudioTrack.cpp
+++ b/media/libaudioclient/AudioTrack.cpp
@@ -184,7 +184,6 @@
       mPreviousSchedulingGroup(SP_DEFAULT),
       mPausedPosition(0),
       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
-      mVolumeShaperId(VolumeShaper::kSystemIdMax),
       mPortId(AUDIO_PORT_HANDLE_NONE)
 {
     mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
@@ -557,7 +556,7 @@
     mFramesWritten = 0;
     mFramesWrittenServerOffset = 0;
     mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
-    mVolumeHandler = new VolumeHandler(mSampleRate);
+    mVolumeHandler = new VolumeHandler();
     return NO_ERROR;
 }
 
@@ -2251,6 +2250,20 @@
                 }
             }
         }
+        // restore volume handler
+        mVolumeHandler->forall([this](const sp<VolumeShaper::Configuration> &configuration,
+                const sp<VolumeShaper::Operation> &operation) -> VolumeShaper::Status {
+            sp<VolumeShaper::Operation> operationToEnd = new VolumeShaper::Operation(*operation);
+            // TODO: Ideally we would restore to the exact xOffset position
+            // as returned by getVolumeShaperState(), but we don't have that
+            // information when restoring at the client unless we periodically poll
+            // the server or create shared memory state.
+            //
+            // For now, we simply advance to the end of the VolumeShaper effect.
+            operationToEnd->setXOffset(1.f);
+            return mAudioTrack->applyVolumeShaper(configuration, operationToEnd);
+        });
+
         if (mState == STATE_ACTIVE) {
             result = mAudioTrack->start();
         }
@@ -2316,24 +2329,12 @@
         const sp<VolumeShaper::Operation>& operation)
 {
     AutoMutex lock(mLock);
-    if (configuration->getType() == VolumeShaper::Configuration::TYPE_SCALE) {
-        const int id = configuration->getId();
-        LOG_ALWAYS_FATAL_IF(id >= VolumeShaper::kSystemIdMax || id < -1,
-                "id must be -1 or a system id (less than kSystemIdMax)");
-        if (id == -1) {
-            // if not a system id, reassign to a unique id
-            configuration->setId(mVolumeShaperId);
-            ALOGD("setting id to %d", mVolumeShaperId);
-            // increment and avoid signed overflow.
-            if (mVolumeShaperId == INT32_MAX) {
-                mVolumeShaperId = VolumeShaper::kSystemIdMax;
-            } else {
-                ++mVolumeShaperId;
-            }
-        }
-    }
+    mVolumeHandler->setIdIfNecessary(configuration);
     VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(configuration, operation);
-    // TODO: For restoration purposes, record successful creation and termination.
+    if (status >= 0) {
+        // save VolumeShaper for restore
+        mVolumeHandler->applyVolumeShaper(configuration, operation);
+    }
     return status;
 }
 
diff --git a/include/media/AudioBufferProvider.h b/media/libaudioclient/include/AudioBufferProvider.h
similarity index 100%
rename from include/media/AudioBufferProvider.h
rename to media/libaudioclient/include/AudioBufferProvider.h
diff --git a/include/media/AudioEffect.h b/media/libaudioclient/include/AudioEffect.h
similarity index 100%
rename from include/media/AudioEffect.h
rename to media/libaudioclient/include/AudioEffect.h
diff --git a/include/media/AudioIoDescriptor.h b/media/libaudioclient/include/AudioIoDescriptor.h
similarity index 100%
rename from include/media/AudioIoDescriptor.h
rename to media/libaudioclient/include/AudioIoDescriptor.h
diff --git a/include/media/AudioMixer.h b/media/libaudioclient/include/AudioMixer.h
similarity index 100%
rename from include/media/AudioMixer.h
rename to media/libaudioclient/include/AudioMixer.h
diff --git a/include/media/AudioParameter.h b/media/libaudioclient/include/AudioParameter.h
similarity index 100%
rename from include/media/AudioParameter.h
rename to media/libaudioclient/include/AudioParameter.h
diff --git a/include/media/AudioPolicy.h b/media/libaudioclient/include/AudioPolicy.h
similarity index 100%
rename from include/media/AudioPolicy.h
rename to media/libaudioclient/include/AudioPolicy.h
diff --git a/include/media/AudioPolicyHelper.h b/media/libaudioclient/include/AudioPolicyHelper.h
similarity index 100%
rename from include/media/AudioPolicyHelper.h
rename to media/libaudioclient/include/AudioPolicyHelper.h
diff --git a/include/media/AudioRecord.h b/media/libaudioclient/include/AudioRecord.h
similarity index 100%
rename from include/media/AudioRecord.h
rename to media/libaudioclient/include/AudioRecord.h
diff --git a/include/media/AudioSystem.h b/media/libaudioclient/include/AudioSystem.h
similarity index 100%
rename from include/media/AudioSystem.h
rename to media/libaudioclient/include/AudioSystem.h
diff --git a/include/media/AudioTimestamp.h b/media/libaudioclient/include/AudioTimestamp.h
similarity index 100%
rename from include/media/AudioTimestamp.h
rename to media/libaudioclient/include/AudioTimestamp.h
diff --git a/include/media/AudioTrack.h b/media/libaudioclient/include/AudioTrack.h
similarity index 99%
rename from include/media/AudioTrack.h
rename to media/libaudioclient/include/AudioTrack.h
index 1996dbe..0358363 100644
--- a/include/media/AudioTrack.h
+++ b/media/libaudioclient/include/AudioTrack.h
@@ -1128,8 +1128,6 @@
 
     sp<VolumeHandler>       mVolumeHandler;
 
-    int32_t                 mVolumeShaperId;
-
 private:
     class DeathNotifier : public IBinder::DeathRecipient {
     public:
diff --git a/include/media/IAudioFlinger.h b/media/libaudioclient/include/IAudioFlinger.h
similarity index 100%
rename from include/media/IAudioFlinger.h
rename to media/libaudioclient/include/IAudioFlinger.h
diff --git a/include/media/IAudioFlingerClient.h b/media/libaudioclient/include/IAudioFlingerClient.h
similarity index 100%
rename from include/media/IAudioFlingerClient.h
rename to media/libaudioclient/include/IAudioFlingerClient.h
diff --git a/include/media/IAudioPolicyService.h b/media/libaudioclient/include/IAudioPolicyService.h
similarity index 100%
rename from include/media/IAudioPolicyService.h
rename to media/libaudioclient/include/IAudioPolicyService.h
diff --git a/include/media/IAudioPolicyServiceClient.h b/media/libaudioclient/include/IAudioPolicyServiceClient.h
similarity index 100%
rename from include/media/IAudioPolicyServiceClient.h
rename to media/libaudioclient/include/IAudioPolicyServiceClient.h
diff --git a/include/media/IAudioRecord.h b/media/libaudioclient/include/IAudioRecord.h
similarity index 100%
rename from include/media/IAudioRecord.h
rename to media/libaudioclient/include/IAudioRecord.h
diff --git a/include/media/IAudioTrack.h b/media/libaudioclient/include/IAudioTrack.h
similarity index 100%
rename from include/media/IAudioTrack.h
rename to media/libaudioclient/include/IAudioTrack.h
diff --git a/include/media/IEffect.h b/media/libaudioclient/include/IEffect.h
similarity index 100%
rename from include/media/IEffect.h
rename to media/libaudioclient/include/IEffect.h
diff --git a/include/media/IEffectClient.h b/media/libaudioclient/include/IEffectClient.h
similarity index 100%
rename from include/media/IEffectClient.h
rename to media/libaudioclient/include/IEffectClient.h
diff --git a/include/media/ToneGenerator.h b/media/libaudioclient/include/ToneGenerator.h
similarity index 100%
rename from include/media/ToneGenerator.h
rename to media/libaudioclient/include/ToneGenerator.h
diff --git a/media/libaudiohal/Android.mk b/media/libaudiohal/Android.mk
index 286c6b7..032b3e9 100644
--- a/media/libaudiohal/Android.mk
+++ b/media/libaudiohal/Android.mk
@@ -52,6 +52,10 @@
 
 endif  # USE_LEGACY_LOCAL_AUDIO_HAL
 
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+
 LOCAL_MODULE := libaudiohal
 
 LOCAL_CFLAGS := -Wall -Werror
diff --git a/media/libaudiohal/ConversionHelperHidl.h b/media/libaudiohal/ConversionHelperHidl.h
index 23fb360..a991baf 100644
--- a/media/libaudiohal/ConversionHelperHidl.h
+++ b/media/libaudiohal/ConversionHelperHidl.h
@@ -56,17 +56,19 @@
     }
 
     status_t processReturn(const char* funcName, const Return<hardware::audio::V2_0::Result>& ret) {
-        return processReturn(funcName, ret, ret);
+        if (!ret.isOk()) {
+            emitError(funcName, ret.description().c_str());
+        }
+        return ret.isOk() ? analyzeResult(ret) : FAILED_TRANSACTION;
     }
 
     template<typename T>
     status_t processReturn(
             const char* funcName, const Return<T>& ret, hardware::audio::V2_0::Result retval) {
-        const status_t st = ret.isOk() ? analyzeResult(retval) : FAILED_TRANSACTION;
         if (!ret.isOk()) {
             emitError(funcName, ret.description().c_str());
         }
-        return st;
+        return ret.isOk() ? analyzeResult(retval) : FAILED_TRANSACTION;
     }
 
   private:
diff --git a/media/libaudiohal/DeviceHalHidl.cpp b/media/libaudiohal/DeviceHalHidl.cpp
index dcedfd3..71fbd98 100644
--- a/media/libaudiohal/DeviceHalHidl.cpp
+++ b/media/libaudiohal/DeviceHalHidl.cpp
@@ -21,6 +21,7 @@
 
 #include <android/hardware/audio/2.0/IPrimaryDevice.h>
 #include <cutils/native_handle.h>
+#include <hwbinder/IPCThreadState.h>
 #include <utils/Log.h>
 
 #include "DeviceHalHidl.h"
@@ -101,6 +102,10 @@
 }
 
 DeviceHalHidl::~DeviceHalHidl() {
+    if (mDevice != 0) {
+        mDevice.clear();
+        hardware::IPCThreadState::self()->flushCommands();
+    }
 }
 
 status_t DeviceHalHidl::getSupportedDevices(uint32_t*) {
diff --git a/media/libaudiohal/EffectHalHidl.cpp b/media/libaudiohal/EffectHalHidl.cpp
index d17f8bd..db115ef 100644
--- a/media/libaudiohal/EffectHalHidl.cpp
+++ b/media/libaudiohal/EffectHalHidl.cpp
@@ -17,6 +17,7 @@
 #define LOG_TAG "EffectHalHidl"
 //#define LOG_NDEBUG 0
 
+#include <hwbinder/IPCThreadState.h>
 #include <media/EffectsFactoryApi.h>
 #include <utils/Log.h>
 
@@ -44,7 +45,11 @@
 }
 
 EffectHalHidl::~EffectHalHidl() {
-    close();
+    if (mEffect != 0) {
+        close();
+        mEffect.clear();
+        hardware::IPCThreadState::self()->flushCommands();
+    }
 }
 
 // static
diff --git a/media/libaudiohal/StreamHalHidl.cpp b/media/libaudiohal/StreamHalHidl.cpp
index b66ba2b..2a7a67f 100644
--- a/media/libaudiohal/StreamHalHidl.cpp
+++ b/media/libaudiohal/StreamHalHidl.cpp
@@ -18,6 +18,7 @@
 //#define LOG_NDEBUG 0
 
 #include <android/hardware/audio/2.0/IStreamOutCallback.h>
+#include <hwbinder/IPCThreadState.h>
 #include <mediautils/SchedulingPolicyService.h>
 #include <utils/Log.h>
 
@@ -263,8 +264,10 @@
             processReturn("clearCallback", mStream->clearCallback());
         }
         processReturn("close", mStream->close());
+        mStream.clear();
     }
     mCallback.clear();
+    hardware::IPCThreadState::self()->flushCommands();
     if (mEfGroup) {
         EventFlag::deleteEventFlag(&mEfGroup);
     }
@@ -538,6 +541,8 @@
 StreamInHalHidl::~StreamInHalHidl() {
     if (mStream != 0) {
         processReturn("close", mStream->close());
+        mStream.clear();
+        hardware::IPCThreadState::self()->flushCommands();
     }
     if (mEfGroup) {
         EventFlag::deleteEventFlag(&mEfGroup);
diff --git a/include/media/audiohal/DeviceHalInterface.h b/media/libaudiohal/include/DeviceHalInterface.h
similarity index 100%
rename from include/media/audiohal/DeviceHalInterface.h
rename to media/libaudiohal/include/DeviceHalInterface.h
diff --git a/include/media/audiohal/DevicesFactoryHalInterface.h b/media/libaudiohal/include/DevicesFactoryHalInterface.h
similarity index 100%
rename from include/media/audiohal/DevicesFactoryHalInterface.h
rename to media/libaudiohal/include/DevicesFactoryHalInterface.h
diff --git a/include/media/audiohal/EffectBufferHalInterface.h b/media/libaudiohal/include/EffectBufferHalInterface.h
similarity index 100%
rename from include/media/audiohal/EffectBufferHalInterface.h
rename to media/libaudiohal/include/EffectBufferHalInterface.h
diff --git a/include/media/audiohal/EffectHalInterface.h b/media/libaudiohal/include/EffectHalInterface.h
similarity index 100%
rename from include/media/audiohal/EffectHalInterface.h
rename to media/libaudiohal/include/EffectHalInterface.h
diff --git a/include/media/audiohal/EffectsFactoryHalInterface.h b/media/libaudiohal/include/EffectsFactoryHalInterface.h
similarity index 100%
rename from include/media/audiohal/EffectsFactoryHalInterface.h
rename to media/libaudiohal/include/EffectsFactoryHalInterface.h
diff --git a/include/media/audiohal/StreamHalInterface.h b/media/libaudiohal/include/StreamHalInterface.h
similarity index 100%
rename from include/media/audiohal/StreamHalInterface.h
rename to media/libaudiohal/include/StreamHalInterface.h
diff --git a/include/media/audiohal/hidl/HalDeathHandler.h b/media/libaudiohal/include/hidl/HalDeathHandler.h
similarity index 100%
rename from include/media/audiohal/hidl/HalDeathHandler.h
rename to media/libaudiohal/include/hidl/HalDeathHandler.h
diff --git a/media/libaudioprocessing/Android.mk b/media/libaudioprocessing/Android.mk
index b7ea99e..c850984 100644
--- a/media/libaudioprocessing/Android.mk
+++ b/media/libaudioprocessing/Android.mk
@@ -14,6 +14,9 @@
 LOCAL_C_INCLUDES := \
     $(TOP) \
     $(call include-path-for, audio-utils) \
+    $(LOCAL_PATH)/include \
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
 
 LOCAL_SHARED_LIBRARIES := \
     libaudiohal \
diff --git a/include/media/AudioResampler.h b/media/libaudioprocessing/include/AudioResampler.h
similarity index 100%
rename from include/media/AudioResampler.h
rename to media/libaudioprocessing/include/AudioResampler.h
diff --git a/include/media/AudioResamplerPublic.h b/media/libaudioprocessing/include/AudioResamplerPublic.h
similarity index 100%
rename from include/media/AudioResamplerPublic.h
rename to media/libaudioprocessing/include/AudioResamplerPublic.h
diff --git a/include/cpustats/CentralTendencyStatistics.h b/media/libcpustats/include/cpustats/CentralTendencyStatistics.h
similarity index 100%
rename from include/cpustats/CentralTendencyStatistics.h
rename to media/libcpustats/include/cpustats/CentralTendencyStatistics.h
diff --git a/include/cpustats/README.txt b/media/libcpustats/include/cpustats/README.txt
similarity index 100%
rename from include/cpustats/README.txt
rename to media/libcpustats/include/cpustats/README.txt
diff --git a/include/cpustats/ThreadCpuUsage.h b/media/libcpustats/include/cpustats/ThreadCpuUsage.h
similarity index 100%
rename from include/cpustats/ThreadCpuUsage.h
rename to media/libcpustats/include/cpustats/ThreadCpuUsage.h
diff --git a/media/libeffects/factory/Android.bp b/media/libeffects/factory/Android.bp
index 0d8b6eb..e0e0d13 100644
--- a/media/libeffects/factory/Android.bp
+++ b/media/libeffects/factory/Android.bp
@@ -10,4 +10,8 @@
     ],
 
     include_dirs: ["system/media/audio_effects/include"],
+
+    local_include_dirs:["include"],
+
+    export_include_dirs: ["include"],
 }
diff --git a/include/media/EffectsFactoryApi.h b/media/libeffects/factory/include/EffectsFactoryApi.h
similarity index 100%
rename from include/media/EffectsFactoryApi.h
rename to media/libeffects/factory/include/EffectsFactoryApi.h
diff --git a/media/libmedia/Android.mk b/media/libmedia/Android.mk
index 6c6c369..eac532b 100644
--- a/media/libmedia/Android.mk
+++ b/media/libmedia/Android.mk
@@ -60,10 +60,10 @@
         libui liblog libcutils libutils libbinder libsonivox libicuuc libicui18n libexpat \
         libcamera_client libstagefright_foundation \
         libgui libdl libaudioutils libaudioclient \
-        libmedia_helper \
+        libmedia_helper libmediadrm \
         libhidlbase \
 
-LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libbinder libsonivox
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libbinder libsonivox libmediadrm
 
 # for memory heap analysis
 LOCAL_STATIC_LIBRARIES := libc_malloc_debug_backtrace libc_logging
diff --git a/media/libmedia/IMediaExtractor.cpp b/media/libmedia/IMediaExtractor.cpp
index bfc43a6..f08fabb 100644
--- a/media/libmedia/IMediaExtractor.cpp
+++ b/media/libmedia/IMediaExtractor.cpp
@@ -21,6 +21,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
+#include <android/media/ICas.h>
 #include <binder/IPCThreadState.h>
 #include <binder/Parcel.h>
 #include <media/IMediaExtractor.h>
@@ -35,6 +36,7 @@
     GETMETADATA,
     FLAGS,
     GETDRMTRACKINFO,
+    SETMEDIACAS,
     SETUID,
     NAME,
     GETMETRICS
@@ -114,6 +116,21 @@
         ALOGV("getDrmTrackInfo NOT IMPLEMENTED");
         return NULL;
     }
+
+    virtual status_t setMediaCas(const sp<ICas> & cas) {
+        ALOGV("setMediaCas");
+
+        Parcel data, reply;
+        data.writeInterfaceToken(BpMediaExtractor::getInterfaceDescriptor());
+        data.writeStrongBinder(IInterface::asBinder(cas));
+
+        status_t err = remote()->transact(SETMEDIACAS, data, &reply);
+        if (err != NO_ERROR) {
+            return err;
+        }
+        return reply.readInt32();
+    }
+
     virtual void setUID(uid_t uid __unused) {
         ALOGV("setUID NOT IMPLEMENTED");
     }
@@ -185,6 +202,21 @@
             status_t ret = getMetrics(reply);
             return ret;
         }
+        case SETMEDIACAS: {
+            ALOGV("setMediaCas");
+            CHECK_INTERFACE(IMediaExtractor, data, reply);
+
+            sp<IBinder> casBinder;
+            status_t err = data.readNullableStrongBinder(&casBinder);
+            if (err != NO_ERROR) {
+                ALOGE("Error reading cas from parcel");
+                return err;
+            }
+            sp<ICas> cas = interface_cast<ICas>(casBinder);
+
+            reply->writeInt32(setMediaCas(cas));
+            return OK;
+        }
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/media/libmedia/MediaDefs.cpp b/media/libmedia/MediaDefs.cpp
index 2ae71f7..544a6ae 100644
--- a/media/libmedia/MediaDefs.cpp
+++ b/media/libmedia/MediaDefs.cpp
@@ -29,6 +29,7 @@
 const char *MEDIA_MIMETYPE_VIDEO_MPEG2 = "video/mpeg2";
 const char *MEDIA_MIMETYPE_VIDEO_RAW = "video/raw";
 const char *MEDIA_MIMETYPE_VIDEO_DOLBY_VISION = "video/dolby-vision";
+const char *MEDIA_MIMETYPE_VIDEO_SCRAMBLED = "video/scrambled";
 
 const char *MEDIA_MIMETYPE_AUDIO_AMR_NB = "audio/3gpp";
 const char *MEDIA_MIMETYPE_AUDIO_AMR_WB = "audio/amr-wb";
@@ -48,6 +49,7 @@
 const char *MEDIA_MIMETYPE_AUDIO_MSGSM = "audio/gsm";
 const char *MEDIA_MIMETYPE_AUDIO_AC3 = "audio/ac3";
 const char *MEDIA_MIMETYPE_AUDIO_EAC3 = "audio/eac3";
+const char *MEDIA_MIMETYPE_AUDIO_SCRAMBLED = "audio/scrambled";
 
 const char *MEDIA_MIMETYPE_CONTAINER_MPEG4 = "video/mp4";
 const char *MEDIA_MIMETYPE_CONTAINER_WAV = "audio/x-wav";
diff --git a/include/media/AVSyncSettings.h b/media/libmedia/include/AVSyncSettings.h
similarity index 100%
rename from include/media/AVSyncSettings.h
rename to media/libmedia/include/AVSyncSettings.h
diff --git a/include/media/BufferProviders.h b/media/libmedia/include/BufferProviders.h
similarity index 100%
rename from include/media/BufferProviders.h
rename to media/libmedia/include/BufferProviders.h
diff --git a/include/media/BufferingSettings.h b/media/libmedia/include/BufferingSettings.h
similarity index 100%
rename from include/media/BufferingSettings.h
rename to media/libmedia/include/BufferingSettings.h
diff --git a/include/media/CharacterEncodingDetector.h b/media/libmedia/include/CharacterEncodingDetector.h
similarity index 100%
rename from include/media/CharacterEncodingDetector.h
rename to media/libmedia/include/CharacterEncodingDetector.h
diff --git a/include/media/Crypto.h b/media/libmedia/include/Crypto.h
similarity index 100%
rename from include/media/Crypto.h
rename to media/libmedia/include/Crypto.h
diff --git a/include/media/CryptoHal.h b/media/libmedia/include/CryptoHal.h
similarity index 100%
rename from include/media/CryptoHal.h
rename to media/libmedia/include/CryptoHal.h
diff --git a/include/media/Drm.h b/media/libmedia/include/Drm.h
similarity index 100%
rename from include/media/Drm.h
rename to media/libmedia/include/Drm.h
diff --git a/include/media/DrmHal.h b/media/libmedia/include/DrmHal.h
similarity index 100%
rename from include/media/DrmHal.h
rename to media/libmedia/include/DrmHal.h
diff --git a/include/media/DrmSessionClientInterface.h b/media/libmedia/include/DrmSessionClientInterface.h
similarity index 100%
rename from include/media/DrmSessionClientInterface.h
rename to media/libmedia/include/DrmSessionClientInterface.h
diff --git a/include/media/DrmSessionManager.h b/media/libmedia/include/DrmSessionManager.h
similarity index 100%
rename from include/media/DrmSessionManager.h
rename to media/libmedia/include/DrmSessionManager.h
diff --git a/include/media/ExtendedAudioBufferProvider.h b/media/libmedia/include/ExtendedAudioBufferProvider.h
similarity index 100%
rename from include/media/ExtendedAudioBufferProvider.h
rename to media/libmedia/include/ExtendedAudioBufferProvider.h
diff --git a/include/media/ICrypto.h b/media/libmedia/include/ICrypto.h
similarity index 100%
rename from include/media/ICrypto.h
rename to media/libmedia/include/ICrypto.h
diff --git a/include/media/IDataSource.h b/media/libmedia/include/IDataSource.h
similarity index 100%
rename from include/media/IDataSource.h
rename to media/libmedia/include/IDataSource.h
diff --git a/include/media/IDrm.h b/media/libmedia/include/IDrm.h
similarity index 100%
rename from include/media/IDrm.h
rename to media/libmedia/include/IDrm.h
diff --git a/include/media/IDrmClient.h b/media/libmedia/include/IDrmClient.h
similarity index 100%
rename from include/media/IDrmClient.h
rename to media/libmedia/include/IDrmClient.h
diff --git a/include/media/IHDCP.h b/media/libmedia/include/IHDCP.h
similarity index 100%
rename from include/media/IHDCP.h
rename to media/libmedia/include/IHDCP.h
diff --git a/include/media/IMediaAnalyticsService.h b/media/libmedia/include/IMediaAnalyticsService.h
similarity index 100%
rename from include/media/IMediaAnalyticsService.h
rename to media/libmedia/include/IMediaAnalyticsService.h
diff --git a/include/media/IMediaCodecList.h b/media/libmedia/include/IMediaCodecList.h
similarity index 100%
rename from include/media/IMediaCodecList.h
rename to media/libmedia/include/IMediaCodecList.h
diff --git a/include/media/IMediaCodecService.h b/media/libmedia/include/IMediaCodecService.h
similarity index 100%
rename from include/media/IMediaCodecService.h
rename to media/libmedia/include/IMediaCodecService.h
diff --git a/include/media/IMediaDeathNotifier.h b/media/libmedia/include/IMediaDeathNotifier.h
similarity index 100%
rename from include/media/IMediaDeathNotifier.h
rename to media/libmedia/include/IMediaDeathNotifier.h
diff --git a/include/media/IMediaDrmService.h b/media/libmedia/include/IMediaDrmService.h
similarity index 100%
rename from include/media/IMediaDrmService.h
rename to media/libmedia/include/IMediaDrmService.h
diff --git a/include/media/IMediaExtractor.h b/media/libmedia/include/IMediaExtractor.h
similarity index 95%
rename from include/media/IMediaExtractor.h
rename to media/libmedia/include/IMediaExtractor.h
index 06db359..cf1b9fb 100644
--- a/include/media/IMediaExtractor.h
+++ b/media/libmedia/include/IMediaExtractor.h
@@ -24,6 +24,10 @@
 namespace android {
 
 class MetaData;
+namespace media {
+class ICas;
+};
+using namespace media;
 
 class IMediaExtractor : public IInterface {
 public:
@@ -57,6 +61,9 @@
 
     // for DRM
     virtual char* getDrmTrackInfo(size_t trackID, int *len)  = 0;
+
+    virtual status_t setMediaCas(const sp<ICas> &cas) = 0;
+
     virtual void setUID(uid_t uid)  = 0;
 
     virtual const char * name() = 0;
diff --git a/include/media/IMediaExtractorService.h b/media/libmedia/include/IMediaExtractorService.h
similarity index 100%
rename from include/media/IMediaExtractorService.h
rename to media/libmedia/include/IMediaExtractorService.h
diff --git a/include/media/IMediaHTTPConnection.h b/media/libmedia/include/IMediaHTTPConnection.h
similarity index 100%
rename from include/media/IMediaHTTPConnection.h
rename to media/libmedia/include/IMediaHTTPConnection.h
diff --git a/include/media/IMediaHTTPService.h b/media/libmedia/include/IMediaHTTPService.h
similarity index 100%
rename from include/media/IMediaHTTPService.h
rename to media/libmedia/include/IMediaHTTPService.h
diff --git a/include/media/IMediaLogService.h b/media/libmedia/include/IMediaLogService.h
similarity index 100%
rename from include/media/IMediaLogService.h
rename to media/libmedia/include/IMediaLogService.h
diff --git a/include/media/IMediaMetadataRetriever.h b/media/libmedia/include/IMediaMetadataRetriever.h
similarity index 100%
rename from include/media/IMediaMetadataRetriever.h
rename to media/libmedia/include/IMediaMetadataRetriever.h
diff --git a/include/media/IMediaPlayer.h b/media/libmedia/include/IMediaPlayer.h
similarity index 100%
rename from include/media/IMediaPlayer.h
rename to media/libmedia/include/IMediaPlayer.h
diff --git a/include/media/IMediaPlayerClient.h b/media/libmedia/include/IMediaPlayerClient.h
similarity index 100%
rename from include/media/IMediaPlayerClient.h
rename to media/libmedia/include/IMediaPlayerClient.h
diff --git a/include/media/IMediaPlayerService.h b/media/libmedia/include/IMediaPlayerService.h
similarity index 100%
rename from include/media/IMediaPlayerService.h
rename to media/libmedia/include/IMediaPlayerService.h
diff --git a/include/media/IMediaRecorder.h b/media/libmedia/include/IMediaRecorder.h
similarity index 100%
rename from include/media/IMediaRecorder.h
rename to media/libmedia/include/IMediaRecorder.h
diff --git a/include/media/IMediaRecorderClient.h b/media/libmedia/include/IMediaRecorderClient.h
similarity index 100%
rename from include/media/IMediaRecorderClient.h
rename to media/libmedia/include/IMediaRecorderClient.h
diff --git a/include/media/IMediaSource.h b/media/libmedia/include/IMediaSource.h
similarity index 100%
rename from include/media/IMediaSource.h
rename to media/libmedia/include/IMediaSource.h
diff --git a/include/media/IOMX.h b/media/libmedia/include/IOMX.h
similarity index 100%
rename from include/media/IOMX.h
rename to media/libmedia/include/IOMX.h
diff --git a/include/media/IRemoteDisplay.h b/media/libmedia/include/IRemoteDisplay.h
similarity index 100%
rename from include/media/IRemoteDisplay.h
rename to media/libmedia/include/IRemoteDisplay.h
diff --git a/include/media/IRemoteDisplayClient.h b/media/libmedia/include/IRemoteDisplayClient.h
similarity index 100%
rename from include/media/IRemoteDisplayClient.h
rename to media/libmedia/include/IRemoteDisplayClient.h
diff --git a/include/media/IResourceManagerClient.h b/media/libmedia/include/IResourceManagerClient.h
similarity index 100%
rename from include/media/IResourceManagerClient.h
rename to media/libmedia/include/IResourceManagerClient.h
diff --git a/include/media/IResourceManagerService.h b/media/libmedia/include/IResourceManagerService.h
similarity index 100%
rename from include/media/IResourceManagerService.h
rename to media/libmedia/include/IResourceManagerService.h
diff --git a/include/media/IStreamSource.h b/media/libmedia/include/IStreamSource.h
similarity index 100%
rename from include/media/IStreamSource.h
rename to media/libmedia/include/IStreamSource.h
diff --git a/include/media/JetPlayer.h b/media/libmedia/include/JetPlayer.h
similarity index 100%
rename from include/media/JetPlayer.h
rename to media/libmedia/include/JetPlayer.h
diff --git a/include/media/LinearMap.h b/media/libmedia/include/LinearMap.h
similarity index 100%
rename from include/media/LinearMap.h
rename to media/libmedia/include/LinearMap.h
diff --git a/include/media/MediaAnalyticsItem.h b/media/libmedia/include/MediaAnalyticsItem.h
similarity index 100%
rename from include/media/MediaAnalyticsItem.h
rename to media/libmedia/include/MediaAnalyticsItem.h
diff --git a/include/media/MediaCodecBuffer.h b/media/libmedia/include/MediaCodecBuffer.h
similarity index 100%
rename from include/media/MediaCodecBuffer.h
rename to media/libmedia/include/MediaCodecBuffer.h
diff --git a/include/media/MediaCodecInfo.h b/media/libmedia/include/MediaCodecInfo.h
similarity index 100%
rename from include/media/MediaCodecInfo.h
rename to media/libmedia/include/MediaCodecInfo.h
diff --git a/include/media/MediaDefs.h b/media/libmedia/include/MediaDefs.h
similarity index 96%
rename from include/media/MediaDefs.h
rename to media/libmedia/include/MediaDefs.h
index 0682413..7f17013 100644
--- a/include/media/MediaDefs.h
+++ b/media/libmedia/include/MediaDefs.h
@@ -31,6 +31,7 @@
 extern const char *MEDIA_MIMETYPE_VIDEO_MPEG2;
 extern const char *MEDIA_MIMETYPE_VIDEO_RAW;
 extern const char *MEDIA_MIMETYPE_VIDEO_DOLBY_VISION;
+extern const char *MEDIA_MIMETYPE_VIDEO_SCRAMBLED;
 
 extern const char *MEDIA_MIMETYPE_AUDIO_AMR_NB;
 extern const char *MEDIA_MIMETYPE_AUDIO_AMR_WB;
@@ -50,6 +51,7 @@
 extern const char *MEDIA_MIMETYPE_AUDIO_MSGSM;
 extern const char *MEDIA_MIMETYPE_AUDIO_AC3;
 extern const char *MEDIA_MIMETYPE_AUDIO_EAC3;
+extern const char *MEDIA_MIMETYPE_AUDIO_SCRAMBLED;
 
 extern const char *MEDIA_MIMETYPE_CONTAINER_MPEG4;
 extern const char *MEDIA_MIMETYPE_CONTAINER_WAV;
diff --git a/include/media/MediaMetadataRetrieverInterface.h b/media/libmedia/include/MediaMetadataRetrieverInterface.h
similarity index 100%
rename from include/media/MediaMetadataRetrieverInterface.h
rename to media/libmedia/include/MediaMetadataRetrieverInterface.h
diff --git a/include/media/MediaProfiles.h b/media/libmedia/include/MediaProfiles.h
similarity index 100%
rename from include/media/MediaProfiles.h
rename to media/libmedia/include/MediaProfiles.h
diff --git a/include/media/MediaRecorderBase.h b/media/libmedia/include/MediaRecorderBase.h
similarity index 100%
rename from include/media/MediaRecorderBase.h
rename to media/libmedia/include/MediaRecorderBase.h
diff --git a/include/media/MediaResource.h b/media/libmedia/include/MediaResource.h
similarity index 100%
rename from include/media/MediaResource.h
rename to media/libmedia/include/MediaResource.h
diff --git a/include/media/MediaResourcePolicy.h b/media/libmedia/include/MediaResourcePolicy.h
similarity index 100%
rename from include/media/MediaResourcePolicy.h
rename to media/libmedia/include/MediaResourcePolicy.h
diff --git a/include/media/MemoryLeakTrackUtil.h b/media/libmedia/include/MemoryLeakTrackUtil.h
similarity index 100%
rename from include/media/MemoryLeakTrackUtil.h
rename to media/libmedia/include/MemoryLeakTrackUtil.h
diff --git a/include/media/Metadata.h b/media/libmedia/include/Metadata.h
similarity index 100%
rename from include/media/Metadata.h
rename to media/libmedia/include/Metadata.h
diff --git a/include/media/MidiDeviceInfo.h b/media/libmedia/include/MidiDeviceInfo.h
similarity index 100%
rename from include/media/MidiDeviceInfo.h
rename to media/libmedia/include/MidiDeviceInfo.h
diff --git a/include/media/MidiIoWrapper.h b/media/libmedia/include/MidiIoWrapper.h
similarity index 100%
rename from include/media/MidiIoWrapper.h
rename to media/libmedia/include/MidiIoWrapper.h
diff --git a/include/media/Modulo.h b/media/libmedia/include/Modulo.h
similarity index 100%
rename from include/media/Modulo.h
rename to media/libmedia/include/Modulo.h
diff --git a/include/media/OMXBuffer.h b/media/libmedia/include/OMXBuffer.h
similarity index 100%
rename from include/media/OMXBuffer.h
rename to media/libmedia/include/OMXBuffer.h
diff --git a/include/media/OMXFenceParcelable.h b/media/libmedia/include/OMXFenceParcelable.h
similarity index 100%
rename from include/media/OMXFenceParcelable.h
rename to media/libmedia/include/OMXFenceParcelable.h
diff --git a/include/media/PluginLoader.h b/media/libmedia/include/PluginLoader.h
similarity index 100%
rename from include/media/PluginLoader.h
rename to media/libmedia/include/PluginLoader.h
diff --git a/include/media/RecordBufferConverter.h b/media/libmedia/include/RecordBufferConverter.h
similarity index 100%
rename from include/media/RecordBufferConverter.h
rename to media/libmedia/include/RecordBufferConverter.h
diff --git a/include/media/RingBuffer.h b/media/libmedia/include/RingBuffer.h
similarity index 100%
rename from include/media/RingBuffer.h
rename to media/libmedia/include/RingBuffer.h
diff --git a/include/media/SharedLibrary.h b/media/libmedia/include/SharedLibrary.h
similarity index 100%
rename from include/media/SharedLibrary.h
rename to media/libmedia/include/SharedLibrary.h
diff --git a/include/media/SingleStateQueue.h b/media/libmedia/include/SingleStateQueue.h
similarity index 100%
rename from include/media/SingleStateQueue.h
rename to media/libmedia/include/SingleStateQueue.h
diff --git a/include/media/StringArray.h b/media/libmedia/include/StringArray.h
similarity index 100%
rename from include/media/StringArray.h
rename to media/libmedia/include/StringArray.h
diff --git a/include/media/TypeConverter.h b/media/libmedia/include/TypeConverter.h
similarity index 100%
rename from include/media/TypeConverter.h
rename to media/libmedia/include/TypeConverter.h
diff --git a/include/media/Visualizer.h b/media/libmedia/include/Visualizer.h
similarity index 100%
rename from include/media/Visualizer.h
rename to media/libmedia/include/Visualizer.h
diff --git a/include/media/convert.h b/media/libmedia/include/convert.h
similarity index 100%
rename from include/media/convert.h
rename to media/libmedia/include/convert.h
diff --git a/include/media/mediametadataretriever.h b/media/libmedia/include/mediametadataretriever.h
similarity index 100%
rename from include/media/mediametadataretriever.h
rename to media/libmedia/include/mediametadataretriever.h
diff --git a/include/media/mediaplayer.h b/media/libmedia/include/mediaplayer.h
similarity index 100%
rename from include/media/mediaplayer.h
rename to media/libmedia/include/mediaplayer.h
diff --git a/include/media/mediarecorder.h b/media/libmedia/include/mediarecorder.h
similarity index 100%
rename from include/media/mediarecorder.h
rename to media/libmedia/include/mediarecorder.h
diff --git a/include/media/mediascanner.h b/media/libmedia/include/mediascanner.h
similarity index 100%
rename from include/media/mediascanner.h
rename to media/libmedia/include/mediascanner.h
diff --git a/media/libmediaplayerservice/Android.mk b/media/libmediaplayerservice/Android.mk
index e6d9b71..f7e1ff5 100644
--- a/media/libmediaplayerservice/Android.mk
+++ b/media/libmediaplayerservice/Android.mk
@@ -36,6 +36,7 @@
     libstagefright_omx          \
     libstagefright_wfd          \
     libutils                    \
+    libnativewindow             \
     libhidlbase                 \
     android.hardware.media.omx@1.0 \
 
@@ -51,7 +52,7 @@
     $(TOP)/frameworks/av/media/libstagefright/rtsp                  \
     $(TOP)/frameworks/av/media/libstagefright/wifi-display          \
     $(TOP)/frameworks/av/media/libstagefright/webm                  \
-    $(TOP)/frameworks/av/include/media                              \
+    $(LOCAL_PATH)/include/media                              \
     $(TOP)/frameworks/av/include/camera                             \
     $(TOP)/frameworks/native/include/media/openmax                  \
     $(TOP)/frameworks/native/include/media/hardware                 \
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index a8b6c66..f3fc924 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -1566,7 +1566,8 @@
       mPid(pid),
       mSendLevel(0.0),
       mAuxEffectId(0),
-      mFlags(AUDIO_OUTPUT_FLAG_NONE)
+      mFlags(AUDIO_OUTPUT_FLAG_NONE),
+      mVolumeHandler(new VolumeHandler())
 {
     ALOGV("AudioOutput(%d)", sessionId);
     if (attr != NULL) {
@@ -2030,6 +2031,13 @@
     ALOGV("setVolume");
     t->setVolume(mLeftVolume, mRightVolume);
 
+    // Dispatch any queued VolumeShapers when the track was not open.
+    mVolumeHandler->forall([&t](const sp<VolumeShaper::Configuration> &configuration,
+            const sp<VolumeShaper::Operation> &operation) -> VolumeShaper::Status {
+        return t->applyVolumeShaper(configuration, operation);
+    });
+    mVolumeHandler->reset(); // After dispatching, clear VolumeShaper queue.
+
     mSampleRateHz = sampleRate;
     mFlags = flags;
     mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
@@ -2272,10 +2280,14 @@
 {
     Mutex::Autolock lock(mLock);
     ALOGV("AudioOutput::applyVolumeShaper");
+
+    // We take ownership of the VolumeShaper if set before the track is created.
+    mVolumeHandler->setIdIfNecessary(configuration);
     if (mTrack != 0) {
         return mTrack->applyVolumeShaper(configuration, operation);
+    } else {
+        return mVolumeHandler->applyVolumeShaper(configuration, operation);
     }
-    return VolumeShaper::Status(INVALID_OPERATION);
 }
 
 sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
@@ -2283,8 +2295,9 @@
     Mutex::Autolock lock(mLock);
     if (mTrack != 0) {
         return mTrack->getVolumeShaperState(id);
+    } else {
+        return mVolumeHandler->getVolumeShaperState(id);
     }
-    return nullptr;
 }
 
 // static
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index dff7322..009fe73 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -165,6 +165,7 @@
         float                   mSendLevel;
         int                     mAuxEffectId;
         audio_output_flags_t    mFlags;
+        sp<VolumeHandler>       mVolumeHandler;
         mutable Mutex           mLock;
 
         // static variables below not protected by mutex
diff --git a/include/media/MediaPlayerInterface.h b/media/libmediaplayerservice/include/MediaPlayerInterface.h
similarity index 100%
rename from include/media/MediaPlayerInterface.h
rename to media/libmediaplayerservice/include/MediaPlayerInterface.h
diff --git a/media/libnbaio/Android.bp b/media/libnbaio/Android.bp
index fd7af4f..f511876 100644
--- a/media/libnbaio/Android.bp
+++ b/media/libnbaio/Android.bp
@@ -34,4 +34,8 @@
     ],
 
     include_dirs: ["system/media/audio_utils/include"],
+
+    local_include_dirs: ["include"],
+
+    export_include_dirs: ["include"],
 }
diff --git a/include/media/nbaio/AudioBufferProviderSource.h b/media/libnbaio/include/AudioBufferProviderSource.h
similarity index 100%
rename from include/media/nbaio/AudioBufferProviderSource.h
rename to media/libnbaio/include/AudioBufferProviderSource.h
diff --git a/include/media/nbaio/AudioStreamInSource.h b/media/libnbaio/include/AudioStreamInSource.h
similarity index 100%
rename from include/media/nbaio/AudioStreamInSource.h
rename to media/libnbaio/include/AudioStreamInSource.h
diff --git a/include/media/nbaio/AudioStreamOutSink.h b/media/libnbaio/include/AudioStreamOutSink.h
similarity index 100%
rename from include/media/nbaio/AudioStreamOutSink.h
rename to media/libnbaio/include/AudioStreamOutSink.h
diff --git a/include/media/nbaio/LibsndfileSink.h b/media/libnbaio/include/LibsndfileSink.h
similarity index 100%
rename from include/media/nbaio/LibsndfileSink.h
rename to media/libnbaio/include/LibsndfileSink.h
diff --git a/include/media/nbaio/LibsndfileSource.h b/media/libnbaio/include/LibsndfileSource.h
similarity index 100%
rename from include/media/nbaio/LibsndfileSource.h
rename to media/libnbaio/include/LibsndfileSource.h
diff --git a/include/media/nbaio/MonoPipe.h b/media/libnbaio/include/MonoPipe.h
similarity index 100%
rename from include/media/nbaio/MonoPipe.h
rename to media/libnbaio/include/MonoPipe.h
diff --git a/include/media/nbaio/MonoPipeReader.h b/media/libnbaio/include/MonoPipeReader.h
similarity index 100%
rename from include/media/nbaio/MonoPipeReader.h
rename to media/libnbaio/include/MonoPipeReader.h
diff --git a/include/media/nbaio/NBAIO.h b/media/libnbaio/include/NBAIO.h
similarity index 100%
rename from include/media/nbaio/NBAIO.h
rename to media/libnbaio/include/NBAIO.h
diff --git a/include/media/nbaio/NBLog.h b/media/libnbaio/include/NBLog.h
similarity index 100%
rename from include/media/nbaio/NBLog.h
rename to media/libnbaio/include/NBLog.h
diff --git a/include/media/nbaio/Pipe.h b/media/libnbaio/include/Pipe.h
similarity index 100%
rename from include/media/nbaio/Pipe.h
rename to media/libnbaio/include/Pipe.h
diff --git a/include/media/nbaio/PipeReader.h b/media/libnbaio/include/PipeReader.h
similarity index 100%
rename from include/media/nbaio/PipeReader.h
rename to media/libnbaio/include/PipeReader.h
diff --git a/include/media/nbaio/SourceAudioBufferProvider.h b/media/libnbaio/include/SourceAudioBufferProvider.h
similarity index 100%
rename from include/media/nbaio/SourceAudioBufferProvider.h
rename to media/libnbaio/include/SourceAudioBufferProvider.h
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index d044754..140ceb1 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -93,6 +93,8 @@
         libui \
         libutils \
         libvorbisidec \
+        libmediadrm \
+        libnativewindow \
 
 LOCAL_STATIC_LIBRARIES := \
         libstagefright_color_conversion \
diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp
index 03010ab..6674e2c 100644
--- a/media/libstagefright/MediaCodec.cpp
+++ b/media/libstagefright/MediaCodec.cpp
@@ -23,6 +23,7 @@
 #include "include/SharedMemoryBuffer.h"
 #include "include/SoftwareRenderer.h"
 
+#include <android/media/IDescrambler.h>
 #include <binder/IMemory.h>
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
@@ -680,8 +681,17 @@
 
 status_t MediaCodec::configure(
         const sp<AMessage> &format,
+        const sp<Surface> &nativeWindow,
+        const sp<ICrypto> &crypto,
+        uint32_t flags) {
+    return configure(format, nativeWindow, crypto, NULL, flags);
+}
+
+status_t MediaCodec::configure(
+        const sp<AMessage> &format,
         const sp<Surface> &surface,
         const sp<ICrypto> &crypto,
+        const sp<IDescrambler> &descrambler,
         uint32_t flags) {
     sp<AMessage> msg = new AMessage(kWhatConfigure, this);
 
@@ -710,8 +720,12 @@
     msg->setInt32("flags", flags);
     msg->setObject("surface", surface);
 
-    if (crypto != NULL) {
-        msg->setPointer("crypto", crypto.get());
+    if (crypto != NULL || descrambler != NULL) {
+        if (crypto != NULL) {
+            msg->setPointer("crypto", crypto.get());
+        } else {
+            msg->setPointer("descrambler", descrambler.get());
+        }
         if (mAnalyticsItem != NULL) {
             // XXX: save indication that it's crypto in some way...
             mAnalyticsItem->setInt32("crypto", 1);
@@ -1992,6 +2006,13 @@
             ALOGV("kWhatConfigure: New mCrypto: %p (%d)",
                     mCrypto.get(), (mCrypto != NULL ? mCrypto->getStrongCount() : 0));
 
+            void *descrambler;
+            if (!msg->findPointer("descrambler", &descrambler)) {
+                descrambler = NULL;
+            }
+
+            mDescrambler = static_cast<IDescrambler *>(descrambler);
+
             uint32_t flags;
             CHECK(msg->findInt32("flags", (int32_t *)&flags));
 
@@ -2592,6 +2613,7 @@
                     mCrypto.get(), (mCrypto != NULL ? mCrypto->getStrongCount() : 0));
         }
         mCrypto.clear();
+        mDescrambler.clear();
         handleSetSurface(NULL);
 
         mInputFormat.clear();
diff --git a/media/libstagefright/MediaCodecList.cpp b/media/libstagefright/MediaCodecList.cpp
index d3b34b7..1dcba29 100644
--- a/media/libstagefright/MediaCodecList.cpp
+++ b/media/libstagefright/MediaCodecList.cpp
@@ -169,12 +169,41 @@
     return sRemoteList;
 }
 
+// Treblized media codec list will be located in /odm/etc or /vendor/etc.
+static const char *kConfigLocationList[] =
+        {"/odm/etc", "/vendor/etc", "/etc"};
+static const int kConfigLocationListSize =
+        (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
+
+#define MEDIA_CODECS_CONFIG_FILE_PATH_MAX_LENGTH 128
+
+static bool findMediaCodecListFileFullPath(const char *file_name, char *out_path) {
+    for (int i = 0; i < kConfigLocationListSize; i++) {
+        snprintf(out_path,
+                 MEDIA_CODECS_CONFIG_FILE_PATH_MAX_LENGTH,
+                 "%s/%s",
+                 kConfigLocationList[i],
+                 file_name);
+        struct stat file_stat;
+        if (stat(out_path, &file_stat) == 0 && S_ISREG(file_stat.st_mode)) {
+            return true;
+        }
+    }
+    return false;
+}
+
 MediaCodecList::MediaCodecList()
     : mInitCheck(NO_INIT),
       mUpdate(false),
       mGlobalSettings(new AMessage()) {
-    parseTopLevelXMLFile("/etc/media_codecs.xml");
-    parseTopLevelXMLFile("/etc/media_codecs_performance.xml", true/* ignore_errors */);
+    char config_file_path[MEDIA_CODECS_CONFIG_FILE_PATH_MAX_LENGTH];
+    if (findMediaCodecListFileFullPath("media_codecs.xml", config_file_path)) {
+        parseTopLevelXMLFile(config_file_path);
+    }
+    if (findMediaCodecListFileFullPath("media_codecs_performance.xml",
+                                       config_file_path)) {
+        parseTopLevelXMLFile(config_file_path, true/* ignore_errors */);
+    }
     parseTopLevelXMLFile(kProfilingResults, true/* ignore_errors */);
 }
 
diff --git a/media/libstagefright/NuMediaExtractor.cpp b/media/libstagefright/NuMediaExtractor.cpp
index 1c1acb0..ea3ed28 100644
--- a/media/libstagefright/NuMediaExtractor.cpp
+++ b/media/libstagefright/NuMediaExtractor.cpp
@@ -35,6 +35,7 @@
 #include <media/stagefright/MediaSource.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/Utils.h>
+#include <android/media/ICas.h>
 
 namespace android {
 
@@ -82,6 +83,10 @@
         return ERROR_UNSUPPORTED;
     }
 
+    if (mCas != NULL) {
+        mImpl->setMediaCas(mCas);
+    }
+
     status_t err = updateDurationAndBitrate();
     if (err == OK) {
         mDataSource = dataSource;
@@ -114,6 +119,10 @@
         return ERROR_UNSUPPORTED;
     }
 
+    if (mCas != NULL) {
+        mImpl->setMediaCas(mCas);
+    }
+
     err = updateDurationAndBitrate();
     if (err == OK) {
         mDataSource = fileSource;
@@ -140,6 +149,10 @@
         return ERROR_UNSUPPORTED;
     }
 
+    if (mCas != NULL) {
+        mImpl->setMediaCas(mCas);
+    }
+
     err = updateDurationAndBitrate();
     if (err == OK) {
         mDataSource = source;
@@ -148,6 +161,27 @@
     return err;
 }
 
+status_t NuMediaExtractor::setMediaCas(const sp<ICas> &cas) {
+    ALOGV("setMediaCas: cas=%p", cas.get());
+
+    Mutex::Autolock autoLock(mLock);
+
+    if (cas == NULL) {
+        return BAD_VALUE;
+    }
+
+    if (mImpl != NULL) {
+        mImpl->setMediaCas(cas);
+        status_t err = updateDurationAndBitrate();
+        if (err != OK) {
+            return err;
+        }
+    }
+
+    mCas = cas;
+    return OK;
+}
+
 status_t NuMediaExtractor::updateDurationAndBitrate() {
     if (mImpl->countTracks() > kMaxTrackCount) {
         return ERROR_UNSUPPORTED;
diff --git a/media/libstagefright/foundation/Android.bp b/media/libstagefright/foundation/Android.bp
index 0557d95..3548f96 100644
--- a/media/libstagefright/foundation/Android.bp
+++ b/media/libstagefright/foundation/Android.bp
@@ -26,6 +26,8 @@
 
     include_dirs: ["frameworks/av/include/media/stagefright/foundation"],
 
+    export_include_dirs: ["include"],
+
     shared_libs: [
         "libbinder",
         "libutils",
diff --git a/media/libstagefright/foundation/include b/media/libstagefright/foundation/include
new file mode 120000
index 0000000..3a1af68
--- /dev/null
+++ b/media/libstagefright/foundation/include
@@ -0,0 +1 @@
+../include/
\ No newline at end of file
diff --git a/include/media/stagefright/AACWriter.h b/media/libstagefright/include/AACWriter.h
similarity index 100%
rename from include/media/stagefright/AACWriter.h
rename to media/libstagefright/include/AACWriter.h
diff --git a/include/media/stagefright/ACodec.h b/media/libstagefright/include/ACodec.h
similarity index 100%
rename from include/media/stagefright/ACodec.h
rename to media/libstagefright/include/ACodec.h
diff --git a/include/media/stagefright/AMRWriter.h b/media/libstagefright/include/AMRWriter.h
similarity index 100%
rename from include/media/stagefright/AMRWriter.h
rename to media/libstagefright/include/AMRWriter.h
diff --git a/include/media/stagefright/AudioPlayer.h b/media/libstagefright/include/AudioPlayer.h
similarity index 100%
rename from include/media/stagefright/AudioPlayer.h
rename to media/libstagefright/include/AudioPlayer.h
diff --git a/include/media/stagefright/AudioSource.h b/media/libstagefright/include/AudioSource.h
similarity index 100%
rename from include/media/stagefright/AudioSource.h
rename to media/libstagefright/include/AudioSource.h
diff --git a/include/media/stagefright/BufferProducerWrapper.h b/media/libstagefright/include/BufferProducerWrapper.h
similarity index 100%
rename from include/media/stagefright/BufferProducerWrapper.h
rename to media/libstagefright/include/BufferProducerWrapper.h
diff --git a/include/media/stagefright/CameraSource.h b/media/libstagefright/include/CameraSource.h
similarity index 100%
rename from include/media/stagefright/CameraSource.h
rename to media/libstagefright/include/CameraSource.h
diff --git a/include/media/stagefright/CameraSourceTimeLapse.h b/media/libstagefright/include/CameraSourceTimeLapse.h
similarity index 100%
rename from include/media/stagefright/CameraSourceTimeLapse.h
rename to media/libstagefright/include/CameraSourceTimeLapse.h
diff --git a/include/media/stagefright/CodecBase.h b/media/libstagefright/include/CodecBase.h
similarity index 100%
rename from include/media/stagefright/CodecBase.h
rename to media/libstagefright/include/CodecBase.h
diff --git a/include/media/stagefright/ColorConverter.h b/media/libstagefright/include/ColorConverter.h
similarity index 100%
rename from include/media/stagefright/ColorConverter.h
rename to media/libstagefright/include/ColorConverter.h
diff --git a/include/media/stagefright/DataSource.h b/media/libstagefright/include/DataSource.h
similarity index 100%
rename from include/media/stagefright/DataSource.h
rename to media/libstagefright/include/DataSource.h
diff --git a/include/media/stagefright/DataURISource.h b/media/libstagefright/include/DataURISource.h
similarity index 100%
rename from include/media/stagefright/DataURISource.h
rename to media/libstagefright/include/DataURISource.h
diff --git a/include/media/stagefright/FileSource.h b/media/libstagefright/include/FileSource.h
similarity index 100%
rename from include/media/stagefright/FileSource.h
rename to media/libstagefright/include/FileSource.h
diff --git a/include/media/stagefright/FrameRenderTracker.h b/media/libstagefright/include/FrameRenderTracker.h
similarity index 100%
rename from include/media/stagefright/FrameRenderTracker.h
rename to media/libstagefright/include/FrameRenderTracker.h
diff --git a/include/media/stagefright/JPEGSource.h b/media/libstagefright/include/JPEGSource.h
similarity index 100%
rename from include/media/stagefright/JPEGSource.h
rename to media/libstagefright/include/JPEGSource.h
diff --git a/include/media/stagefright/MPEG2TSWriter.h b/media/libstagefright/include/MPEG2TSWriter.h
similarity index 100%
rename from include/media/stagefright/MPEG2TSWriter.h
rename to media/libstagefright/include/MPEG2TSWriter.h
diff --git a/include/media/stagefright/MPEG4Writer.h b/media/libstagefright/include/MPEG4Writer.h
similarity index 100%
rename from include/media/stagefright/MPEG4Writer.h
rename to media/libstagefright/include/MPEG4Writer.h
diff --git a/include/media/stagefright/MediaAdapter.h b/media/libstagefright/include/MediaAdapter.h
similarity index 100%
rename from include/media/stagefright/MediaAdapter.h
rename to media/libstagefright/include/MediaAdapter.h
diff --git a/include/media/stagefright/MediaBuffer.h b/media/libstagefright/include/MediaBuffer.h
similarity index 100%
rename from include/media/stagefright/MediaBuffer.h
rename to media/libstagefright/include/MediaBuffer.h
diff --git a/include/media/stagefright/MediaBufferGroup.h b/media/libstagefright/include/MediaBufferGroup.h
similarity index 100%
rename from include/media/stagefright/MediaBufferGroup.h
rename to media/libstagefright/include/MediaBufferGroup.h
diff --git a/include/media/stagefright/MediaClock.h b/media/libstagefright/include/MediaClock.h
similarity index 100%
rename from include/media/stagefright/MediaClock.h
rename to media/libstagefright/include/MediaClock.h
diff --git a/include/media/stagefright/MediaCodec.h b/media/libstagefright/include/MediaCodec.h
similarity index 97%
rename from include/media/stagefright/MediaCodec.h
rename to media/libstagefright/include/MediaCodec.h
index 20b26e2..fd3ff26 100644
--- a/include/media/stagefright/MediaCodec.h
+++ b/media/libstagefright/include/MediaCodec.h
@@ -47,6 +47,10 @@
 struct PersistentSurface;
 class SoftwareRenderer;
 class Surface;
+namespace media {
+class IDescrambler;
+};
+using namespace media;
 
 struct MediaCodec : public AHandler {
     enum ConfigureFlags {
@@ -91,6 +95,13 @@
             const sp<ICrypto> &crypto,
             uint32_t flags);
 
+    status_t configure(
+            const sp<AMessage> &format,
+            const sp<Surface> &nativeWindow,
+            const sp<ICrypto> &crypto,
+            const sp<IDescrambler> &descrambler,
+            uint32_t flags);
+
     status_t releaseCrypto();
 
     status_t setCallback(const sp<AMessage> &callback);
@@ -345,6 +356,8 @@
 
     sp<ICrypto> mCrypto;
 
+    sp<IDescrambler> mDescrambler;
+
     List<sp<ABuffer> > mCSD;
 
     sp<AMessage> mActivityNotify;
diff --git a/include/media/stagefright/MediaCodecList.h b/media/libstagefright/include/MediaCodecList.h
similarity index 100%
rename from include/media/stagefright/MediaCodecList.h
rename to media/libstagefright/include/MediaCodecList.h
diff --git a/include/media/stagefright/MediaCodecSource.h b/media/libstagefright/include/MediaCodecSource.h
similarity index 100%
rename from include/media/stagefright/MediaCodecSource.h
rename to media/libstagefright/include/MediaCodecSource.h
diff --git a/include/media/stagefright/MediaDefs.h b/media/libstagefright/include/MediaDefs.h
similarity index 100%
rename from include/media/stagefright/MediaDefs.h
rename to media/libstagefright/include/MediaDefs.h
diff --git a/include/media/stagefright/MediaErrors.h b/media/libstagefright/include/MediaErrors.h
similarity index 100%
rename from include/media/stagefright/MediaErrors.h
rename to media/libstagefright/include/MediaErrors.h
diff --git a/include/media/stagefright/MediaExtractor.h b/media/libstagefright/include/MediaExtractor.h
similarity index 94%
rename from include/media/stagefright/MediaExtractor.h
rename to media/libstagefright/include/MediaExtractor.h
index 9ce6cc5..073391f 100644
--- a/include/media/stagefright/MediaExtractor.h
+++ b/media/libstagefright/include/MediaExtractor.h
@@ -23,7 +23,10 @@
 #include <media/MediaAnalyticsItem.h>
 
 namespace android {
-
+namespace media {
+class ICas;
+};
+using namespace media;
 class DataSource;
 struct MediaSource;
 class MetaData;
@@ -67,6 +70,9 @@
     }
     virtual void setUID(uid_t /*uid*/) {
     }
+    virtual status_t setMediaCas(const sp<ICas> &cas) override {
+        return INVALID_OPERATION;
+    }
 
     virtual const char * name() { return "<unspecified>"; }
 
diff --git a/include/media/stagefright/MediaFilter.h b/media/libstagefright/include/MediaFilter.h
similarity index 100%
rename from include/media/stagefright/MediaFilter.h
rename to media/libstagefright/include/MediaFilter.h
diff --git a/include/media/stagefright/MediaHTTP.h b/media/libstagefright/include/MediaHTTP.h
similarity index 100%
rename from include/media/stagefright/MediaHTTP.h
rename to media/libstagefright/include/MediaHTTP.h
diff --git a/include/media/stagefright/MediaMuxer.h b/media/libstagefright/include/MediaMuxer.h
similarity index 100%
rename from include/media/stagefright/MediaMuxer.h
rename to media/libstagefright/include/MediaMuxer.h
diff --git a/include/media/stagefright/MediaSource.h b/media/libstagefright/include/MediaSource.h
similarity index 100%
rename from include/media/stagefright/MediaSource.h
rename to media/libstagefright/include/MediaSource.h
diff --git a/include/media/stagefright/MediaSync.h b/media/libstagefright/include/MediaSync.h
similarity index 100%
rename from include/media/stagefright/MediaSync.h
rename to media/libstagefright/include/MediaSync.h
diff --git a/include/media/stagefright/MediaWriter.h b/media/libstagefright/include/MediaWriter.h
similarity index 100%
rename from include/media/stagefright/MediaWriter.h
rename to media/libstagefright/include/MediaWriter.h
diff --git a/include/media/stagefright/MetaData.h b/media/libstagefright/include/MetaData.h
similarity index 100%
rename from include/media/stagefright/MetaData.h
rename to media/libstagefright/include/MetaData.h
diff --git a/include/media/stagefright/NuMediaExtractor.h b/media/libstagefright/include/NuMediaExtractor.h
similarity index 96%
rename from include/media/stagefright/NuMediaExtractor.h
rename to media/libstagefright/include/NuMediaExtractor.h
index ad0d37b..3e3cc17 100644
--- a/include/media/stagefright/NuMediaExtractor.h
+++ b/media/libstagefright/include/NuMediaExtractor.h
@@ -28,6 +28,10 @@
 #include <utils/Vector.h>
 
 namespace android {
+namespace media {
+class ICas;
+}
+using namespace media;
 
 struct ABuffer;
 struct AMessage;
@@ -60,6 +64,8 @@
 
     status_t setDataSource(const sp<DataSource> &datasource);
 
+    status_t setMediaCas(const sp<ICas> &cas);
+
     size_t countTracks() const;
     status_t getTrackFormat(size_t index, sp<AMessage> *format, uint32_t flags = 0) const;
 
@@ -109,6 +115,7 @@
     sp<DataSource> mDataSource;
 
     sp<IMediaExtractor> mImpl;
+    sp<ICas> mCas;
 
     Vector<TrackInfo> mSelectedTracks;
     int64_t mTotalBitrate;  // in bits/sec
diff --git a/include/media/stagefright/OMXClient.h b/media/libstagefright/include/OMXClient.h
similarity index 100%
rename from include/media/stagefright/OMXClient.h
rename to media/libstagefright/include/OMXClient.h
diff --git a/include/media/stagefright/PersistentSurface.h b/media/libstagefright/include/PersistentSurface.h
similarity index 100%
rename from include/media/stagefright/PersistentSurface.h
rename to media/libstagefright/include/PersistentSurface.h
diff --git a/include/media/stagefright/ProcessInfo.h b/media/libstagefright/include/ProcessInfo.h
similarity index 100%
rename from include/media/stagefright/ProcessInfo.h
rename to media/libstagefright/include/ProcessInfo.h
diff --git a/include/media/stagefright/ProcessInfoInterface.h b/media/libstagefright/include/ProcessInfoInterface.h
similarity index 100%
rename from include/media/stagefright/ProcessInfoInterface.h
rename to media/libstagefright/include/ProcessInfoInterface.h
diff --git a/include/media/stagefright/RenderScriptWrapper.h b/media/libstagefright/include/RenderScriptWrapper.h
similarity index 100%
rename from include/media/stagefright/RenderScriptWrapper.h
rename to media/libstagefright/include/RenderScriptWrapper.h
diff --git a/include/media/stagefright/SimpleDecodingSource.h b/media/libstagefright/include/SimpleDecodingSource.h
similarity index 100%
rename from include/media/stagefright/SimpleDecodingSource.h
rename to media/libstagefright/include/SimpleDecodingSource.h
diff --git a/include/media/stagefright/SkipCutBuffer.h b/media/libstagefright/include/SkipCutBuffer.h
similarity index 100%
rename from include/media/stagefright/SkipCutBuffer.h
rename to media/libstagefright/include/SkipCutBuffer.h
diff --git a/include/media/stagefright/StagefrightMediaScanner.h b/media/libstagefright/include/StagefrightMediaScanner.h
similarity index 100%
rename from include/media/stagefright/StagefrightMediaScanner.h
rename to media/libstagefright/include/StagefrightMediaScanner.h
diff --git a/include/media/stagefright/SurfaceMediaSource.h b/media/libstagefright/include/SurfaceMediaSource.h
similarity index 100%
rename from include/media/stagefright/SurfaceMediaSource.h
rename to media/libstagefright/include/SurfaceMediaSource.h
diff --git a/include/media/stagefright/SurfaceUtils.h b/media/libstagefright/include/SurfaceUtils.h
similarity index 100%
rename from include/media/stagefright/SurfaceUtils.h
rename to media/libstagefright/include/SurfaceUtils.h
diff --git a/include/media/stagefright/Utils.h b/media/libstagefright/include/Utils.h
similarity index 100%
rename from include/media/stagefright/Utils.h
rename to media/libstagefright/include/Utils.h
diff --git a/include/media/stagefright/VideoFrameScheduler.h b/media/libstagefright/include/VideoFrameScheduler.h
similarity index 100%
rename from include/media/stagefright/VideoFrameScheduler.h
rename to media/libstagefright/include/VideoFrameScheduler.h
diff --git a/include/media/stagefright/YUVCanvas.h b/media/libstagefright/include/YUVCanvas.h
similarity index 100%
rename from include/media/stagefright/YUVCanvas.h
rename to media/libstagefright/include/YUVCanvas.h
diff --git a/include/media/stagefright/YUVImage.h b/media/libstagefright/include/YUVImage.h
similarity index 100%
rename from include/media/stagefright/YUVImage.h
rename to media/libstagefright/include/YUVImage.h
diff --git a/include/media/stagefright/foundation/AAtomizer.h b/media/libstagefright/include/foundation/AAtomizer.h
similarity index 100%
rename from include/media/stagefright/foundation/AAtomizer.h
rename to media/libstagefright/include/foundation/AAtomizer.h
diff --git a/include/media/stagefright/foundation/ABase.h b/media/libstagefright/include/foundation/ABase.h
similarity index 100%
rename from include/media/stagefright/foundation/ABase.h
rename to media/libstagefright/include/foundation/ABase.h
diff --git a/include/media/stagefright/foundation/ABitReader.h b/media/libstagefright/include/foundation/ABitReader.h
similarity index 100%
rename from include/media/stagefright/foundation/ABitReader.h
rename to media/libstagefright/include/foundation/ABitReader.h
diff --git a/include/media/stagefright/foundation/ABuffer.h b/media/libstagefright/include/foundation/ABuffer.h
similarity index 100%
rename from include/media/stagefright/foundation/ABuffer.h
rename to media/libstagefright/include/foundation/ABuffer.h
diff --git a/include/media/stagefright/foundation/AData.h b/media/libstagefright/include/foundation/AData.h
similarity index 100%
rename from include/media/stagefright/foundation/AData.h
rename to media/libstagefright/include/foundation/AData.h
diff --git a/include/media/stagefright/foundation/ADebug.h b/media/libstagefright/include/foundation/ADebug.h
similarity index 100%
rename from include/media/stagefright/foundation/ADebug.h
rename to media/libstagefright/include/foundation/ADebug.h
diff --git a/include/media/stagefright/foundation/AHandler.h b/media/libstagefright/include/foundation/AHandler.h
similarity index 100%
rename from include/media/stagefright/foundation/AHandler.h
rename to media/libstagefright/include/foundation/AHandler.h
diff --git a/include/media/stagefright/foundation/AHandlerReflector.h b/media/libstagefright/include/foundation/AHandlerReflector.h
similarity index 100%
rename from include/media/stagefright/foundation/AHandlerReflector.h
rename to media/libstagefright/include/foundation/AHandlerReflector.h
diff --git a/include/media/stagefright/foundation/AHierarchicalStateMachine.h b/media/libstagefright/include/foundation/AHierarchicalStateMachine.h
similarity index 100%
rename from include/media/stagefright/foundation/AHierarchicalStateMachine.h
rename to media/libstagefright/include/foundation/AHierarchicalStateMachine.h
diff --git a/include/media/stagefright/foundation/ALookup.h b/media/libstagefright/include/foundation/ALookup.h
similarity index 100%
rename from include/media/stagefright/foundation/ALookup.h
rename to media/libstagefright/include/foundation/ALookup.h
diff --git a/include/media/stagefright/foundation/ALooper.h b/media/libstagefright/include/foundation/ALooper.h
similarity index 100%
rename from include/media/stagefright/foundation/ALooper.h
rename to media/libstagefright/include/foundation/ALooper.h
diff --git a/include/media/stagefright/foundation/ALooperRoster.h b/media/libstagefright/include/foundation/ALooperRoster.h
similarity index 100%
rename from include/media/stagefright/foundation/ALooperRoster.h
rename to media/libstagefright/include/foundation/ALooperRoster.h
diff --git a/include/media/stagefright/foundation/AMessage.h b/media/libstagefright/include/foundation/AMessage.h
similarity index 100%
rename from include/media/stagefright/foundation/AMessage.h
rename to media/libstagefright/include/foundation/AMessage.h
diff --git a/include/media/stagefright/foundation/ANetworkSession.h b/media/libstagefright/include/foundation/ANetworkSession.h
similarity index 100%
rename from include/media/stagefright/foundation/ANetworkSession.h
rename to media/libstagefright/include/foundation/ANetworkSession.h
diff --git a/include/media/stagefright/foundation/AString.h b/media/libstagefright/include/foundation/AString.h
similarity index 100%
rename from include/media/stagefright/foundation/AString.h
rename to media/libstagefright/include/foundation/AString.h
diff --git a/include/media/stagefright/foundation/AStringUtils.h b/media/libstagefright/include/foundation/AStringUtils.h
similarity index 100%
rename from include/media/stagefright/foundation/AStringUtils.h
rename to media/libstagefright/include/foundation/AStringUtils.h
diff --git a/include/media/stagefright/foundation/AUtils.h b/media/libstagefright/include/foundation/AUtils.h
similarity index 100%
rename from include/media/stagefright/foundation/AUtils.h
rename to media/libstagefright/include/foundation/AUtils.h
diff --git a/include/media/stagefright/foundation/AWakeLock.h b/media/libstagefright/include/foundation/AWakeLock.h
similarity index 100%
rename from include/media/stagefright/foundation/AWakeLock.h
rename to media/libstagefright/include/foundation/AWakeLock.h
diff --git a/include/media/stagefright/foundation/ColorUtils.h b/media/libstagefright/include/foundation/ColorUtils.h
similarity index 100%
rename from include/media/stagefright/foundation/ColorUtils.h
rename to media/libstagefright/include/foundation/ColorUtils.h
diff --git a/include/media/stagefright/foundation/Flagged.h b/media/libstagefright/include/foundation/Flagged.h
similarity index 100%
rename from include/media/stagefright/foundation/Flagged.h
rename to media/libstagefright/include/foundation/Flagged.h
diff --git a/include/media/stagefright/foundation/MediaBufferBase.h b/media/libstagefright/include/foundation/MediaBufferBase.h
similarity index 100%
rename from include/media/stagefright/foundation/MediaBufferBase.h
rename to media/libstagefright/include/foundation/MediaBufferBase.h
diff --git a/include/media/stagefright/foundation/Mutexed.h b/media/libstagefright/include/foundation/Mutexed.h
similarity index 100%
rename from include/media/stagefright/foundation/Mutexed.h
rename to media/libstagefright/include/foundation/Mutexed.h
diff --git a/include/media/stagefright/foundation/ParsedMessage.h b/media/libstagefright/include/foundation/ParsedMessage.h
similarity index 100%
rename from include/media/stagefright/foundation/ParsedMessage.h
rename to media/libstagefright/include/foundation/ParsedMessage.h
diff --git a/include/media/stagefright/foundation/TypeTraits.h b/media/libstagefright/include/foundation/TypeTraits.h
similarity index 100%
rename from include/media/stagefright/foundation/TypeTraits.h
rename to media/libstagefright/include/foundation/TypeTraits.h
diff --git a/include/media/stagefright/foundation/base64.h b/media/libstagefright/include/foundation/base64.h
similarity index 100%
rename from include/media/stagefright/foundation/base64.h
rename to media/libstagefright/include/foundation/base64.h
diff --git a/include/media/stagefright/foundation/hexdump.h b/media/libstagefright/include/foundation/hexdump.h
similarity index 100%
rename from include/media/stagefright/foundation/hexdump.h
rename to media/libstagefright/include/foundation/hexdump.h
diff --git a/media/libstagefright/matroska/MatroskaExtractor.cpp b/media/libstagefright/matroska/MatroskaExtractor.cpp
index a974671..81179d1 100644
--- a/media/libstagefright/matroska/MatroskaExtractor.cpp
+++ b/media/libstagefright/matroska/MatroskaExtractor.cpp
@@ -1288,8 +1288,51 @@
                     continue;
                 }
 
-                meta->setInt32(kKeyWidth, vtrack->GetWidth());
-                meta->setInt32(kKeyHeight, vtrack->GetHeight());
+                const long long width = vtrack->GetWidth();
+                const long long height = vtrack->GetHeight();
+                if (width <= 0 || width > INT32_MAX) {
+                    ALOGW("track width exceeds int32_t, %lld", width);
+                    continue;
+                }
+                if (height <= 0 || height > INT32_MAX) {
+                    ALOGW("track height exceeds int32_t, %lld", height);
+                    continue;
+                }
+                meta->setInt32(kKeyWidth, (int32_t)width);
+                meta->setInt32(kKeyHeight, (int32_t)height);
+
+                // setting display width/height is optional
+                const long long displayUnit = vtrack->GetDisplayUnit();
+                const long long displayWidth = vtrack->GetDisplayWidth();
+                const long long displayHeight = vtrack->GetDisplayHeight();
+                if (displayWidth > 0 && displayWidth <= INT32_MAX
+                        && displayHeight > 0 && displayHeight <= INT32_MAX) {
+                    switch (displayUnit) {
+                    case 0: // pixels
+                        meta->setInt32(kKeyDisplayWidth, (int32_t)displayWidth);
+                        meta->setInt32(kKeyDisplayHeight, (int32_t)displayHeight);
+                        break;
+                    case 1: // centimeters
+                    case 2: // inches
+                    case 3: // aspect ratio
+                    {
+                        // Physical layout size is treated the same as aspect ratio.
+                        // Note: displayWidth and displayHeight are never zero as they are
+                        // checked in the if above.
+                        const long long computedWidth =
+                                std::max(width, height * displayWidth / displayHeight);
+                        const long long computedHeight =
+                                std::max(height, width * displayHeight / displayWidth);
+                        if (computedWidth <= INT32_MAX && computedHeight <= INT32_MAX) {
+                            meta->setInt32(kKeyDisplayWidth, (int32_t)computedWidth);
+                            meta->setInt32(kKeyDisplayHeight, (int32_t)computedHeight);
+                        }
+                        break;
+                    }
+                    default: // unknown display units, perhaps future version of spec.
+                        break;
+                    }
+                }
 
                 getColorInformation(vtrack, meta);
 
diff --git a/media/libstagefright/omx/hal/1.0/impl/Android.mk b/media/libstagefright/omx/hal/1.0/impl/Android.mk
index db0cb4e..09424b5 100644
--- a/media/libstagefright/omx/hal/1.0/impl/Android.mk
+++ b/media/libstagefright/omx/hal/1.0/impl/Android.mk
@@ -32,6 +32,10 @@
     android.hardware.media@1.0 \
     android.hidl.base@1.0 \
 
+LOCAL_C_FLAGS += \
+    -Wno-unused-parameter \
+    -Werror
+
 LOCAL_C_INCLUDES += \
         $(TOP)/frameworks/av/include \
         $(TOP)/frameworks/av/media/libstagefright \
diff --git a/media/mtp/MtpFfsHandle.cpp b/media/mtp/MtpFfsHandle.cpp
index 58d2bb8..35dd10f 100644
--- a/media/mtp/MtpFfsHandle.cpp
+++ b/media/mtp/MtpFfsHandle.cpp
@@ -205,13 +205,13 @@
 const struct usb_ss_ep_comp_descriptor ss_sink_comp = {
     .bLength = sizeof(ss_sink_comp),
     .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
-    .bMaxBurst = 2,
+    .bMaxBurst = 6,
 };
 
 const struct usb_ss_ep_comp_descriptor ss_source_comp = {
     .bLength = sizeof(ss_source_comp),
     .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
-    .bMaxBurst = 2,
+    .bMaxBurst = 6,
 };
 
 const struct usb_ss_ep_comp_descriptor ss_intr_comp = {
diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h
index f33c710..f84ba08 100644
--- a/services/audioflinger/PlaybackTracks.h
+++ b/services/audioflinger/PlaybackTracks.h
@@ -59,6 +59,10 @@
             bool        isOffloaded() const
                                 { return (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; }
             bool        isDirect() const { return (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0; }
+            bool        isOffloadedOrDirect() const { return (mFlags
+                            & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
+                                    | AUDIO_OUTPUT_FLAG_DIRECT)) != 0; }
+
             status_t    setParameters(const String8& keyValuePairs);
             status_t    attachAuxEffect(int EffectId);
             void        setAuxBuffer(int EffectId, int32_t *buffer);
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index 8bf1688..b10e42c 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -3063,8 +3063,13 @@
                     releaseWakeLock_l();
                     released = true;
                 }
-                ALOGV("wait async completion");
-                mWaitWorkCV.wait(mLock);
+
+                const int64_t waitNs = computeWaitTimeNs_l();
+                ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
+                status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
+                if (status == TIMED_OUT) {
+                    mSignalPending = true; // if timeout recheck everything
+                }
                 ALOGV("async completion/wake");
                 if (released) {
                     acquireWakeLock_l();
@@ -4131,7 +4136,7 @@
                 // cache the combined master volume and stream type volume for fast mixer; this
                 // lacks any synchronization or barrier so VolumeProvider may read a stale value
                 const float vh = track->getVolumeHandler()->getVolume(
-                        track->mAudioTrackServerProxy->framesReleased());
+                        track->mAudioTrackServerProxy->framesReleased()).first;
                 track->mCachedVolume = masterVolume
                         * mStreamTypes[track->streamType()].volume
                         * vh;
@@ -4277,7 +4282,7 @@
                     vrf = GAIN_FLOAT_UNITY;
                 }
                 const float vh = track->getVolumeHandler()->getVolume(
-                        track->mAudioTrackServerProxy->framesReleased());
+                        track->mAudioTrackServerProxy->framesReleased()).first;
                 // now apply the master volume and stream type volume and shaper volume
                 vlf *= v * vh;
                 vrf *= v * vh;
@@ -4756,6 +4761,7 @@
         ThreadBase::type_t type, bool systemReady)
     :   PlaybackThread(audioFlinger, output, id, device, type, systemReady)
         // mLeftVolFloat, mRightVolFloat
+        , mVolumeShaperActive(false)
 {
 }
 
@@ -4774,13 +4780,12 @@
         float v = mMasterVolume * typeVolume;
         sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
 
-        if (audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
-            const float vh = track->getVolumeHandler()->getVolume(
+        // Get volumeshaper scaling
+        std::pair<float /* volume */, bool /* active */>
+            vh = track->getVolumeHandler()->getVolume(
                     track->mAudioTrackServerProxy->framesReleased());
-            v *= vh;
-        } else {
-            // TODO: implement volume scaling in HW
-        }
+        v *= vh.first;
+        mVolumeShaperActive = vh.second;
 
         gain_minifloat_packed_t vlr = proxy->getVolumeLR();
         left = float_from_gain(gain_minifloat_unpack_left(vlr));
@@ -5238,6 +5243,13 @@
     mFlushPending = false;
 }
 
+int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
+    // If a VolumeShaper is active, we must wake up periodically to update volume.
+    const int64_t NS_PER_MS = 1000000;
+    return mVolumeShaperActive ?
+            kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
+}
+
 // ----------------------------------------------------------------------------
 
 AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index 2a6652d..0a17a8e 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -757,6 +757,9 @@
 
     virtual     void        getAudioPortConfig(struct audio_port_config *config);
 
+                // Return the asynchronous signal wait time.
+    virtual     int64_t     computeWaitTimeNs_l() const { return INT64_MAX; }
+
 protected:
     // updated by readOutputParameters_l()
     size_t                          mNormalFrameCount;  // normal mixer and effects
@@ -1174,6 +1177,7 @@
     // volumes last sent to audio HAL with stream->set_volume()
     float mLeftVolFloat;
     float mRightVolFloat;
+    bool mVolumeShaperActive;
 
     DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
                         audio_io_handle_t id, uint32_t device, ThreadBase::type_t type,
@@ -1187,6 +1191,8 @@
 
 public:
     virtual     bool        hasFastMixer() const { return false; }
+
+    virtual     int64_t     computeWaitTimeNs_l() const override;
 };
 
 class OffloadThread : public DirectOutputThread {
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index edf41fd..5e07e3b 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -905,10 +905,33 @@
         const sp<VolumeShaper::Configuration>& configuration,
         const sp<VolumeShaper::Operation>& operation)
 {
-    // Note: We don't check if Thread exists.
+    sp<VolumeShaper::Configuration> newConfiguration;
 
-    // mVolumeHandler is thread-safe.
-    return mVolumeHandler->applyVolumeShaper(configuration, operation);
+    if (isOffloadedOrDirect()) {
+        const VolumeShaper::Configuration::OptionFlag optionFlag
+            = configuration->getOptionFlags();
+        if ((optionFlag & VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME) == 0) {
+            ALOGW("%s tracks do not support frame counted VolumeShaper,"
+                    " using clock time instead", isOffloaded() ? "Offload" : "Direct");
+            newConfiguration = new VolumeShaper::Configuration(*configuration);
+            newConfiguration->setOptionFlags(
+                VolumeShaper::Configuration::OptionFlag(optionFlag
+                        | VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME));
+        }
+    }
+
+    VolumeShaper::Status status = mVolumeHandler->applyVolumeShaper(
+            (newConfiguration.get() != nullptr ? newConfiguration : configuration), operation);
+
+    if (isOffloadedOrDirect()) {
+        // Signal thread to fetch new volume.
+        sp<ThreadBase> thread = mThread.promote();
+        if (thread != 0) {
+             Mutex::Autolock _l(thread->mLock);
+            thread->broadcast_l();
+        }
+    }
+    return status;
 }
 
 sp<VolumeShaper::State> AudioFlinger::PlaybackThread::Track::getVolumeShaperState(int id)
diff --git a/services/mediadrm/Android.mk b/services/mediadrm/Android.mk
index e72236d..87fddd4 100644
--- a/services/mediadrm/Android.mk
+++ b/services/mediadrm/Android.mk
@@ -17,6 +17,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
+    MediaCasService.cpp \
     MediaDrmService.cpp \
     main_mediadrmserver.cpp
 
diff --git a/services/mediadrm/FactoryLoader.h b/services/mediadrm/FactoryLoader.h
new file mode 100644
index 0000000..1e03e9b
--- /dev/null
+++ b/services/mediadrm/FactoryLoader.h
@@ -0,0 +1,220 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef MEDIA_CAS_LOADER_H_
+#define MEDIA_CAS_LOADER_H_
+
+#include <dirent.h>
+#include <dlfcn.h>
+#include <media/SharedLibrary.h>
+#include <utils/KeyedVector.h>
+#include <utils/Mutex.h>
+
+namespace android {
+using namespace std;
+using namespace media;
+using namespace MediaCas;
+
+template <class T>
+class FactoryLoader {
+public:
+    FactoryLoader(const char *name) :
+        mFactory(NULL), mCreateFactoryFuncName(name) {}
+
+    virtual ~FactoryLoader() { closeFactory(); }
+
+    bool findFactoryForScheme(
+            int32_t CA_system_id,
+            sp<SharedLibrary> *library = NULL,
+            T** factory = NULL);
+
+    bool enumeratePlugins(vector<ParcelableCasPluginDescriptor>* results);
+
+private:
+    typedef T*(*CreateFactoryFunc)();
+
+    Mutex mMapLock;
+    T* mFactory;
+    const char *mCreateFactoryFuncName;
+    sp<SharedLibrary> mLibrary;
+    KeyedVector<int32_t, String8> mCASystemIdToLibraryPathMap;
+    KeyedVector<String8, wp<SharedLibrary> > mLibraryPathToOpenLibraryMap;
+
+    bool loadFactoryForSchemeFromPath(
+            const String8 &path,
+            int32_t CA_system_id,
+            sp<SharedLibrary> *library,
+            T** factory);
+
+    bool queryPluginsFromPath(
+            const String8 &path,
+            vector<ParcelableCasPluginDescriptor>* results);
+
+    bool openFactory(const String8 &path);
+    void closeFactory();
+};
+
+template <class T>
+bool FactoryLoader<T>::findFactoryForScheme(
+        int32_t CA_system_id, sp<SharedLibrary> *library, T** factory) {
+    if (library != NULL) {
+        library->clear();
+    }
+    if (factory != NULL) {
+        *factory = NULL;
+    }
+
+    Mutex::Autolock autoLock(mMapLock);
+
+    // first check cache
+    ssize_t index = mCASystemIdToLibraryPathMap.indexOfKey(CA_system_id);
+    if (index >= 0) {
+        return loadFactoryForSchemeFromPath(
+                mCASystemIdToLibraryPathMap[index],
+                CA_system_id, library, factory);
+    }
+
+    // no luck, have to search
+    String8 dirPath("/vendor/lib/mediacas");
+    DIR* pDir = opendir(dirPath.string());
+
+    if (pDir == NULL) {
+        ALOGE("Failed to open plugin directory %s", dirPath.string());
+        return false;
+    }
+
+    struct dirent* pEntry;
+    while ((pEntry = readdir(pDir))) {
+        String8 pluginPath = dirPath + "/" + pEntry->d_name;
+        if (pluginPath.getPathExtension() == ".so") {
+            if (loadFactoryForSchemeFromPath(
+                    pluginPath, CA_system_id, library, factory)) {
+                mCASystemIdToLibraryPathMap.add(CA_system_id, pluginPath);
+                closedir(pDir);
+
+                return true;
+            }
+        }
+    }
+
+    closedir(pDir);
+
+    ALOGE("Failed to find plugin");
+    return false;
+}
+
+template <class T>
+bool FactoryLoader<T>::enumeratePlugins(
+        vector<ParcelableCasPluginDescriptor>* results) {
+    ALOGI("enumeratePlugins");
+
+    results->clear();
+
+    String8 dirPath("/vendor/lib/mediacas");
+    DIR* pDir = opendir(dirPath.string());
+
+    if (pDir == NULL) {
+        ALOGE("Failed to open plugin directory %s", dirPath.string());
+        return false;
+    }
+
+    Mutex::Autolock autoLock(mMapLock);
+
+    struct dirent* pEntry;
+    while ((pEntry = readdir(pDir))) {
+        String8 pluginPath = dirPath + "/" + pEntry->d_name;
+        if (pluginPath.getPathExtension() == ".so") {
+            queryPluginsFromPath(pluginPath, results);
+        }
+    }
+    return true;
+}
+
+template <class T>
+bool FactoryLoader<T>::loadFactoryForSchemeFromPath(
+        const String8 &path, int32_t CA_system_id,
+        sp<SharedLibrary> *library, T** factory) {
+    closeFactory();
+
+    if (!openFactory(path) || !mFactory->isSystemIdSupported(CA_system_id)) {
+        closeFactory();
+        return false;
+    }
+
+    if (library != NULL) {
+        *library = mLibrary;
+    }
+    if (factory != NULL) {
+        *factory = mFactory;
+    }
+    return true;
+}
+
+template <class T>
+bool FactoryLoader<T>::queryPluginsFromPath(
+        const String8 &path, vector<ParcelableCasPluginDescriptor>* results) {
+    closeFactory();
+
+    vector<CasPluginDescriptor> descriptors;
+    if (!openFactory(path) || mFactory->queryPlugins(&descriptors) != OK) {
+        closeFactory();
+        return false;
+    }
+
+    for (auto it = descriptors.begin(); it != descriptors.end(); it++) {
+        results->push_back(ParcelableCasPluginDescriptor(
+                it->CA_system_id, it->name));
+    }
+    return true;
+}
+
+template <class T>
+bool FactoryLoader<T>::openFactory(const String8 &path) {
+    // get strong pointer to open shared library
+    ssize_t index = mLibraryPathToOpenLibraryMap.indexOfKey(path);
+    if (index >= 0) {
+        mLibrary = mLibraryPathToOpenLibraryMap[index].promote();
+    } else {
+        index = mLibraryPathToOpenLibraryMap.add(path, NULL);
+    }
+
+    if (!mLibrary.get()) {
+        mLibrary = new SharedLibrary(path);
+        if (!*mLibrary) {
+            return false;
+        }
+
+        mLibraryPathToOpenLibraryMap.replaceValueAt(index, mLibrary);
+    }
+
+    CreateFactoryFunc createFactory =
+        (CreateFactoryFunc)mLibrary->lookup(mCreateFactoryFuncName);
+    if (createFactory == NULL || (mFactory = createFactory()) == NULL) {
+        return false;
+    }
+    return true;
+}
+
+template <class T>
+void FactoryLoader<T>::closeFactory() {
+    delete mFactory;
+    mFactory = NULL;
+    mLibrary.clear();
+}
+
+} // namespace android
+
+#endif // MEDIA_CAS_LOADER_H_
diff --git a/services/mediadrm/MediaCasService.cpp b/services/mediadrm/MediaCasService.cpp
new file mode 100644
index 0000000..c111283
--- /dev/null
+++ b/services/mediadrm/MediaCasService.cpp
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "MediaCasService"
+
+#include <binder/IServiceManager.h>
+#include <media/cas/CasAPI.h>
+#include <media/cas/DescramblerAPI.h>
+#include <media/CasImpl.h>
+#include <media/DescramblerImpl.h>
+#include <utils/Log.h>
+#include <utils/List.h>
+#include "MediaCasService.h"
+#include <android/media/ICasListener.h>
+
+namespace android {
+
+//static
+void MediaCasService::instantiate() {
+    defaultServiceManager()->addService(
+            String16("media.cas"), new MediaCasService());
+}
+
+MediaCasService::MediaCasService() :
+    mCasLoader(new FactoryLoader<CasFactory>("createCasFactory")),
+    mDescramblerLoader(new FactoryLoader<DescramblerFactory>(
+            "createDescramblerFactory")) {
+}
+
+MediaCasService::~MediaCasService() {
+    delete mCasLoader;
+    delete mDescramblerLoader;
+}
+
+Status MediaCasService::enumeratePlugins(
+        vector<ParcelableCasPluginDescriptor>* results) {
+    ALOGV("enumeratePlugins");
+
+    mCasLoader->enumeratePlugins(results);
+
+    return Status::ok();
+}
+
+Status MediaCasService::isSystemIdSupported(
+        int32_t CA_system_id, bool* result) {
+    ALOGV("isSystemIdSupported: CA_system_id=%d", CA_system_id);
+
+    *result = mCasLoader->findFactoryForScheme(CA_system_id);
+
+    return Status::ok();
+}
+
+Status MediaCasService::createPlugin(
+        int32_t CA_system_id,
+        const sp<ICasListener> &listener,
+        sp<ICas>* result) {
+    ALOGV("createPlugin: CA_system_id=%d", CA_system_id);
+
+    result->clear();
+
+    CasFactory *factory;
+    sp<SharedLibrary> library;
+    if (mCasLoader->findFactoryForScheme(CA_system_id, &library, &factory)) {
+        CasPlugin *plugin = NULL;
+        sp<CasImpl> casImpl = new CasImpl(listener);
+        if (factory->createPlugin(CA_system_id, (uint64_t)casImpl.get(),
+                &CasImpl::OnEvent, &plugin) == OK && plugin != NULL) {
+            casImpl->init(library, plugin);
+            *result = casImpl;
+        }
+    }
+
+    return Status::ok();
+}
+
+Status MediaCasService::isDescramblerSupported(
+        int32_t CA_system_id, bool* result) {
+    ALOGV("isDescramblerSupported: CA_system_id=%d", CA_system_id);
+
+    *result = mDescramblerLoader->findFactoryForScheme(CA_system_id);
+
+    return Status::ok();
+}
+
+Status MediaCasService::createDescrambler(
+        int32_t CA_system_id, sp<IDescrambler>* result) {
+    ALOGV("createDescrambler: CA_system_id=%d", CA_system_id);
+
+    result->clear();
+
+    DescramblerFactory *factory;
+    sp<SharedLibrary> library;
+    if (mDescramblerLoader->findFactoryForScheme(
+            CA_system_id, &library, &factory)) {
+        DescramblerPlugin *plugin = NULL;
+        if (factory->createPlugin(CA_system_id, &plugin) == OK
+                && plugin != NULL) {
+            *result = new DescramblerImpl(library, plugin);
+        }
+    }
+
+    return Status::ok();
+}
+
+} // namespace android
diff --git a/services/mediadrm/MediaCasService.h b/services/mediadrm/MediaCasService.h
new file mode 100644
index 0000000..cb828f2
--- /dev/null
+++ b/services/mediadrm/MediaCasService.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef MEDIA_CAS_SERVICE_H_
+#define MEDIA_CAS_SERVICE_H_
+
+#include <android/media/BnMediaCasService.h>
+
+#include "FactoryLoader.h"
+
+namespace android {
+using binder::Status;
+struct CasFactory;
+struct DescramblerFactory;
+
+class MediaCasService : public BnMediaCasService {
+public:
+    static void instantiate();
+
+    virtual Status enumeratePlugins(
+            vector<ParcelableCasPluginDescriptor>* results) override;
+
+    virtual Status isSystemIdSupported(
+            int32_t CA_system_id, bool* result) override;
+
+    virtual Status createPlugin(
+            int32_t CA_system_id,
+            const sp<ICasListener> &listener,
+            sp<ICas>* result) override;
+
+    virtual Status isDescramblerSupported(
+            int32_t CA_system_id, bool* result) override;
+
+    virtual Status createDescrambler(
+            int32_t CA_system_id, sp<IDescrambler>* result) override;
+
+private:
+    FactoryLoader<CasFactory> *mCasLoader;
+    FactoryLoader<DescramblerFactory> *mDescramblerLoader;
+
+    MediaCasService();
+    virtual ~MediaCasService();
+};
+
+} // namespace android
+
+#endif // MEDIA_CAS_SERVICE_H_
diff --git a/services/mediadrm/main_mediadrmserver.cpp b/services/mediadrm/main_mediadrmserver.cpp
index b767b8c..b685ae0 100644
--- a/services/mediadrm/main_mediadrmserver.cpp
+++ b/services/mediadrm/main_mediadrmserver.cpp
@@ -27,6 +27,7 @@
 #include <cutils/properties.h>
 #include <utils/Log.h>
 #include "MediaDrmService.h"
+#include "MediaCasService.h"
 
 using namespace android;
 
@@ -38,6 +39,7 @@
     sp<IServiceManager> sm = defaultServiceManager();
     ALOGI("ServiceManager: %p", sm.get());
     MediaDrmService::instantiate();
+    MediaCasService::instantiate();
     ProcessState::self()->startThreadPool();
     IPCThreadState::self()->joinThreadPool();
 }
diff --git a/services/oboeservice/FakeAudioHal.cpp b/services/oboeservice/FakeAudioHal.cpp
index 34a2476..122671e 100644
--- a/services/oboeservice/FakeAudioHal.cpp
+++ b/services/oboeservice/FakeAudioHal.cpp
@@ -23,9 +23,6 @@
 #include <string.h>
 #include <unistd.h>
 
-#define __force
-#define __bitwise
-#define __user
 #include <sound/asound.h>
 
 #include "tinyalsa/asoundlib.h"
diff --git a/services/radio/RadioHalHidl.cpp b/services/radio/RadioHalHidl.cpp
index 3dcf2f3..bfc5500 100644
--- a/services/radio/RadioHalHidl.cpp
+++ b/services/radio/RadioHalHidl.cpp
@@ -116,7 +116,7 @@
 sp<IBroadcastRadio> RadioHalHidl::getService()
 {
     if (mHalModule == 0) {
-        sp<IBroadcastRadioFactory> factory = IBroadcastRadioFactory::getService("broadcastradio");
+        sp<IBroadcastRadioFactory> factory = IBroadcastRadioFactory::getService();
         if (factory != 0) {
             factory->connectModule(static_cast<Class>(mClassId),
                                [&](Result retval, const ::android::sp<IBroadcastRadio>& result) {