Merge "Fixing crash in surround sound settings which occurs due to API getSurroundSound." into sc-dev
diff --git a/Android.bp b/Android.bp
index a7cf3e5..944cdc1 100644
--- a/Android.bp
+++ b/Android.bp
@@ -33,10 +33,10 @@
     name: "av-headers",
     export_include_dirs: ["include"],
     static_libs: [
-        "av-types-aidl-unstable-cpp",
+        "av-types-aidl-cpp",
     ],
     export_static_lib_headers: [
-        "av-types-aidl-unstable-cpp",
+        "av-types-aidl-cpp",
     ],
     header_libs: [
         "libaudioclient_aidl_conversion_util",
diff --git a/camera/ndk/include/camera/NdkCameraCaptureSession.h b/camera/ndk/include/camera/NdkCameraCaptureSession.h
index 07176cf..6c1cf33 100644
--- a/camera/ndk/include/camera/NdkCameraCaptureSession.h
+++ b/camera/ndk/include/camera/NdkCameraCaptureSession.h
@@ -45,8 +45,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraCaptureSession is an opaque type that manages frame captures of a camera device.
  *
@@ -593,10 +591,6 @@
 camera_status_t ACameraCaptureSession_abortCaptures(ACameraCaptureSession* session)
         __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 28
-
 typedef struct ACaptureSessionOutput ACaptureSessionOutput;
 
 /**
@@ -641,9 +635,7 @@
  */
 camera_status_t ACameraCaptureSession_updateSharedOutput(ACameraCaptureSession* session,
         ACaptureSessionOutput* output) __INTRODUCED_IN(28);
-#endif /* __ANDROID_API__ >= 28 */
 
-#if __ANDROID_API__ >= 29
 /**
  * The definition of final capture result callback with logical multi-camera support.
  *
@@ -788,8 +780,6 @@
         int numRequests, ACaptureRequest** requests,
         /*optional*/int* captureSequenceId) __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_CAPTURE_SESSION_H */
diff --git a/camera/ndk/include/camera/NdkCameraDevice.h b/camera/ndk/include/camera/NdkCameraDevice.h
index 1537bde..f72fe8d 100644
--- a/camera/ndk/include/camera/NdkCameraDevice.h
+++ b/camera/ndk/include/camera/NdkCameraDevice.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraDevice is opaque type that provides access to a camera device.
  *
@@ -687,10 +685,6 @@
         const ACameraCaptureSession_stateCallbacks* callbacks,
         /*out*/ACameraCaptureSession** session) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 28
-
 /**
  * Create a shared ACaptureSessionOutput object.
  *
@@ -782,10 +776,6 @@
         const ACameraCaptureSession_stateCallbacks* callbacks,
         /*out*/ACameraCaptureSession** session) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Create a ACaptureSessionOutput object used for streaming from a physical
  * camera as part of a logical camera device.
@@ -890,8 +880,6 @@
         const ACameraDevice* device,
         const ACaptureSessionOutputContainer* sessionOutputContainer) __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_DEVICE_H */
diff --git a/camera/ndk/include/camera/NdkCameraError.h b/camera/ndk/include/camera/NdkCameraError.h
index fc618ee..9d77eb4 100644
--- a/camera/ndk/include/camera/NdkCameraError.h
+++ b/camera/ndk/include/camera/NdkCameraError.h
@@ -40,8 +40,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 typedef enum {
     ACAMERA_OK = 0,
 
@@ -138,8 +136,6 @@
     ACAMERA_ERROR_UNSUPPORTED_OPERATION = ACAMERA_ERROR_BASE - 14,
 } camera_status_t;
 
-#endif /* __ANDROID_API__ >= 24 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_ERROR_H */
diff --git a/camera/ndk/include/camera/NdkCameraManager.h b/camera/ndk/include/camera/NdkCameraManager.h
index 0a2ee57..be32b11 100644
--- a/camera/ndk/include/camera/NdkCameraManager.h
+++ b/camera/ndk/include/camera/NdkCameraManager.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraManager is opaque type that provides access to camera service.
  *
@@ -293,10 +291,6 @@
         ACameraDevice_StateCallbacks* callback,
         /*out*/ACameraDevice** device) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Definition of camera access permission change callback.
  *
@@ -419,8 +413,6 @@
         __INTRODUCED_IN(29);
 #endif
 
-#endif /* __ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_MANAGER_H */
diff --git a/camera/ndk/include/camera/NdkCameraMetadata.h b/camera/ndk/include/camera/NdkCameraMetadata.h
index a840bd1..0d5e6c4 100644
--- a/camera/ndk/include/camera/NdkCameraMetadata.h
+++ b/camera/ndk/include/camera/NdkCameraMetadata.h
@@ -41,9 +41,7 @@
 #include <sys/cdefs.h>
 
 #ifndef __ANDROID_VNDK__
-#if __ANDROID_API__ >= 30
 #include "jni.h"
-#endif  /* __ANDROID_API__ >= 30 */
 #endif  /* __ANDROID_VNDK__ */
 
 #include "NdkCameraError.h"
@@ -51,8 +49,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraMetadata is opaque type that provides access to read-only camera metadata like camera
  * characteristics (via {@link ACameraManager_getCameraCharacteristics}) or capture results (via
@@ -238,10 +234,6 @@
  */
 void ACameraMetadata_free(ACameraMetadata* metadata) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Helper function to check if a camera is logical multi-camera.
  *
@@ -260,10 +252,7 @@
         /*out*/size_t* numPhysicalCameras, /*out*/const char* const** physicalCameraIds)
         __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
 #ifndef __ANDROID_VNDK__
-#if __ANDROID_API__ >= 30
 
 /**
  * Return a {@link ACameraMetadata} that references the same data as
@@ -290,7 +279,6 @@
 ACameraMetadata* ACameraMetadata_fromCameraMetadata(JNIEnv* env, jobject cameraMetadata)
         __INTRODUCED_IN(30);
 
-#endif /* __ANDROID_API__ >= 30 */
 #endif  /* __ANDROID_VNDK__ */
 
 __END_DECLS
diff --git a/camera/ndk/include/camera/NdkCameraMetadataTags.h b/camera/ndk/include/camera/NdkCameraMetadataTags.h
index c7c3dd5..a2aa529 100644
--- a/camera/ndk/include/camera/NdkCameraMetadataTags.h
+++ b/camera/ndk/include/camera/NdkCameraMetadataTags.h
@@ -40,8 +40,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 typedef enum acamera_metadata_section {
     ACAMERA_COLOR_CORRECTION,
     ACAMERA_CONTROL,
@@ -9145,8 +9143,6 @@
 
 
 
-#endif /* __ANDROID_API__ >= 24 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_METADATA_TAGS_H */
diff --git a/camera/ndk/include/camera/NdkCaptureRequest.h b/camera/ndk/include/camera/NdkCaptureRequest.h
index d3f8826..a4dc374 100644
--- a/camera/ndk/include/camera/NdkCaptureRequest.h
+++ b/camera/ndk/include/camera/NdkCaptureRequest.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 // Container for output targets
 typedef struct ACameraOutputTargets ACameraOutputTargets;
 
@@ -304,10 +302,6 @@
  */
 void ACaptureRequest_free(ACaptureRequest* request) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 28
-
 /**
  * Associate an arbitrary user context pointer to the {@link ACaptureRequest}
  *
@@ -356,10 +350,6 @@
  */
 ACaptureRequest* ACaptureRequest_copy(const ACaptureRequest* src) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Get a metadata entry from input {@link ACaptureRequest} for
  * a physical camera backing a logical multi-camera device.
@@ -569,8 +559,6 @@
         ACaptureRequest* request, const char* physicalId, uint32_t tag,
         uint32_t count, const ACameraMetadata_rational* data) __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif /* _NDK_CAPTURE_REQUEST_H */
diff --git a/cmds/screenrecord/screenrecord.cpp b/cmds/screenrecord/screenrecord.cpp
index b31a58b..e6e3473 100644
--- a/cmds/screenrecord/screenrecord.cpp
+++ b/cmds/screenrecord/screenrecord.cpp
@@ -57,7 +57,7 @@
 #include <media/stagefright/foundation/ABuffer.h>
 #include <media/stagefright/foundation/AMessage.h>
 #include <mediadrm/ICrypto.h>
-#include <ui/DisplayConfig.h>
+#include <ui/DisplayMode.h>
 #include <ui/DisplayState.h>
 
 #include "screenrecord.h"
@@ -68,7 +68,7 @@
 using android::ALooper;
 using android::AMessage;
 using android::AString;
-using android::DisplayConfig;
+using android::ui::DisplayMode;
 using android::FrameOutput;
 using android::IBinder;
 using android::IGraphicBufferProducer;
@@ -689,8 +689,8 @@
         return err;
     }
 
-    DisplayConfig displayConfig;
-    err = SurfaceComposerClient::getActiveDisplayConfig(display, &displayConfig);
+    DisplayMode displayMode;
+    err = SurfaceComposerClient::getActiveDisplayMode(display, &displayMode);
     if (err != NO_ERROR) {
         fprintf(stderr, "ERROR: unable to get display config\n");
         return err;
@@ -700,7 +700,7 @@
     if (gVerbose) {
         printf("Display is %dx%d @%.2ffps (orientation=%s), layerStack=%u\n",
                 layerStackSpaceRect.getWidth(), layerStackSpaceRect.getHeight(),
-                displayConfig.refreshRate, toCString(displayState.orientation),
+                displayMode.refreshRate, toCString(displayState.orientation),
                 displayState.layerStack);
         fflush(stdout);
     }
@@ -718,7 +718,7 @@
     sp<FrameOutput> frameOutput;
     sp<IGraphicBufferProducer> encoderInputSurface;
     if (gOutputFormat != FORMAT_FRAMES && gOutputFormat != FORMAT_RAW_FRAMES) {
-        err = prepareEncoder(displayConfig.refreshRate, &encoder, &encoderInputSurface);
+        err = prepareEncoder(displayMode.refreshRate, &encoder, &encoderInputSurface);
 
         if (err != NO_ERROR && !gSizeSpecified) {
             // fallback is defined for landscape; swap if we're in portrait
@@ -731,7 +731,7 @@
                         gVideoWidth, gVideoHeight, newWidth, newHeight);
                 gVideoWidth = newWidth;
                 gVideoHeight = newHeight;
-                err = prepareEncoder(displayConfig.refreshRate, &encoder, &encoderInputSurface);
+                err = prepareEncoder(displayMode.refreshRate, &encoder, &encoderInputSurface);
             }
         }
         if (err != NO_ERROR) return err;
diff --git a/cmds/stagefright/codec.cpp b/cmds/stagefright/codec.cpp
index 33c4663..beeab54 100644
--- a/cmds/stagefright/codec.cpp
+++ b/cmds/stagefright/codec.cpp
@@ -39,7 +39,7 @@
 #include <gui/ISurfaceComposer.h>
 #include <gui/SurfaceComposerClient.h>
 #include <gui/Surface.h>
-#include <ui/DisplayConfig.h>
+#include <ui/DisplayMode.h>
 
 static void usage(const char *me) {
     fprintf(stderr, "usage: %s [-a] use audio\n"
@@ -414,10 +414,10 @@
         const sp<IBinder> display = SurfaceComposerClient::getInternalDisplayToken();
         CHECK(display != nullptr);
 
-        DisplayConfig config;
-        CHECK_EQ(SurfaceComposerClient::getActiveDisplayConfig(display, &config), NO_ERROR);
+        ui::DisplayMode mode;
+        CHECK_EQ(SurfaceComposerClient::getActiveDisplayMode(display, &mode), NO_ERROR);
 
-        const ui::Size& resolution = config.resolution;
+        const ui::Size& resolution = mode.resolution;
         const ssize_t displayWidth = resolution.getWidth();
         const ssize_t displayHeight = resolution.getHeight();
 
diff --git a/cmds/stagefright/mediafilter.cpp b/cmds/stagefright/mediafilter.cpp
index ca058ab..67c68e6 100644
--- a/cmds/stagefright/mediafilter.cpp
+++ b/cmds/stagefright/mediafilter.cpp
@@ -34,7 +34,7 @@
 #include <media/stagefright/NuMediaExtractor.h>
 #include <media/stagefright/RenderScriptWrapper.h>
 #include <OMX_IVCommon.h>
-#include <ui/DisplayConfig.h>
+#include <ui/DisplayMode.h>
 
 #include "RenderScript.h"
 #include "ScriptC_argbtorgba.h"
@@ -752,10 +752,10 @@
         const android::sp<IBinder> display = SurfaceComposerClient::getInternalDisplayToken();
         CHECK(display != nullptr);
 
-        DisplayConfig config;
-        CHECK_EQ(SurfaceComposerClient::getActiveDisplayConfig(display, &config), NO_ERROR);
+        ui::DisplayMode mode;
+        CHECK_EQ(SurfaceComposerClient::getActiveDisplayMode(display, &mode), NO_ERROR);
 
-        const ui::Size& resolution = config.resolution;
+        const ui::Size& resolution = mode.resolution;
         const ssize_t displayWidth = resolution.getWidth();
         const ssize_t displayHeight = resolution.getHeight();
 
diff --git a/cmds/stagefright/stream.cpp b/cmds/stagefright/stream.cpp
index 250d26b..40b2392 100644
--- a/cmds/stagefright/stream.cpp
+++ b/cmds/stagefright/stream.cpp
@@ -42,7 +42,7 @@
 #include <gui/Surface.h>
 
 #include <fcntl.h>
-#include <ui/DisplayConfig.h>
+#include <ui/DisplayMode.h>
 
 using namespace android;
 
@@ -321,10 +321,10 @@
     const sp<IBinder> display = SurfaceComposerClient::getInternalDisplayToken();
     CHECK(display != nullptr);
 
-    DisplayConfig config;
-    CHECK_EQ(SurfaceComposerClient::getActiveDisplayConfig(display, &config), NO_ERROR);
+    ui::DisplayMode mode;
+    CHECK_EQ(SurfaceComposerClient::getActiveDisplayMode(display, &mode), NO_ERROR);
 
-    const ui::Size& resolution = config.resolution;
+    const ui::Size& resolution = mode.resolution;
     const ssize_t displayWidth = resolution.getWidth();
     const ssize_t displayHeight = resolution.getHeight();
 
diff --git a/drm/mediadrm/plugins/clearkey/default/DrmPlugin.cpp b/drm/mediadrm/plugins/clearkey/default/DrmPlugin.cpp
index 1b8b8c1..6ac3510 100644
--- a/drm/mediadrm/plugins/clearkey/default/DrmPlugin.cpp
+++ b/drm/mediadrm/plugins/clearkey/default/DrmPlugin.cpp
@@ -109,6 +109,7 @@
 }
 
 void DrmPlugin::setPlayPolicy() {
+    android::Mutex::Autolock lock(mPlayPolicyLock);
     mPlayPolicy.clear();
     mPlayPolicy.add(kQueryKeyLicenseType, kStreaming);
     mPlayPolicy.add(kQueryKeyPlayAllowed, kTrue);
diff --git a/drm/mediadrm/plugins/clearkey/default/include/DrmPlugin.h b/drm/mediadrm/plugins/clearkey/default/include/DrmPlugin.h
index 4fa42e5..aa9b59d 100644
--- a/drm/mediadrm/plugins/clearkey/default/include/DrmPlugin.h
+++ b/drm/mediadrm/plugins/clearkey/default/include/DrmPlugin.h
@@ -262,6 +262,7 @@
     void initProperties();
     void setPlayPolicy();
 
+    android::Mutex mPlayPolicyLock;
     android::KeyedVector<String8, String8> mPlayPolicy;
     android::KeyedVector<String8, String8> mStringProperties;
     android::KeyedVector<String8, Vector<uint8_t>> mByteArrayProperties;
diff --git a/drm/mediadrm/plugins/clearkey/hidl/DrmPlugin.cpp b/drm/mediadrm/plugins/clearkey/hidl/DrmPlugin.cpp
index f87f830..a77759e 100644
--- a/drm/mediadrm/plugins/clearkey/hidl/DrmPlugin.cpp
+++ b/drm/mediadrm/plugins/clearkey/hidl/DrmPlugin.cpp
@@ -304,6 +304,7 @@
 }
 
 void DrmPlugin::setPlayPolicy() {
+    android::Mutex::Autolock lock(mPlayPolicyLock);
     mPlayPolicy.clear();
 
     KeyValue policy;
diff --git a/drm/mediadrm/plugins/clearkey/hidl/include/DrmPlugin.h b/drm/mediadrm/plugins/clearkey/hidl/include/DrmPlugin.h
index 3de7589..076beb8 100644
--- a/drm/mediadrm/plugins/clearkey/hidl/include/DrmPlugin.h
+++ b/drm/mediadrm/plugins/clearkey/hidl/include/DrmPlugin.h
@@ -406,6 +406,7 @@
     int64_t mCloseSessionOkCount;
     int64_t mCloseSessionNotOpenedCount;
     uint32_t mNextSecureStopId;
+    android::Mutex mPlayPolicyLock;
 
     // set by property to mock error scenarios
     Status_V1_2 mMockError;
diff --git a/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp b/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp
index 82c061a..b1cf388 100644
--- a/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp
+++ b/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp
@@ -30,6 +30,7 @@
 
 namespace android {
 constexpr size_t kMinInputBufferSize = 2 * 1024 * 1024;
+constexpr size_t kMaxDimension = 1920;
 constexpr char COMPONENT_NAME[] = "c2.android.mpeg2.decoder";
 
 class C2SoftMpeg2Dec::IntfImpl : public SimpleInterface<void>::BaseParams {
@@ -64,8 +65,8 @@
                 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
                 .withDefault(new C2StreamPictureSizeInfo::output(0u, 320, 240))
                 .withFields({
-                    C2F(mSize, width).inRange(16, 1920, 4),
-                    C2F(mSize, height).inRange(16, 1088, 4),
+                    C2F(mSize, width).inRange(16, kMaxDimension, 2),
+                    C2F(mSize, height).inRange(16, kMaxDimension, 2),
                 })
                 .withSetter(SizeSetter)
                 .build());
@@ -91,8 +92,8 @@
                 DefineParam(mMaxSize, C2_PARAMKEY_MAX_PICTURE_SIZE)
                 .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 320, 240))
                 .withFields({
-                    C2F(mSize, width).inRange(2, 1920, 2),
-                    C2F(mSize, height).inRange(2, 1088, 2),
+                    C2F(mSize, width).inRange(2, kMaxDimension, 2),
+                    C2F(mSize, height).inRange(2, kMaxDimension, 2),
                 })
                 .withSetter(MaxPictureSizeSetter, mSize)
                 .build());
@@ -204,8 +205,8 @@
                                     const C2P<C2StreamPictureSizeInfo::output> &size) {
         (void)mayBlock;
         // TODO: get max width/height from the size's field helpers vs. hardcoding
-        me.set().width = c2_min(c2_max(me.v.width, size.v.width), 1920u);
-        me.set().height = c2_min(c2_max(me.v.height, size.v.height), 1088u);
+        me.set().width = c2_min(c2_max(me.v.width, size.v.width), kMaxDimension);
+        me.set().height = c2_min(c2_max(me.v.height, size.v.height), kMaxDimension);
         return C2R::Ok();
     }
 
diff --git a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp
index a7cc037..ddd312f 100644
--- a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp
+++ b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp
@@ -35,8 +35,10 @@
 namespace android {
 constexpr size_t kMinInputBufferSize = 2 * 1024 * 1024;
 #ifdef MPEG4
+constexpr size_t kMaxDimension = 1920;
 constexpr char COMPONENT_NAME[] = "c2.android.mpeg4.decoder";
 #else
+constexpr size_t kMaxDimension = 352;
 constexpr char COMPONENT_NAME[] = "c2.android.h263.decoder";
 #endif
 
@@ -75,13 +77,8 @@
                 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
                 .withDefault(new C2StreamPictureSizeInfo::output(0u, 176, 144))
                 .withFields({
-#ifdef MPEG4
-                    C2F(mSize, width).inRange(2, 1920, 2),
-                    C2F(mSize, height).inRange(2, 1088, 2),
-#else
-                    C2F(mSize, width).inRange(2, 352, 2),
-                    C2F(mSize, height).inRange(2, 288, 2),
-#endif
+                    C2F(mSize, width).inRange(2, kMaxDimension, 2),
+                    C2F(mSize, height).inRange(2, kMaxDimension, 2),
                 })
                 .withSetter(SizeSetter)
                 .build());
@@ -130,19 +127,10 @@
 
         addParameter(
                 DefineParam(mMaxSize, C2_PARAMKEY_MAX_PICTURE_SIZE)
-#ifdef MPEG4
-                .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 1920, 1088))
-#else
                 .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 352, 288))
-#endif
                 .withFields({
-#ifdef MPEG4
-                    C2F(mSize, width).inRange(2, 1920, 2),
-                    C2F(mSize, height).inRange(2, 1088, 2),
-#else
-                    C2F(mSize, width).inRange(2, 352, 2),
-                    C2F(mSize, height).inRange(2, 288, 2),
-#endif
+                    C2F(mSize, width).inRange(2, kMaxDimension, 2),
+                    C2F(mSize, height).inRange(2, kMaxDimension, 2),
                 })
                 .withSetter(MaxPictureSizeSetter, mSize)
                 .build());
@@ -200,13 +188,8 @@
                                     const C2P<C2StreamPictureSizeInfo::output> &size) {
         (void)mayBlock;
         // TODO: get max width/height from the size's field helpers vs. hardcoding
-#ifdef MPEG4
-        me.set().width = c2_min(c2_max(me.v.width, size.v.width), 1920u);
-        me.set().height = c2_min(c2_max(me.v.height, size.v.height), 1088u);
-#else
-        me.set().width = c2_min(c2_max(me.v.width, size.v.width), 352u);
-        me.set().height = c2_min(c2_max(me.v.height, size.v.height), 288u);
-#endif
+        me.set().width = c2_min(c2_max(me.v.width, size.v.width), kMaxDimension);
+        me.set().height = c2_min(c2_max(me.v.height, size.v.height), kMaxDimension);
         return C2R::Ok();
     }
 
diff --git a/media/codec2/sfplugin/Android.bp b/media/codec2/sfplugin/Android.bp
index 94034b5..c3cfcce 100644
--- a/media/codec2/sfplugin/Android.bp
+++ b/media/codec2/sfplugin/Android.bp
@@ -11,6 +11,7 @@
         "CCodecConfig.cpp",
         "Codec2Buffer.cpp",
         "Codec2InfoBuilder.cpp",
+        "FrameReassembler.cpp",
         "PipelineWatcher.cpp",
         "ReflectedParamUpdater.cpp",
     ],
diff --git a/media/codec2/sfplugin/CCodecBufferChannel.cpp b/media/codec2/sfplugin/CCodecBufferChannel.cpp
index 813d85b..44ebf84 100644
--- a/media/codec2/sfplugin/CCodecBufferChannel.cpp
+++ b/media/codec2/sfplugin/CCodecBufferChannel.cpp
@@ -30,6 +30,7 @@
 
 #include <android/hardware/cas/native/1.0/IDescrambler.h>
 #include <android/hardware/drm/1.0/types.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <binder/MemoryBase.h>
 #include <binder/MemoryDealer.h>
@@ -217,6 +218,7 @@
         flags |= C2FrameData::FLAG_CODEC_CONFIG;
     }
     ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
+    std::list<std::unique_ptr<C2Work>> items;
     std::unique_ptr<C2Work> work(new C2Work);
     work->input.ordinal.timestamp = timeUs;
     work->input.ordinal.frameIndex = mFrameIndex++;
@@ -226,9 +228,8 @@
     work->input.ordinal.customOrdinal = timeUs;
     work->input.buffers.clear();
 
-    uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
-    std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
     sp<Codec2Buffer> copy;
+    bool usesFrameReassembler = false;
 
     if (buffer->size() > 0u) {
         Mutexed<Input>::Locked input(mInput);
@@ -253,43 +254,48 @@
                       "buffer starvation on component.", mName);
             }
         }
-        int32_t cvo = 0;
-        if (buffer->meta()->findInt32("cvo", &cvo)) {
-            int32_t rotation = cvo % 360;
-            // change rotation to counter-clock wise.
-            rotation = ((rotation <= 0) ? 0 : 360) - rotation;
-            Mutexed<OutputSurface>::Locked output(mOutputSurface);
-            output->rotation[queuedFrameIndex] = rotation;
+        if (input->frameReassembler) {
+            usesFrameReassembler = true;
+            input->frameReassembler.process(buffer, &items);
+        } else {
+            int32_t cvo = 0;
+            if (buffer->meta()->findInt32("cvo", &cvo)) {
+                int32_t rotation = cvo % 360;
+                // change rotation to counter-clock wise.
+                rotation = ((rotation <= 0) ? 0 : 360) - rotation;
+
+                Mutexed<OutputSurface>::Locked output(mOutputSurface);
+                uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
+                output->rotation[frameIndex] = rotation;
+            }
+            work->input.buffers.push_back(c2buffer);
+            if (encryptedBlock) {
+                work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
+                        kParamIndexEncryptedBuffer,
+                        encryptedBlock->share(0, blockSize, C2Fence())));
+            }
         }
-        work->input.buffers.push_back(c2buffer);
-        if (encryptedBlock) {
-            work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
-                    kParamIndexEncryptedBuffer,
-                    encryptedBlock->share(0, blockSize, C2Fence())));
-        }
-        queuedBuffers.push_back(c2buffer);
     } else if (eos) {
         flags |= C2FrameData::FLAG_END_OF_STREAM;
     }
-    work->input.flags = (C2FrameData::flags_t)flags;
-    // TODO: fill info's
+    if (usesFrameReassembler) {
+        if (!items.empty()) {
+            items.front()->input.configUpdate = std::move(mParamsToBeSet);
+            mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
+        }
+    } else {
+        work->input.flags = (C2FrameData::flags_t)flags;
+        // TODO: fill info's
 
-    work->input.configUpdate = std::move(mParamsToBeSet);
-    work->worklets.clear();
-    work->worklets.emplace_back(new C2Worklet);
+        work->input.configUpdate = std::move(mParamsToBeSet);
+        work->worklets.clear();
+        work->worklets.emplace_back(new C2Worklet);
 
-    std::list<std::unique_ptr<C2Work>> items;
-    items.push_back(std::move(work));
-    mPipelineWatcher.lock()->onWorkQueued(
-            queuedFrameIndex,
-            std::move(queuedBuffers),
-            PipelineWatcher::Clock::now());
-    c2_status_t err = mComponent->queue(&items);
-    if (err != C2_OK) {
-        mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
+        items.push_back(std::move(work));
+
+        eos = eos && buffer->size() > 0u;
     }
-
-    if (err == C2_OK && eos && buffer->size() > 0u) {
+    if (eos) {
         work.reset(new C2Work);
         work->input.ordinal.timestamp = timeUs;
         work->input.ordinal.frameIndex = mFrameIndex++;
@@ -298,23 +304,28 @@
         work->input.buffers.clear();
         work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
         work->worklets.emplace_back(new C2Worklet);
-
-        queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
-        queuedBuffers.clear();
-
-        items.clear();
         items.push_back(std::move(work));
-
-        mPipelineWatcher.lock()->onWorkQueued(
-                queuedFrameIndex,
-                std::move(queuedBuffers),
-                PipelineWatcher::Clock::now());
-        err = mComponent->queue(&items);
-        if (err != C2_OK) {
-            mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
-        }
     }
-    if (err == C2_OK) {
+    c2_status_t err = C2_OK;
+    if (!items.empty()) {
+        {
+            Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
+            PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
+            for (const std::unique_ptr<C2Work> &work : items) {
+                watcher->onWorkQueued(
+                        work->input.ordinal.frameIndex.peeku(),
+                        std::vector(work->input.buffers),
+                        now);
+            }
+        }
+        err = mComponent->queue(&items);
+    }
+    if (err != C2_OK) {
+        Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
+        for (const std::unique_ptr<C2Work> &work : items) {
+            watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
+        }
+    } else {
         Mutexed<Input>::Locked input(mInput);
         bool released = false;
         if (buffer) {
@@ -885,7 +896,12 @@
         }
         return result;
     }
-    ALOGV("[%s] queue buffer successful", mName);
+
+    if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
+        ALOGD("[%s] queue buffer successful", mName);
+    } else {
+        ALOGV("[%s] queue buffer successful", mName);
+    }
 
     int64_t mediaTimeUs = 0;
     (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
@@ -946,6 +962,7 @@
         bool buffersBoundToCodec) {
     C2StreamBufferTypeSetting::input iStreamFormat(0u);
     C2StreamBufferTypeSetting::output oStreamFormat(0u);
+    C2ComponentKindSetting kind;
     C2PortReorderBufferDepthTuning::output reorderDepth;
     C2PortReorderKeySetting::output reorderKey;
     C2PortActualDelayTuning::input inputDelay(0);
@@ -957,6 +974,7 @@
             {
                 &iStreamFormat,
                 &oStreamFormat,
+                &kind,
                 &reorderDepth,
                 &reorderKey,
                 &inputDelay,
@@ -968,7 +986,7 @@
             C2_DONT_BLOCK,
             nullptr);
     if (err == C2_BAD_INDEX) {
-        if (!iStreamFormat || !oStreamFormat) {
+        if (!iStreamFormat || !oStreamFormat || !kind) {
             return UNKNOWN_ERROR;
         }
     } else if (err != C2_OK) {
@@ -994,12 +1012,17 @@
 
     if (inputFormat != nullptr) {
         bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
+        bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
         C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
                 API_REFLECTION |
                 API_VALUES |
                 API_CURRENT_VALUES |
                 API_DEPENDENCY |
                 API_SAME_INPUT_BUFFER);
+        C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
+        C2StreamSampleRateInfo::input sampleRate(0u);
+        C2StreamChannelCountInfo::input channelCount(0u);
+        C2StreamPcmEncodingInfo::input pcmEncoding(0u);
         std::shared_ptr<C2BlockPool> pool;
         {
             Mutexed<BlockPools>::Locked pools(mBlockPools);
@@ -1012,7 +1035,19 @@
             // from component, create the input block pool with given ID. Otherwise, use default IDs.
             std::vector<std::unique_ptr<C2Param>> params;
             C2ApiFeaturesSetting featuresSetting{apiFeatures};
-            err = mComponent->query({ &featuresSetting },
+            std::vector<C2Param *> stackParams({&featuresSetting});
+            if (audioEncoder) {
+                stackParams.push_back(&encoderFrameSize);
+                stackParams.push_back(&sampleRate);
+                stackParams.push_back(&channelCount);
+                stackParams.push_back(&pcmEncoding);
+            } else {
+                encoderFrameSize.invalidate();
+                sampleRate.invalidate();
+                channelCount.invalidate();
+                pcmEncoding.invalidate();
+            }
+            err = mComponent->query(stackParams,
                                     { C2PortAllocatorsTuning::input::PARAM_TYPE },
                                     C2_DONT_BLOCK,
                                     &params);
@@ -1070,10 +1105,21 @@
         input->numSlots = numInputSlots;
         input->extraBuffers.flush();
         input->numExtraSlots = 0u;
+        if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
+            input->frameReassembler.init(
+                    pool,
+                    {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
+                    encoderFrameSize.value,
+                    sampleRate.value,
+                    channelCount.value,
+                    pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
+        }
         bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
         // For encrypted content, framework decrypts source buffer (ashmem) into
         // C2Buffers. Thus non-conforming codecs can process these.
-        if (!buffersBoundToCodec && (hasCryptoOrDescrambler() || conforming)) {
+        if (!buffersBoundToCodec
+                && !input->frameReassembler
+                && (hasCryptoOrDescrambler() || conforming)) {
             input->buffers.reset(new SlotInputBuffers(mName));
         } else if (graphic) {
             if (mInputSurface) {
diff --git a/media/codec2/sfplugin/CCodecBufferChannel.h b/media/codec2/sfplugin/CCodecBufferChannel.h
index 4dc418a..45da003 100644
--- a/media/codec2/sfplugin/CCodecBufferChannel.h
+++ b/media/codec2/sfplugin/CCodecBufferChannel.h
@@ -31,6 +31,7 @@
 #include <media/stagefright/CodecBase.h>
 
 #include "CCodecBuffers.h"
+#include "FrameReassembler.h"
 #include "InputSurfaceWrapper.h"
 #include "PipelineWatcher.h"
 
@@ -271,6 +272,8 @@
         size_t numExtraSlots;
         uint32_t inputDelay;
         uint32_t pipelineDelay;
+
+        FrameReassembler frameReassembler;
     };
     Mutexed<Input> mInput;
     struct Output {
diff --git a/media/codec2/sfplugin/FrameReassembler.cpp b/media/codec2/sfplugin/FrameReassembler.cpp
new file mode 100644
index 0000000..9cec23f
--- /dev/null
+++ b/media/codec2/sfplugin/FrameReassembler.cpp
@@ -0,0 +1,226 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "FrameReassembler"
+
+#include <log/log.h>
+
+#include <media/stagefright/foundation/AMessage.h>
+
+#include "FrameReassembler.h"
+
+namespace android {
+
+static constexpr uint64_t kToleranceUs = 1000;  // 1ms
+
+FrameReassembler::FrameReassembler()
+    : mUsage{0, 0},
+      mSampleRate(0u),
+      mChannelCount(0u),
+      mEncoding(C2Config::PCM_16),
+      mCurrentOrdinal({0, 0, 0}) {
+}
+
+void FrameReassembler::init(
+        const std::shared_ptr<C2BlockPool> &pool,
+        C2MemoryUsage usage,
+        uint32_t frameSize,
+        uint32_t sampleRate,
+        uint32_t channelCount,
+        C2Config::pcm_encoding_t encoding) {
+    mBlockPool = pool;
+    mUsage = usage;
+    mFrameSize = frameSize;
+    mSampleRate = sampleRate;
+    mChannelCount = channelCount;
+    mEncoding = encoding;
+}
+
+void FrameReassembler::updateFrameSize(uint32_t frameSize) {
+    finishCurrentBlock(&mPendingWork);
+    mFrameSize = frameSize;
+}
+
+void FrameReassembler::updateSampleRate(uint32_t sampleRate) {
+    finishCurrentBlock(&mPendingWork);
+    mSampleRate = sampleRate;
+}
+
+void FrameReassembler::updateChannelCount(uint32_t channelCount) {
+    finishCurrentBlock(&mPendingWork);
+    mChannelCount = channelCount;
+}
+
+void FrameReassembler::updatePcmEncoding(C2Config::pcm_encoding_t encoding) {
+    finishCurrentBlock(&mPendingWork);
+    mEncoding = encoding;
+}
+
+void FrameReassembler::reset() {
+    flush();
+    mCurrentOrdinal = {0, 0, 0};
+    mBlockPool.reset();
+    mFrameSize.reset();
+    mSampleRate = 0u;
+    mChannelCount = 0u;
+    mEncoding = C2Config::PCM_16;
+}
+
+FrameReassembler::operator bool() const {
+    return mFrameSize.has_value();
+}
+
+c2_status_t FrameReassembler::process(
+        const sp<MediaCodecBuffer> &buffer,
+        std::list<std::unique_ptr<C2Work>> *items) {
+    int64_t timeUs;
+    if (buffer->size() == 0u
+            || !buffer->meta()->findInt64("timeUs", &timeUs)) {
+        return C2_BAD_VALUE;
+    }
+
+    items->splice(items->end(), mPendingWork);
+
+    // Fill mCurrentBlock
+    if (mCurrentBlock) {
+        // First check the timestamp
+        c2_cntr64_t endTimestampUs = mCurrentOrdinal.timestamp;
+        endTimestampUs += bytesToSamples(mWriteView->size()) * 1000000 / mSampleRate;
+        if (timeUs < endTimestampUs.peek()) {
+            uint64_t diffUs = (endTimestampUs - timeUs).peeku();
+            if (diffUs > kToleranceUs) {
+                // The timestamp is going back in time in large amount.
+                // TODO: b/145702136
+                ALOGW("timestamp going back in time! from %lld to %lld",
+                        endTimestampUs.peekll(), (long long)timeUs);
+            }
+        } else {  // timeUs >= endTimestampUs.peek()
+            uint64_t diffUs = (timeUs - endTimestampUs).peeku();
+            if (diffUs > kToleranceUs) {
+                // The timestamp is going forward; add silence as necessary.
+                size_t gapSamples = usToSamples(diffUs);
+                size_t remainingSamples =
+                    (mWriteView->capacity() - mWriteView->size())
+                    / mChannelCount / bytesPerSample();
+                if (gapSamples < remainingSamples) {
+                    size_t gapBytes = gapSamples * mChannelCount * bytesPerSample();
+                    memset(mWriteView->base() + mWriteView->size(), 0u, gapBytes);
+                    mWriteView->setSize(mWriteView->size() + gapBytes);
+                } else {
+                    finishCurrentBlock(items);
+                }
+            }
+        }
+    }
+
+    if (mCurrentBlock) {
+        // Append the data at the end of the current block
+        size_t copySize = std::min(
+                buffer->size(),
+                size_t(mWriteView->capacity() - mWriteView->size()));
+        memcpy(mWriteView->base() + mWriteView->size(), buffer->data(), copySize);
+        buffer->setRange(buffer->offset() + copySize, buffer->size() - copySize);
+        mWriteView->setSize(mWriteView->size() + copySize);
+        if (mWriteView->size() == mWriteView->capacity()) {
+            finishCurrentBlock(items);
+        }
+        timeUs += bytesToSamples(copySize) * 1000000 / mSampleRate;
+    }
+
+    if (buffer->size() > 0) {
+        mCurrentOrdinal.timestamp = timeUs;
+    }
+
+    size_t frameSizeBytes = mFrameSize.value() * mChannelCount * bytesPerSample();
+    while (buffer->size() > 0) {
+        LOG_ALWAYS_FATAL_IF(
+                mCurrentBlock,
+                "There's remaining data but the pending block is not filled & finished");
+        std::unique_ptr<C2Work> work(new C2Work);
+        c2_status_t err = mBlockPool->fetchLinearBlock(frameSizeBytes, mUsage, &mCurrentBlock);
+        if (err != C2_OK) {
+            return err;
+        }
+        size_t copySize = std::min(buffer->size(), frameSizeBytes);
+        mWriteView = mCurrentBlock->map().get();
+        if (mWriteView->error() != C2_OK) {
+            return mWriteView->error();
+        }
+        ALOGV("buffer={offset=%zu size=%zu} copySize=%zu",
+                buffer->offset(), buffer->size(), copySize);
+        memcpy(mWriteView->base(), buffer->data(), copySize);
+        mWriteView->setOffset(0u);
+        mWriteView->setSize(copySize);
+        buffer->setRange(buffer->offset() + copySize, buffer->size() - copySize);
+        if (copySize == frameSizeBytes) {
+            finishCurrentBlock(items);
+        }
+    }
+
+    int32_t eos = 0;
+    if (buffer->meta()->findInt32("eos", &eos) && eos) {
+        finishCurrentBlock(items);
+    }
+
+    return C2_OK;
+}
+
+void FrameReassembler::flush() {
+    mPendingWork.clear();
+    mWriteView.reset();
+    mCurrentBlock.reset();
+}
+
+uint64_t FrameReassembler::bytesToSamples(size_t numBytes) const {
+    return numBytes / mChannelCount / bytesPerSample();
+}
+
+size_t FrameReassembler::usToSamples(uint64_t us) const {
+    return (us * mChannelCount * mSampleRate / 1000000);
+}
+
+uint32_t FrameReassembler::bytesPerSample() const {
+    return (mEncoding == C2Config::PCM_8) ? 1
+         : (mEncoding == C2Config::PCM_16) ? 2
+         : (mEncoding == C2Config::PCM_FLOAT) ? 4 : 0;
+}
+
+void FrameReassembler::finishCurrentBlock(std::list<std::unique_ptr<C2Work>> *items) {
+    if (!mCurrentBlock) {
+        // No-op
+        return;
+    }
+    if (mWriteView->size() < mWriteView->capacity()) {
+        memset(mWriteView->base() + mWriteView->size(), 0u,
+                mWriteView->capacity() - mWriteView->size());
+        mWriteView->setSize(mWriteView->capacity());
+    }
+    std::unique_ptr<C2Work> work{std::make_unique<C2Work>()};
+    work->input.ordinal = mCurrentOrdinal;
+    work->input.buffers.push_back(C2Buffer::CreateLinearBuffer(
+            mCurrentBlock->share(0, mCurrentBlock->capacity(), C2Fence())));
+    work->worklets.clear();
+    work->worklets.emplace_back(new C2Worklet);
+    items->push_back(std::move(work));
+
+    ++mCurrentOrdinal.frameIndex;
+    mCurrentOrdinal.timestamp += mFrameSize.value() * 1000000 / mSampleRate;
+    mCurrentBlock.reset();
+    mWriteView.reset();
+}
+
+}  // namespace android
diff --git a/media/codec2/sfplugin/FrameReassembler.h b/media/codec2/sfplugin/FrameReassembler.h
new file mode 100644
index 0000000..17ac06d
--- /dev/null
+++ b/media/codec2/sfplugin/FrameReassembler.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef FRAME_REASSEMBLER_H_
+#define FRAME_REASSEMBLER_H_
+
+#include <set>
+#include <memory>
+
+#include <media/MediaCodecBuffer.h>
+
+#include <C2Config.h>
+#include <C2Work.h>
+
+namespace android {
+
+class FrameReassembler {
+public:
+    FrameReassembler();
+
+    void init(
+            const std::shared_ptr<C2BlockPool> &pool,
+            C2MemoryUsage usage,
+            uint32_t frameSize,
+            uint32_t sampleRate,
+            uint32_t channelCount,
+            C2Config::pcm_encoding_t encoding);
+    void updateFrameSize(uint32_t frameSize);
+    void updateSampleRate(uint32_t sampleRate);
+    void updateChannelCount(uint32_t channelCount);
+    void updatePcmEncoding(C2Config::pcm_encoding_t encoding);
+    void reset();
+    void flush();
+
+    explicit operator bool() const;
+
+    c2_status_t process(
+            const sp<MediaCodecBuffer> &buffer,
+            std::list<std::unique_ptr<C2Work>> *items);
+
+private:
+    std::shared_ptr<C2BlockPool> mBlockPool;
+    C2MemoryUsage mUsage;
+    std::optional<uint32_t> mFrameSize;
+    uint32_t mSampleRate;
+    uint32_t mChannelCount;
+    C2Config::pcm_encoding_t mEncoding;
+    std::list<std::unique_ptr<C2Work>> mPendingWork;
+    C2WorkOrdinalStruct mCurrentOrdinal;
+    std::shared_ptr<C2LinearBlock> mCurrentBlock;
+    std::optional<C2WriteView> mWriteView;
+
+    uint64_t bytesToSamples(size_t numBytes) const;
+    size_t usToSamples(uint64_t us) const;
+    uint32_t bytesPerSample() const;
+
+    void finishCurrentBlock(std::list<std::unique_ptr<C2Work>> *items);
+};
+
+}  // namespace android
+
+#endif  // FRAME_REASSEMBLER_H_
diff --git a/media/codec2/sfplugin/tests/Android.bp b/media/codec2/sfplugin/tests/Android.bp
index 5c774a2..d705cfd 100644
--- a/media/codec2/sfplugin/tests/Android.bp
+++ b/media/codec2/sfplugin/tests/Android.bp
@@ -5,6 +5,7 @@
     srcs: [
         "CCodecBuffers_test.cpp",
         "CCodecConfig_test.cpp",
+        "FrameReassembler_test.cpp",
         "ReflectedParamUpdater_test.cpp",
     ],
 
diff --git a/media/codec2/sfplugin/tests/FrameReassembler_test.cpp b/media/codec2/sfplugin/tests/FrameReassembler_test.cpp
new file mode 100644
index 0000000..6738ee7
--- /dev/null
+++ b/media/codec2/sfplugin/tests/FrameReassembler_test.cpp
@@ -0,0 +1,340 @@
+/*
+ * Copyright 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "FrameReassembler.h"
+
+#include <gtest/gtest.h>
+
+#include <C2PlatformSupport.h>
+
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/AMessage.h>
+
+namespace android {
+
+static size_t BytesPerSample(C2Config::pcm_encoding_t encoding) {
+    return encoding == PCM_8 ? 1
+         : encoding == PCM_16 ? 2
+         : encoding == PCM_FLOAT ? 4 : 0;
+}
+
+static uint64_t Diff(c2_cntr64_t a, c2_cntr64_t b) {
+    return std::abs((a - b).peek());
+}
+
+class FrameReassemblerTest : public ::testing::Test {
+public:
+    static const C2MemoryUsage kUsage;
+    static constexpr uint64_t kTimestampToleranceUs = 100;
+
+    FrameReassemblerTest() {
+        mInitStatus = GetCodec2BlockPool(C2BlockPool::BASIC_LINEAR, nullptr, &mPool);
+    }
+
+    status_t initStatus() const { return mInitStatus; }
+
+    void testPushSameSize(
+            size_t encoderFrameSize,
+            size_t sampleRate,
+            size_t channelCount,
+            C2Config::pcm_encoding_t encoding,
+            size_t inputFrameSizeInBytes,
+            size_t count,
+            size_t expectedOutputSize) {
+        FrameReassembler frameReassembler;
+        frameReassembler.init(
+                mPool,
+                kUsage,
+                encoderFrameSize,
+                sampleRate,
+                channelCount,
+                encoding);
+
+        ASSERT_TRUE(frameReassembler) << "FrameReassembler init failed";
+
+        size_t inputIndex = 0, outputIndex = 0;
+        size_t expectCount = 0;
+        for (size_t i = 0; i < count; ++i) {
+            sp<MediaCodecBuffer> buffer = new MediaCodecBuffer(
+                    new AMessage, new ABuffer(inputFrameSizeInBytes));
+            buffer->setRange(0, inputFrameSizeInBytes);
+            buffer->meta()->setInt64(
+                    "timeUs",
+                    inputIndex * 1000000 / sampleRate / channelCount / BytesPerSample(encoding));
+            if (i == count - 1) {
+                buffer->meta()->setInt32("eos", 1);
+            }
+            for (size_t j = 0; j < inputFrameSizeInBytes; ++j, ++inputIndex) {
+                buffer->base()[j] = (inputIndex & 0xFF);
+            }
+            std::list<std::unique_ptr<C2Work>> items;
+            ASSERT_EQ(C2_OK, frameReassembler.process(buffer, &items));
+            while (!items.empty()) {
+                std::unique_ptr<C2Work> work = std::move(*items.begin());
+                items.erase(items.begin());
+                // Verify timestamp
+                uint64_t expectedTimeUs =
+                    outputIndex * 1000000 / sampleRate / channelCount / BytesPerSample(encoding);
+                EXPECT_GE(
+                        kTimestampToleranceUs,
+                        Diff(expectedTimeUs, work->input.ordinal.timestamp))
+                    << "expected timestamp: " << expectedTimeUs
+                    << " actual timestamp: " << work->input.ordinal.timestamp.peeku()
+                    << " output index: " << outputIndex;
+
+                // Verify buffer
+                ASSERT_EQ(1u, work->input.buffers.size());
+                std::shared_ptr<C2Buffer> buffer = work->input.buffers.front();
+                ASSERT_EQ(C2BufferData::LINEAR, buffer->data().type());
+                ASSERT_EQ(1u, buffer->data().linearBlocks().size());
+                C2ReadView view = buffer->data().linearBlocks().front().map().get();
+                ASSERT_EQ(C2_OK, view.error());
+                ASSERT_EQ(encoderFrameSize * BytesPerSample(encoding), view.capacity());
+                for (size_t j = 0; j < view.capacity(); ++j, ++outputIndex) {
+                    ASSERT_TRUE(outputIndex < inputIndex
+                             || inputIndex == inputFrameSizeInBytes * count);
+                    uint8_t expected = outputIndex < inputIndex ? (outputIndex & 0xFF) : 0;
+                    if (expectCount < 10) {
+                        ++expectCount;
+                        EXPECT_EQ(expected, view.data()[j]) << "output index = " << outputIndex;
+                    }
+                }
+            }
+        }
+
+        ASSERT_EQ(inputFrameSizeInBytes * count, inputIndex);
+        size_t encoderFrameSizeInBytes =
+            encoderFrameSize * channelCount * BytesPerSample(encoding);
+        ASSERT_EQ(0, outputIndex % encoderFrameSizeInBytes)
+            << "output size must be multiple of frame size: output size = " << outputIndex
+            << " frame size = " << encoderFrameSizeInBytes;
+        ASSERT_EQ(expectedOutputSize, outputIndex)
+            << "output size must be smallest multiple of frame size, "
+            << "equal to or larger than input size. output size = " << outputIndex
+            << " input size = " << inputIndex << " frame size = " << encoderFrameSizeInBytes;
+    }
+
+private:
+    status_t mInitStatus;
+    std::shared_ptr<C2BlockPool> mPool;
+};
+
+const C2MemoryUsage FrameReassemblerTest::kUsage{C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
+
+// Push frames with exactly the same size as the encoder requested.
+TEST_F(FrameReassemblerTest, PushExactFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            1024 /* input frame size in bytes = 1024 samples * 1 channel * 1 bytes/sample */,
+            10 /* count */,
+            10240 /* expected output size = 10 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            2048 /* input frame size in bytes = 1024 samples * 1 channel * 2 bytes/sample */,
+            10 /* count */,
+            20480 /* expected output size = 10 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            4096 /* input frame size in bytes = 1024 samples * 1 channel * 4 bytes/sample */,
+            10 /* count */,
+            40960 /* expected output size = 10 * 4096 bytes/frame */);
+}
+
+// Push frames with half the size that the encoder requested.
+TEST_F(FrameReassemblerTest, PushHalfFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            512 /* input frame size in bytes = 512 samples * 1 channel * 1 bytes per sample */,
+            10 /* count */,
+            5120 /* expected output size = 5 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            1024 /* input frame size in bytes = 512 samples * 1 channel * 2 bytes per sample */,
+            10 /* count */,
+            10240 /* expected output size = 5 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            2048 /* input frame size in bytes = 512 samples * 1 channel * 4 bytes per sample */,
+            10 /* count */,
+            20480 /* expected output size = 5 * 4096 bytes/frame */);
+}
+
+// Push frames with twice the size that the encoder requested.
+TEST_F(FrameReassemblerTest, PushDoubleFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            2048 /* input frame size in bytes = 2048 samples * 1 channel * 1 bytes per sample */,
+            10 /* count */,
+            20480 /* expected output size = 20 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            4096 /* input frame size in bytes = 2048 samples * 1 channel * 2 bytes per sample */,
+            10 /* count */,
+            40960 /* expected output size = 20 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            8192 /* input frame size in bytes = 2048 samples * 1 channel * 4 bytes per sample */,
+            10 /* count */,
+            81920 /* expected output size = 20 * 4096 bytes/frame */);
+}
+
+// Push frames with a little bit larger (+5 samples) than the requested size.
+TEST_F(FrameReassemblerTest, PushLittleLargerFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            1029 /* input frame size in bytes = 1029 samples * 1 channel * 1 bytes per sample */,
+            10 /* count */,
+            11264 /* expected output size = 11 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            2058 /* input frame size in bytes = 1029 samples * 1 channel * 2 bytes per sample */,
+            10 /* count */,
+            22528 /* expected output size = 11 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            4116 /* input frame size in bytes = 1029 samples * 1 channel * 4 bytes per sample */,
+            10 /* count */,
+            45056 /* expected output size = 11 * 4096 bytes/frame */);
+}
+
+// Push frames with a little bit smaller (-5 samples) than the requested size.
+TEST_F(FrameReassemblerTest, PushLittleSmallerFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            1019 /* input frame size in bytes = 1019 samples * 1 channel * 1 bytes per sample */,
+            10 /* count */,
+            10240 /* expected output size = 10 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            2038 /* input frame size in bytes = 1019 samples * 1 channel * 2 bytes per sample */,
+            10 /* count */,
+            20480 /* expected output size = 10 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            4076 /* input frame size in bytes = 1019 samples * 1 channel * 4 bytes per sample */,
+            10 /* count */,
+            40960 /* expected output size = 10 * 4096 bytes/frame */);
+}
+
+// Push single-byte frames
+TEST_F(FrameReassemblerTest, PushSingleByte) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            1 /* input frame size in bytes */,
+            100000 /* count */,
+            100352 /* expected output size = 98 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            1 /* input frame size in bytes */,
+            100000 /* count */,
+            100352 /* expected output size = 49 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            1 /* input frame size in bytes */,
+            100000 /* count */,
+            102400 /* expected output size = 25 * 4096 bytes/frame */);
+}
+
+// Push one big chunk.
+TEST_F(FrameReassemblerTest, PushBigChunk) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            100000 /* input frame size in bytes */,
+            1 /* count */,
+            100352 /* expected output size = 98 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            100000 /* input frame size in bytes */,
+            1 /* count */,
+            100352 /* expected output size = 49 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            100000 /* input frame size in bytes */,
+            1 /* count */,
+            102400 /* expected output size = 25 * 4096 bytes/frame */);
+}
+
+} // namespace android
diff --git a/media/libaaudio/include/aaudio/AAudio.h b/media/libaaudio/include/aaudio/AAudio.h
index ea4fe04..9072886 100644
--- a/media/libaaudio/include/aaudio/AAudio.h
+++ b/media/libaaudio/include/aaudio/AAudio.h
@@ -1049,7 +1049,6 @@
 // Stream Control
 // ============================================================
 
-#if __ANDROID_API__ >= 30
 /**
  * Free the audio resources associated with a stream created by
  * AAudioStreamBuilder_openStream().
@@ -1067,11 +1066,12 @@
  * On other "Legacy" streams some audio resources will still be in use
  * and some callbacks may still be in process after this call.
  *
+ * Available since API level 30.
+ *
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return {@link #AAUDIO_OK} or a negative error.
  */
 AAUDIO_API aaudio_result_t  AAudioStream_release(AAudioStream* stream) __INTRODUCED_IN(30);
-#endif // __ANDROID_API__
 
 /**
  * Delete the internal data structures associated with the stream created
@@ -1079,6 +1079,8 @@
  *
  * If AAudioStream_release() has not been called then it will be called automatically.
  *
+ * Available since API level 26.
+ *
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return {@link #AAUDIO_OK} or a negative error.
  */
diff --git a/media/libaaudio/src/core/AudioStream.cpp b/media/libaaudio/src/core/AudioStream.cpp
index a4beaf4..5078d2c 100644
--- a/media/libaaudio/src/core/AudioStream.cpp
+++ b/media/libaaudio/src/core/AudioStream.cpp
@@ -591,7 +591,8 @@
     std::lock_guard<std::mutex> lock(mParentLock);
     mParent = parent;
     if (!mRegistered) {
-        init(android::PLAYER_TYPE_AAUDIO, AAudioConvert_usageToInternal(parent->getUsage()));
+        init(android::PLAYER_TYPE_AAUDIO, AAudioConvert_usageToInternal(parent->getUsage()),
+            (audio_session_t)parent->getSessionId());
         mRegistered = true;
     }
 }
diff --git a/media/libaaudio/tests/Android.bp b/media/libaaudio/tests/Android.bp
index 95d6543..85376ad 100644
--- a/media/libaaudio/tests/Android.bp
+++ b/media/libaaudio/tests/Android.bp
@@ -16,7 +16,7 @@
         "libbinder",
         "libcutils",
         "libutils",
-        "shared-file-region-aidl-unstable-cpp",
+        "shared-file-region-aidl-cpp",
     ],
 }
 
diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp
index 004ae39..8a575d5 100644
--- a/media/libaudioclient/Android.bp
+++ b/media/libaudioclient/Android.bp
@@ -14,14 +14,14 @@
         "libaudiofoundation_headers",
     ],
     static_libs: [
-        "audioflinger-aidl-unstable-cpp",
-        "audiopolicy-aidl-unstable-cpp",
-        "av-types-aidl-unstable-cpp",
+        "audioflinger-aidl-cpp",
+        "audiopolicy-aidl-cpp",
+        "av-types-aidl-cpp",
     ],
     export_static_lib_headers: [
-        "audioflinger-aidl-unstable-cpp",
-        "audiopolicy-aidl-unstable-cpp",
-        "av-types-aidl-unstable-cpp",
+        "audioflinger-aidl-cpp",
+        "audiopolicy-aidl-cpp",
+        "av-types-aidl-cpp",
     ],
     target: {
         darwin: {
@@ -40,11 +40,11 @@
         "PolicyAidlConversion.cpp"
     ],
     shared_libs: [
-        "audioclient-types-aidl-unstable-cpp",
-        "audioflinger-aidl-unstable-cpp",
-        "audiopolicy-aidl-unstable-cpp",
-        "audiopolicy-types-aidl-unstable-cpp",
-        "capture_state_listener-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
+        "audioflinger-aidl-cpp",
+        "audiopolicy-aidl-cpp",
+        "audiopolicy-types-aidl-cpp",
+        "capture_state_listener-aidl-cpp",
         "libaudiofoundation",
         "libaudioclient_aidl_conversion",
         "libaudioutils",
@@ -60,11 +60,11 @@
     include_dirs: ["system/media/audio_utils/include"],
     export_include_dirs: ["include"],
     export_shared_lib_headers: [
-        "audioclient-types-aidl-unstable-cpp",
-        "audioflinger-aidl-unstable-cpp",
-        "audiopolicy-aidl-unstable-cpp",
-        "audiopolicy-types-aidl-unstable-cpp",
-        "capture_state_listener-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
+        "audioflinger-aidl-cpp",
+        "audiopolicy-aidl-cpp",
+        "audiopolicy-types-aidl-cpp",
+        "capture_state_listener-aidl-cpp",
         "libaudiofoundation",
         "libaudioclient_aidl_conversion",
     ],
@@ -100,12 +100,12 @@
         "TrackPlayerBase.cpp",
     ],
     shared_libs: [
-        "audioclient-types-aidl-unstable-cpp",
-        "audioflinger-aidl-unstable-cpp",
-        "audiopolicy-aidl-unstable-cpp",
-        "audiopolicy-types-aidl-unstable-cpp",
-        "av-types-aidl-unstable-cpp",
-        "capture_state_listener-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
+        "audioflinger-aidl-cpp",
+        "audiopolicy-aidl-cpp",
+        "audiopolicy-types-aidl-cpp",
+        "av-types-aidl-cpp",
+        "capture_state_listener-aidl-cpp",
         "libaudioclient_aidl_conversion",
         "libaudiofoundation",
         "libaudioutils",
@@ -125,8 +125,8 @@
         "libvibrator",
     ],
     export_shared_lib_headers: [
-        "audioflinger-aidl-unstable-cpp",
-        "audiopolicy-aidl-unstable-cpp",
+        "audioflinger-aidl-cpp",
+        "audiopolicy-aidl-cpp",
         "libbinder",
     ],
 
@@ -144,15 +144,15 @@
     ],
     export_header_lib_headers: ["libaudioclient_headers"],
     export_static_lib_headers: [
-        "effect-aidl-unstable-cpp",
-        "shared-file-region-aidl-unstable-cpp",
+        "effect-aidl-cpp",
+        "shared-file-region-aidl-cpp",
     ],
 
     static_libs: [
-        "effect-aidl-unstable-cpp",
+        "effect-aidl-cpp",
         // for memory heap analysis
         "libc_malloc_debug_backtrace",
-        "shared-file-region-aidl-unstable-cpp",
+        "shared-file-region-aidl-cpp",
     ],
     cflags: [
         "-Wall",
@@ -213,18 +213,18 @@
         "libaudioclient_aidl_conversion_util",
     ],
     shared_libs: [
-        "audioclient-types-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
         "libbase",
         "libbinder",
         "liblog",
         "libshmemcompat",
         "libutils",
-        "shared-file-region-aidl-unstable-cpp",
+        "shared-file-region-aidl-cpp",
     ],
     export_shared_lib_headers: [
-        "audioclient-types-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
         "libbase",
-        "shared-file-region-aidl-unstable-cpp",
+        "shared-file-region-aidl-cpp",
     ],
     cflags: [
         "-Wall",
diff --git a/media/libaudioclient/PlayerBase.cpp b/media/libaudioclient/PlayerBase.cpp
index 8793735..446a58c 100644
--- a/media/libaudioclient/PlayerBase.cpp
+++ b/media/libaudioclient/PlayerBase.cpp
@@ -49,11 +49,12 @@
     baseDestroy();
 }
 
-void PlayerBase::init(player_type_t playerType, audio_usage_t usage) {
+void PlayerBase::init(player_type_t playerType, audio_usage_t usage, audio_session_t sessionId) {
     if (mAudioManager == 0) {
                 ALOGE("AudioPlayer realize: no audio service, player will not be registered");
     } else {
-        mPIId = mAudioManager->trackPlayer(playerType, usage, AUDIO_CONTENT_TYPE_UNKNOWN, this);
+        mPIId = mAudioManager->trackPlayer(playerType, usage, AUDIO_CONTENT_TYPE_UNKNOWN, this,
+                sessionId);
     }
 }
 
diff --git a/media/libaudioclient/TrackPlayerBase.cpp b/media/libaudioclient/TrackPlayerBase.cpp
index 5c73756..536e9fb 100644
--- a/media/libaudioclient/TrackPlayerBase.cpp
+++ b/media/libaudioclient/TrackPlayerBase.cpp
@@ -33,8 +33,9 @@
     doDestroy();
 }
 
-void TrackPlayerBase::init(AudioTrack* pat, player_type_t playerType, audio_usage_t usage) {
-    PlayerBase::init(playerType, usage);
+void TrackPlayerBase::init(AudioTrack* pat, player_type_t playerType, audio_usage_t usage,
+        audio_session_t sessionId) {
+    PlayerBase::init(playerType, usage, sessionId);
     mAudioTrack = pat;
     if (mAudioTrack != 0) {
         mSelfAudioDeviceCallback = new SelfAudioDeviceCallback(*this);
diff --git a/media/libaudioclient/fuzzer/Android.bp b/media/libaudioclient/fuzzer/Android.bp
new file mode 100644
index 0000000..edfc5a5
--- /dev/null
+++ b/media/libaudioclient/fuzzer/Android.bp
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+cc_fuzz {
+    name: "audioflinger_fuzzer",
+    srcs: [
+        "audioflinger_fuzzer.cpp",
+    ],
+    static_libs: [
+        "android.hardware.audio.common@7.0-enums",
+        "effect-aidl-unstable-cpp",
+        "libaudioclient",
+        "libbase",
+        "libcgrouprc",
+        "libcgrouprc_format",
+        "libcutils",
+        "libjsoncpp",
+        "liblog",
+        "libmediametrics",
+        "libmediametricsservice",
+        "libmedia_helper",
+        "libprocessgroup",
+        "shared-file-region-aidl-unstable-cpp",
+    ],
+    shared_libs: [
+        "android.hardware.audio.common-util",
+        "audioclient-types-aidl-unstable-cpp",
+        "audioflinger-aidl-unstable-cpp",
+        "audiopolicy-aidl-unstable-cpp",
+        "audiopolicy-types-aidl-unstable-cpp",
+        "av-types-aidl-unstable-cpp",
+        "capture_state_listener-aidl-unstable-cpp",
+        "libaudioclient_aidl_conversion",
+        "libaudioflinger",
+        "libaudiofoundation",
+        "libaudiomanager",
+        "libaudiopolicy",
+        "libaudioutils",
+        "libbinder",
+        "libdl",
+        "libmediautils",
+        "libnblog",
+        "libutils",
+        "libxml2",
+        "mediametricsservice-aidl-unstable-cpp",
+    ],
+    header_libs: [
+        "libaudiofoundation_headers",
+        "libmedia_headers",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
diff --git a/media/libaudioclient/fuzzer/README.md b/media/libaudioclient/fuzzer/README.md
new file mode 100644
index 0000000..ada6c49
--- /dev/null
+++ b/media/libaudioclient/fuzzer/README.md
@@ -0,0 +1,80 @@
+# Fuzzer for libaudioflinger
+
+## Plugin Design Considerations
+The fuzzer plugin for libaudioflinger is designed based on the understanding of the
+library and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer. The fuzzer
+covers libaudioflinger APIs as called from libaudioclient through IPC.
+
+libaudioflinger supports the following parameters:
+1. Unique IDs (parameter name: `uniqueId`)
+2. Audio Mode (parameter name: `mode`)
+3. Session ID (parameter name: `sessionId`)
+4. Encapsulation Mode (parameter name: `encapsulationMode`)
+5. Audio Port Role (parameter name: `portRole`)
+6. Audio Port Type (parameter name: `portType`)
+7. Audio Stream Type (parameter name: `streamType`)
+8. Audio Format (parameter name: `format`)
+9. Audio Channel Mask (parameter name: `channelMask`)
+10. Usage (parameter name: `usage`)
+11. Audio Content Type (parameter name: `contentType`)
+12. Input Source (parameter name: `inputSource`)
+13. Input Flags (parameter name: `inputFlags`)
+14. Output Flags (parameter name: `outputFlags`)
+15. Audio Gain Mode (parameter name: `gainMode`)
+16. Audio Device (parameter name: `device`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `uniqueId`   | 0. `AUDIO_UNIQUE_ID_USE_UNSPECIFIED` 1. `AUDIO_UNIQUE_ID_USE_SESSION` 2. `AUDIO_UNIQUE_ID_USE_MODULE` 3. `AUDIO_UNIQUE_ID_USE_EFFECT` 4. `AUDIO_UNIQUE_ID_USE_PATCH` 5. `AUDIO_UNIQUE_ID_USE_OUTPUT` 6. `AUDIO_UNIQUE_ID_USE_INPUT` 7. `AUDIO_UNIQUE_ID_USE_CLIENT` 8. `AUDIO_UNIQUE_ID_USE_MAX` | Value obtained from FuzzedDataProvider
+| `mode`   | 0.`AUDIO_MODE_INVALID` 1. `AUDIO_MODE_CURRENT` 2. ` AUDIO_MODE_NORMAL` 3. `AUDIO_MODE_RINGTONE` 4. `AUDIO_MODE_IN_CALL` 5. `AUDIO_MODE_IN_COMMUNICATION` 6. `AUDIO_MODE_CALL_SCREEN` | Value obtained from FuzzedDataProvider|
+| `sessionId`   | 0. `AUDIO_SESSION_NONE` 1. `AUDIO_SESSION_OUTPUT_STAGE` 2. `AUDIO_SESSION_DEVICE` | Value obtained from FuzzedDataProvider|
+| `encapsulationMode`   | 0. `AUDIO_ENCAPSULATION_MODE_NONE` 1. `AUDIO_ENCAPSULATION_MODE_ELEMENTARY_STREAM` 2. `AUDIO_ENCAPSULATION_MODE_HANDLE` | Value obtained from FuzzedDataProvider|
+| `portRole`   | 0. `AUDIO_PORT_ROLE_NONE` 1. `AUDIO_PORT_ROLE_SOURCE` 2. `AUDIO_PORT_ROLE_SINK` | Value obtained from FuzzedDataProvider|
+| `portType`   | 0. `AUDIO_PORT_TYPE_NONE` 1. `AUDIO_PORT_TYPE_DEVICE` 2. `AUDIO_PORT_TYPE_MIX` 3. `AUDIO_PORT_TYPE_SESSION`| Value obtained from FuzzedDataProvider|
+| `streamType` | 15 values of type `audio_stream_type_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `format` | 77 values of type `audio_format_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `channelMask` | 83 values of type `audio_channel_mask_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `usage` | 22 values of type `audio_usage_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `contentType` | 5 values of type `audio_content_type_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `inputSource` | 14 values of type `audio_source_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `inputFlags` | 9 values of type `audio_input_flags_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `outputFlags` | 16 values of type `audio_output_flags_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `gainMode` | 3 values of type `audio_gain_mode_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `device` | 66 values of type `audio_devices_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+##### Maximize utilization of input data
+The plugin tolerates any kind of input (empty, huge,
+malformed, etc) and doesn't `exit()` on any input and thereby increasing the
+chance of identifying vulnerabilities.
+
+## Build
+
+This describes steps to build audioflinger_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) audioflinger_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/audioflinger_fuzzer/audioflinger_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.co
diff --git a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp
new file mode 100644
index 0000000..db2b0b8
--- /dev/null
+++ b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp
@@ -0,0 +1,730 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/**
+ * NOTE
+ * 1) The input to AudioFlinger binder calls are fuzzed in this fuzzer
+ * 2) AudioFlinger crashes due to the fuzzer are detected by the
+      Binder DeathRecipient, where the fuzzer aborts if AudioFlinger dies
+ */
+
+#include <android_audio_policy_configuration_V7_0-enums.h>
+#include <binder/IServiceManager.h>
+#include <binder/MemoryDealer.h>
+#include <media/AudioEffect.h>
+#include <media/AudioRecord.h>
+#include <media/AudioSystem.h>
+#include <media/AudioTrack.h>
+#include <media/IAudioFlinger.h>
+#include "fuzzer/FuzzedDataProvider.h"
+
+#define MAX_STRING_LENGTH 256
+#define MAX_ARRAY_LENGTH 256
+
+using namespace std;
+using namespace android;
+
+namespace xsd {
+using namespace ::android::audio::policy::configuration::V7_0;
+}
+
+constexpr audio_unique_id_use_t kUniqueIds[] = {
+    AUDIO_UNIQUE_ID_USE_UNSPECIFIED, AUDIO_UNIQUE_ID_USE_SESSION, AUDIO_UNIQUE_ID_USE_MODULE,
+    AUDIO_UNIQUE_ID_USE_EFFECT,      AUDIO_UNIQUE_ID_USE_PATCH,   AUDIO_UNIQUE_ID_USE_OUTPUT,
+    AUDIO_UNIQUE_ID_USE_INPUT,       AUDIO_UNIQUE_ID_USE_CLIENT,  AUDIO_UNIQUE_ID_USE_MAX,
+};
+
+constexpr audio_mode_t kModes[] = {
+    AUDIO_MODE_INVALID, AUDIO_MODE_CURRENT,          AUDIO_MODE_NORMAL,     AUDIO_MODE_RINGTONE,
+    AUDIO_MODE_IN_CALL, AUDIO_MODE_IN_COMMUNICATION, AUDIO_MODE_CALL_SCREEN};
+
+constexpr audio_session_t kSessionId[] = {AUDIO_SESSION_NONE, AUDIO_SESSION_OUTPUT_STAGE,
+                                          AUDIO_SESSION_DEVICE};
+
+constexpr audio_encapsulation_mode_t kEncapsulation[] = {
+    AUDIO_ENCAPSULATION_MODE_NONE,
+    AUDIO_ENCAPSULATION_MODE_ELEMENTARY_STREAM,
+    AUDIO_ENCAPSULATION_MODE_HANDLE,
+};
+
+constexpr audio_port_role_t kPortRoles[] = {
+    AUDIO_PORT_ROLE_NONE,
+    AUDIO_PORT_ROLE_SOURCE,
+    AUDIO_PORT_ROLE_SINK,
+};
+
+constexpr audio_port_type_t kPortTypes[] = {
+    AUDIO_PORT_TYPE_NONE,
+    AUDIO_PORT_TYPE_DEVICE,
+    AUDIO_PORT_TYPE_MIX,
+    AUDIO_PORT_TYPE_SESSION,
+};
+
+template <typename T, typename X, typename FUNC>
+std::vector<T> getFlags(const xsdc_enum_range<X> &range, const FUNC &func,
+                        const std::string &findString = {}) {
+    std::vector<T> vec;
+    for (const auto &xsdEnumVal : range) {
+        T enumVal;
+        std::string enumString = toString(xsdEnumVal);
+        if (enumString.find(findString) != std::string::npos &&
+            func(enumString.c_str(), &enumVal)) {
+            vec.push_back(enumVal);
+        }
+    }
+    return vec;
+}
+
+static const std::vector<audio_stream_type_t> kStreamtypes =
+    getFlags<audio_stream_type_t, xsd::AudioStreamType, decltype(audio_stream_type_from_string)>(
+        xsdc_enum_range<xsd::AudioStreamType>{}, audio_stream_type_from_string);
+
+static const std::vector<audio_format_t> kFormats =
+    getFlags<audio_format_t, xsd::AudioFormat, decltype(audio_format_from_string)>(
+        xsdc_enum_range<xsd::AudioFormat>{}, audio_format_from_string);
+
+static const std::vector<audio_channel_mask_t> kChannelMasks =
+    getFlags<audio_channel_mask_t, xsd::AudioChannelMask, decltype(audio_channel_mask_from_string)>(
+        xsdc_enum_range<xsd::AudioChannelMask>{}, audio_channel_mask_from_string);
+
+static const std::vector<audio_usage_t> kUsages =
+    getFlags<audio_usage_t, xsd::AudioUsage, decltype(audio_usage_from_string)>(
+        xsdc_enum_range<xsd::AudioUsage>{}, audio_usage_from_string);
+
+static const std::vector<audio_content_type_t> kContentType =
+    getFlags<audio_content_type_t, xsd::AudioContentType, decltype(audio_content_type_from_string)>(
+        xsdc_enum_range<xsd::AudioContentType>{}, audio_content_type_from_string);
+
+static const std::vector<audio_source_t> kInputSources =
+    getFlags<audio_source_t, xsd::AudioSource, decltype(audio_source_from_string)>(
+        xsdc_enum_range<xsd::AudioSource>{}, audio_source_from_string);
+
+static const std::vector<audio_gain_mode_t> kGainModes =
+    getFlags<audio_gain_mode_t, xsd::AudioGainMode, decltype(audio_gain_mode_from_string)>(
+        xsdc_enum_range<xsd::AudioGainMode>{}, audio_gain_mode_from_string);
+
+static const std::vector<audio_devices_t> kDevices =
+    getFlags<audio_devices_t, xsd::AudioDevice, decltype(audio_device_from_string)>(
+        xsdc_enum_range<xsd::AudioDevice>{}, audio_device_from_string);
+
+static const std::vector<audio_input_flags_t> kInputFlags =
+    getFlags<audio_input_flags_t, xsd::AudioInOutFlag, decltype(audio_input_flag_from_string)>(
+        xsdc_enum_range<xsd::AudioInOutFlag>{}, audio_input_flag_from_string, "_INPUT_");
+
+static const std::vector<audio_output_flags_t> kOutputFlags =
+    getFlags<audio_output_flags_t, xsd::AudioInOutFlag, decltype(audio_output_flag_from_string)>(
+        xsdc_enum_range<xsd::AudioInOutFlag>{}, audio_output_flag_from_string, "_OUTPUT_");
+
+template <typename T, size_t size>
+T getValueFromArray(FuzzedDataProvider *fdp, const T (&arr)[size]) {
+    return arr[fdp->ConsumeIntegralInRange<int32_t>(0, size - 1)];
+}
+
+template <typename T, size_t size>
+T getValue(FuzzedDataProvider *fdp, const T (&arr)[size]) {
+    if (fdp->ConsumeBool()) {
+        return static_cast<T>(fdp->ConsumeIntegral<int32_t>());
+    }
+    return getValueFromArray(fdp, arr);
+}
+
+template <typename T>
+T getValueFromVector(FuzzedDataProvider *fdp, std::vector<T> vec) {
+    return vec[fdp->ConsumeIntegralInRange<int32_t>(0, vec.size() - 1)];
+}
+
+template <typename T>
+T getValue(FuzzedDataProvider *fdp, std::vector<T> vec) {
+    if (fdp->ConsumeBool()) {
+        return static_cast<T>(fdp->ConsumeIntegral<int32_t>());
+    }
+    return getValueFromVector(fdp, vec);
+}
+
+class DeathNotifier : public IBinder::DeathRecipient {
+   public:
+    void binderDied(const wp<IBinder> &) { abort(); }
+};
+
+class AudioFlingerFuzzer {
+   public:
+    AudioFlingerFuzzer(const uint8_t *data, size_t size);
+    void process();
+
+   private:
+    FuzzedDataProvider mFdp;
+    void invokeAudioTrack();
+    void invokeAudioRecord();
+    status_t invokeAudioEffect();
+    void invokeAudioSystem();
+    status_t invokeAudioInputDevice();
+    status_t invokeAudioOutputDevice();
+    void invokeAudioPatch();
+
+    sp<DeathNotifier> mDeathNotifier;
+};
+
+AudioFlingerFuzzer::AudioFlingerFuzzer(const uint8_t *data, size_t size) : mFdp(data, size) {
+    sp<IServiceManager> sm = defaultServiceManager();
+    sp<IBinder> binder = sm->getService(String16("media.audio_flinger"));
+    if (binder == nullptr) {
+        return;
+    }
+    mDeathNotifier = new DeathNotifier();
+    binder->linkToDeath(mDeathNotifier);
+}
+
+void AudioFlingerFuzzer::invokeAudioTrack() {
+    uint32_t sampleRate = mFdp.ConsumeIntegral<uint32_t>();
+    audio_format_t format = getValue(&mFdp, kFormats);
+    audio_channel_mask_t channelMask = getValue(&mFdp, kChannelMasks);
+    size_t frameCount = static_cast<size_t>(mFdp.ConsumeIntegral<uint32_t>());
+    int32_t notificationFrames = mFdp.ConsumeIntegral<int32_t>();
+    uint32_t useSharedBuffer = mFdp.ConsumeBool();
+    audio_output_flags_t flags = getValue(&mFdp, kOutputFlags);
+    audio_session_t sessionId = getValue(&mFdp, kSessionId);
+    audio_usage_t usage = getValue(&mFdp, kUsages);
+    audio_content_type_t contentType = getValue(&mFdp, kContentType);
+    audio_attributes_t attributes = {};
+    sp<IMemory> sharedBuffer;
+    sp<MemoryDealer> heap = nullptr;
+    audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
+
+    bool offload = false;
+    bool fast = ((flags & AUDIO_OUTPUT_FLAG_FAST) != 0);
+
+    if (useSharedBuffer != 0) {
+        size_t heapSize = audio_channel_count_from_out_mask(channelMask) *
+                          audio_bytes_per_sample(format) * frameCount;
+        heap = new MemoryDealer(heapSize, "AudioTrack Heap Base");
+        sharedBuffer = heap->allocate(heapSize);
+        frameCount = 0;
+        notificationFrames = 0;
+    }
+    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
+        offloadInfo.sample_rate = sampleRate;
+        offloadInfo.channel_mask = channelMask;
+        offloadInfo.format = format;
+        offload = true;
+    }
+
+    attributes.content_type = contentType;
+    attributes.usage = usage;
+    sp<AudioTrack> track = new AudioTrack();
+
+    track->set(AUDIO_STREAM_DEFAULT, sampleRate, format, channelMask, frameCount, flags, nullptr,
+               nullptr, notificationFrames, sharedBuffer, false, sessionId,
+               ((fast && sharedBuffer == 0) || offload) ? AudioTrack::TRANSFER_CALLBACK
+                                                        : AudioTrack::TRANSFER_DEFAULT,
+               offload ? &offloadInfo : nullptr, getuid(), getpid(), &attributes, false, 1.0f,
+               AUDIO_PORT_HANDLE_NONE);
+
+    status_t status = track->initCheck();
+    if (status != NO_ERROR) {
+        track.clear();
+        return;
+    }
+    track->getSampleRate();
+    track->latency();
+    track->getUnderrunCount();
+    track->streamType();
+    track->channelCount();
+    track->getNotificationPeriodInFrames();
+    uint32_t bufferSizeInFrames = mFdp.ConsumeIntegral<uint32_t>();
+    track->setBufferSizeInFrames(bufferSizeInFrames);
+    track->getBufferSizeInFrames();
+
+    int64_t duration = mFdp.ConsumeIntegral<int64_t>();
+    track->getBufferDurationInUs(&duration);
+    sp<IMemory> sharedBuffer2 = track->sharedBuffer();
+    track->setCallerName(mFdp.ConsumeRandomLengthString(MAX_STRING_LENGTH));
+
+    track->setVolume(mFdp.ConsumeFloatingPoint<float>(), mFdp.ConsumeFloatingPoint<float>());
+    track->setVolume(mFdp.ConsumeFloatingPoint<float>());
+    track->setAuxEffectSendLevel(mFdp.ConsumeFloatingPoint<float>());
+
+    float auxEffectSendLevel;
+    track->getAuxEffectSendLevel(&auxEffectSendLevel);
+    track->setSampleRate(mFdp.ConsumeIntegral<uint32_t>());
+    track->getSampleRate();
+    track->getOriginalSampleRate();
+
+    AudioPlaybackRate playbackRate = {};
+    playbackRate.mSpeed = mFdp.ConsumeFloatingPoint<float>();
+    playbackRate.mPitch = mFdp.ConsumeFloatingPoint<float>();
+    track->setPlaybackRate(playbackRate);
+    track->getPlaybackRate();
+    track->setLoop(mFdp.ConsumeIntegral<uint32_t>(), mFdp.ConsumeIntegral<uint32_t>(),
+                   mFdp.ConsumeIntegral<uint32_t>());
+    track->setMarkerPosition(mFdp.ConsumeIntegral<uint32_t>());
+
+    uint32_t marker = {};
+    track->getMarkerPosition(&marker);
+    track->setPositionUpdatePeriod(mFdp.ConsumeIntegral<uint32_t>());
+
+    uint32_t updatePeriod = {};
+    track->getPositionUpdatePeriod(&updatePeriod);
+    track->setPosition(mFdp.ConsumeIntegral<uint32_t>());
+    uint32_t position = {};
+    track->getPosition(&position);
+    track->getBufferPosition(&position);
+    track->reload();
+    track->start();
+    track->pause();
+    track->flush();
+    track->stop();
+    track->stopped();
+}
+
+void AudioFlingerFuzzer::invokeAudioRecord() {
+    int32_t notificationFrames = mFdp.ConsumeIntegral<int32_t>();
+    uint32_t sampleRate = mFdp.ConsumeIntegral<uint32_t>();
+    size_t frameCount = static_cast<size_t>(mFdp.ConsumeIntegral<uint32_t>());
+    audio_format_t format = getValue(&mFdp, kFormats);
+    audio_channel_mask_t channelMask = getValue(&mFdp, kChannelMasks);
+    audio_input_flags_t flags = getValue(&mFdp, kInputFlags);
+    audio_session_t sessionId = getValue(&mFdp, kSessionId);
+    audio_source_t inputSource = getValue(&mFdp, kInputSources);
+
+    audio_attributes_t attributes = {};
+    bool fast = ((flags & AUDIO_OUTPUT_FLAG_FAST) != 0);
+
+    attributes.source = inputSource;
+
+    sp<AudioRecord> record = new AudioRecord(String16(mFdp.ConsumeRandomLengthString().c_str()));
+    record->set(AUDIO_SOURCE_DEFAULT, sampleRate, format, channelMask, frameCount, nullptr, nullptr,
+                notificationFrames, false, sessionId,
+                fast ? AudioRecord::TRANSFER_CALLBACK : AudioRecord::TRANSFER_DEFAULT, flags,
+                getuid(), getpid(), &attributes, AUDIO_PORT_HANDLE_NONE);
+    status_t status = record->initCheck();
+    if (status != NO_ERROR) {
+        return;
+    }
+    record->latency();
+    record->format();
+    record->channelCount();
+    record->frameCount();
+    record->frameSize();
+    record->inputSource();
+    record->getNotificationPeriodInFrames();
+    record->start();
+    record->stop();
+    record->stopped();
+
+    uint32_t marker = mFdp.ConsumeIntegral<uint32_t>();
+    record->setMarkerPosition(marker);
+    record->getMarkerPosition(&marker);
+
+    uint32_t updatePeriod = mFdp.ConsumeIntegral<uint32_t>();
+    record->setPositionUpdatePeriod(updatePeriod);
+    record->getPositionUpdatePeriod(&updatePeriod);
+
+    uint32_t position;
+    record->getPosition(&position);
+
+    ExtendedTimestamp timestamp;
+    record->getTimestamp(&timestamp);
+    record->getSessionId();
+    record->getCallerName();
+    android::AudioRecord::Buffer audioBuffer;
+    int32_t waitCount = mFdp.ConsumeIntegral<int32_t>();
+    size_t nonContig = static_cast<size_t>(mFdp.ConsumeIntegral<uint32_t>());
+    audioBuffer.frameCount = static_cast<size_t>(mFdp.ConsumeIntegral<uint32_t>());
+    record->obtainBuffer(&audioBuffer, waitCount, &nonContig);
+    bool blocking = false;
+    record->read(audioBuffer.raw, audioBuffer.size, blocking);
+    record->getInputFramesLost();
+    record->getFlags();
+
+    std::vector<media::MicrophoneInfo> activeMicrophones;
+    record->getActiveMicrophones(&activeMicrophones);
+    record->releaseBuffer(&audioBuffer);
+
+    audio_port_handle_t deviceId =
+        static_cast<audio_port_handle_t>(mFdp.ConsumeIntegral<int32_t>());
+    record->setInputDevice(deviceId);
+    record->getInputDevice();
+    record->getRoutedDeviceId();
+    record->getPortId();
+}
+
+struct EffectClient : public android::media::BnEffectClient {
+    EffectClient() {}
+    binder::Status controlStatusChanged(bool controlGranted __unused) override {
+        return binder::Status::ok();
+    }
+    binder::Status enableStatusChanged(bool enabled __unused) override {
+        return binder::Status::ok();
+    }
+    binder::Status commandExecuted(int32_t cmdCode __unused,
+                                   const std::vector<uint8_t> &cmdData __unused,
+                                   const std::vector<uint8_t> &replyData __unused) override {
+        return binder::Status::ok();
+    }
+};
+
+status_t AudioFlingerFuzzer::invokeAudioEffect() {
+    effect_uuid_t type;
+    type.timeLow = mFdp.ConsumeIntegral<uint32_t>();
+    type.timeMid = mFdp.ConsumeIntegral<uint16_t>();
+    type.timeHiAndVersion = mFdp.ConsumeIntegral<uint16_t>();
+    type.clockSeq = mFdp.ConsumeIntegral<uint16_t>();
+    for (int i = 0; i < 6; ++i) {
+        type.node[i] = mFdp.ConsumeIntegral<uint8_t>();
+    }
+
+    effect_descriptor_t descriptor = {};
+    descriptor.type = type;
+    descriptor.uuid = *EFFECT_UUID_NULL;
+
+    sp<EffectClient> effectClient(new EffectClient());
+
+    const int32_t priority = mFdp.ConsumeIntegral<int32_t>();
+    audio_session_t sessionId = static_cast<audio_session_t>(mFdp.ConsumeIntegral<int32_t>());
+    const audio_io_handle_t io = mFdp.ConsumeIntegral<int32_t>();
+    String16 opPackageName = static_cast<String16>(mFdp.ConsumeRandomLengthString().c_str());
+    AudioDeviceTypeAddr device;
+
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (!af) {
+        return NO_ERROR;
+    }
+
+    media::CreateEffectRequest request{};
+    request.desc =
+        VALUE_OR_RETURN_STATUS(legacy2aidl_effect_descriptor_t_EffectDescriptor(descriptor));
+    request.client = effectClient;
+    request.priority = priority;
+    request.output = io;
+    request.sessionId = sessionId;
+    request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(device));
+    request.opPackageName = VALUE_OR_RETURN_STATUS(legacy2aidl_String16_string(opPackageName));
+    request.pid = getpid();
+    request.probe = false;
+
+    media::CreateEffectResponse response{};
+    status_t status = af->createEffect(request, &response);
+
+    if (status != OK) {
+        return NO_ERROR;
+    }
+
+    descriptor =
+        VALUE_OR_RETURN_STATUS(aidl2legacy_EffectDescriptor_effect_descriptor_t(response.desc));
+
+    uint32_t numEffects;
+    af->queryNumberEffects(&numEffects);
+
+    uint32_t queryIndex = mFdp.ConsumeIntegral<uint32_t>();
+    af->queryEffect(queryIndex, &descriptor);
+
+    effect_descriptor_t getDescriptor;
+    uint32_t preferredTypeFlag = mFdp.ConsumeIntegral<int32_t>();
+    af->getEffectDescriptor(&descriptor.uuid, &descriptor.type, preferredTypeFlag, &getDescriptor);
+
+    sessionId = static_cast<audio_session_t>(mFdp.ConsumeIntegral<int32_t>());
+    audio_io_handle_t srcOutput = mFdp.ConsumeIntegral<int32_t>();
+    audio_io_handle_t dstOutput = mFdp.ConsumeIntegral<int32_t>();
+    af->moveEffects(sessionId, srcOutput, dstOutput);
+
+    int effectId = mFdp.ConsumeIntegral<int32_t>();
+    sessionId = static_cast<audio_session_t>(mFdp.ConsumeIntegral<int32_t>());
+    af->setEffectSuspended(effectId, sessionId, mFdp.ConsumeBool());
+    return NO_ERROR;
+}
+
+void AudioFlingerFuzzer::invokeAudioSystem() {
+    AudioSystem::muteMicrophone(mFdp.ConsumeBool());
+    AudioSystem::setMasterMute(mFdp.ConsumeBool());
+    AudioSystem::setMasterVolume(mFdp.ConsumeFloatingPoint<float>());
+    AudioSystem::setMasterBalance(mFdp.ConsumeFloatingPoint<float>());
+    AudioSystem::setVoiceVolume(mFdp.ConsumeFloatingPoint<float>());
+
+    float volume;
+    AudioSystem::getMasterVolume(&volume);
+
+    bool state;
+    AudioSystem::getMasterMute(&state);
+    AudioSystem::isMicrophoneMuted(&state);
+
+    audio_stream_type_t stream = getValue(&mFdp, kStreamtypes);
+    AudioSystem::setStreamMute(getValue(&mFdp, kStreamtypes), mFdp.ConsumeBool());
+
+    stream = getValue(&mFdp, kStreamtypes);
+    AudioSystem::setStreamVolume(stream, mFdp.ConsumeFloatingPoint<float>(),
+                                 mFdp.ConsumeIntegral<int32_t>());
+
+    audio_mode_t mode = getValue(&mFdp, kModes);
+    AudioSystem::setMode(mode);
+
+    size_t frameCount;
+    stream = getValue(&mFdp, kStreamtypes);
+    AudioSystem::getOutputFrameCount(&frameCount, stream);
+
+    uint32_t latency;
+    stream = getValue(&mFdp, kStreamtypes);
+    AudioSystem::getOutputLatency(&latency, stream);
+
+    stream = getValue(&mFdp, kStreamtypes);
+    AudioSystem::getStreamVolume(stream, &volume, mFdp.ConsumeIntegral<int32_t>());
+
+    stream = getValue(&mFdp, kStreamtypes);
+    AudioSystem::getStreamMute(stream, &state);
+
+    uint32_t samplingRate;
+    AudioSystem::getSamplingRate(mFdp.ConsumeIntegral<int32_t>(), &samplingRate);
+
+    AudioSystem::getFrameCount(mFdp.ConsumeIntegral<int32_t>(), &frameCount);
+    AudioSystem::getLatency(mFdp.ConsumeIntegral<int32_t>(), &latency);
+    AudioSystem::setVoiceVolume(mFdp.ConsumeFloatingPoint<float>());
+
+    uint32_t halFrames;
+    uint32_t dspFrames;
+    AudioSystem::getRenderPosition(mFdp.ConsumeIntegral<int32_t>(), &halFrames, &dspFrames);
+
+    AudioSystem::getInputFramesLost(mFdp.ConsumeIntegral<int32_t>());
+    AudioSystem::getInputFramesLost(mFdp.ConsumeIntegral<int32_t>());
+
+    audio_unique_id_use_t uniqueIdUse = getValue(&mFdp, kUniqueIds);
+    AudioSystem::newAudioUniqueId(uniqueIdUse);
+
+    audio_session_t sessionId = getValue(&mFdp, kSessionId);
+    pid_t pid = mFdp.ConsumeBool() ? getpid() : mFdp.ConsumeIntegral<int32_t>();
+    uid_t uid = mFdp.ConsumeBool() ? getuid() : mFdp.ConsumeIntegral<int32_t>();
+    AudioSystem::acquireAudioSessionId(sessionId, pid, uid);
+
+    pid = mFdp.ConsumeBool() ? getpid() : mFdp.ConsumeIntegral<int32_t>();
+    sessionId = getValue(&mFdp, kSessionId);
+    AudioSystem::releaseAudioSessionId(sessionId, pid);
+
+    sessionId = getValue(&mFdp, kSessionId);
+    AudioSystem::getAudioHwSyncForSession(sessionId);
+
+    AudioSystem::systemReady();
+    AudioSystem::getFrameCountHAL(mFdp.ConsumeIntegral<int32_t>(), &frameCount);
+
+    size_t buffSize;
+    uint32_t sampleRate = mFdp.ConsumeIntegral<uint32_t>();
+    audio_format_t format = getValue(&mFdp, kFormats);
+    audio_channel_mask_t channelMask = getValue(&mFdp, kChannelMasks);
+    AudioSystem::getInputBufferSize(sampleRate, format, channelMask, &buffSize);
+
+    AudioSystem::getPrimaryOutputSamplingRate();
+    AudioSystem::getPrimaryOutputFrameCount();
+    AudioSystem::setLowRamDevice(mFdp.ConsumeBool(), mFdp.ConsumeIntegral<int64_t>());
+
+    std::vector<media::MicrophoneInfo> microphones;
+    AudioSystem::getMicrophones(&microphones);
+
+    std::vector<pid_t> pids;
+    pids.insert(pids.begin(), getpid());
+    for (int i = 1; i < mFdp.ConsumeIntegralInRange<int32_t>(2, MAX_ARRAY_LENGTH); ++i) {
+        pids.insert(pids.begin() + i, static_cast<pid_t>(mFdp.ConsumeIntegral<int32_t>()));
+    }
+    AudioSystem::setAudioHalPids(pids);
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (!af) {
+        return;
+    }
+    af->setRecordSilenced(mFdp.ConsumeIntegral<uint32_t>(), mFdp.ConsumeBool());
+
+    float balance = mFdp.ConsumeFloatingPoint<float>();
+    af->getMasterBalance(&balance);
+    af->invalidateStream(static_cast<audio_stream_type_t>(mFdp.ConsumeIntegral<uint32_t>()));
+}
+
+status_t AudioFlingerFuzzer::invokeAudioInputDevice() {
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (!af) {
+        return NO_ERROR;
+    }
+
+    audio_config_t config = {};
+    audio_module_handle_t module = mFdp.ConsumeIntegral<int32_t>();
+    audio_io_handle_t input = mFdp.ConsumeIntegral<int32_t>();
+    config.frame_count = mFdp.ConsumeIntegral<uint32_t>();
+    String8 address = static_cast<String8>(mFdp.ConsumeRandomLengthString().c_str());
+
+    config.channel_mask = getValue(&mFdp, kChannelMasks);
+    config.format = getValue(&mFdp, kFormats);
+
+    config.offload_info = AUDIO_INFO_INITIALIZER;
+    config.offload_info.bit_rate = mFdp.ConsumeIntegral<uint32_t>();
+    config.offload_info.bit_width = mFdp.ConsumeIntegral<uint32_t>();
+    config.offload_info.content_id = mFdp.ConsumeIntegral<uint32_t>();
+    config.offload_info.channel_mask = getValue(&mFdp, kChannelMasks);
+    config.offload_info.duration_us = mFdp.ConsumeIntegral<int64_t>();
+    config.offload_info.encapsulation_mode = getValue(&mFdp, kEncapsulation);
+    config.offload_info.format = getValue(&mFdp, kFormats);
+    config.offload_info.has_video = mFdp.ConsumeBool();
+    config.offload_info.is_streaming = mFdp.ConsumeBool();
+    config.offload_info.sample_rate = (mFdp.ConsumeIntegral<uint32_t>());
+    config.offload_info.sync_id = mFdp.ConsumeIntegral<uint32_t>();
+    config.offload_info.stream_type = getValue(&mFdp, kStreamtypes);
+    config.offload_info.usage = getValue(&mFdp, kUsages);
+
+    config.sample_rate = mFdp.ConsumeIntegral<uint32_t>();
+
+    audio_devices_t device = getValue(&mFdp, kDevices);
+    audio_source_t source = getValue(&mFdp, kInputSources);
+    audio_input_flags_t flags = getValue(&mFdp, kInputFlags);
+
+    AudioDeviceTypeAddr deviceTypeAddr(device, address.c_str());
+
+    media::OpenInputRequest request{};
+    request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module));
+    request.input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input));
+    request.config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config));
+    request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(deviceTypeAddr));
+    request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSourceType(source));
+    request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags));
+
+    media::OpenInputResponse response{};
+    status_t status = af->openInput(request, &response);
+    if (status != NO_ERROR) {
+        return NO_ERROR;
+    }
+
+    input = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(response.input));
+    af->closeInput(input);
+    return NO_ERROR;
+}
+
+status_t AudioFlingerFuzzer::invokeAudioOutputDevice() {
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (!af) {
+        return NO_ERROR;
+    }
+
+    audio_config_t config = {};
+    audio_module_handle_t module = mFdp.ConsumeIntegral<int32_t>();
+    audio_io_handle_t output = mFdp.ConsumeIntegral<int32_t>();
+    config.frame_count = mFdp.ConsumeIntegral<uint32_t>();
+    String8 address = static_cast<String8>(mFdp.ConsumeRandomLengthString().c_str());
+
+    config.channel_mask = getValue(&mFdp, kChannelMasks);
+
+    config.offload_info = AUDIO_INFO_INITIALIZER;
+    config.offload_info.bit_rate = mFdp.ConsumeIntegral<uint32_t>();
+    config.offload_info.bit_width = mFdp.ConsumeIntegral<uint32_t>();
+    config.offload_info.channel_mask = getValue(&mFdp, kChannelMasks);
+    config.offload_info.content_id = mFdp.ConsumeIntegral<uint32_t>();
+    config.offload_info.duration_us = mFdp.ConsumeIntegral<int64_t>();
+    config.offload_info.encapsulation_mode = getValue(&mFdp, kEncapsulation);
+    config.offload_info.format = getValue(&mFdp, kFormats);
+    config.offload_info.has_video = mFdp.ConsumeBool();
+    config.offload_info.is_streaming = mFdp.ConsumeBool();
+    config.offload_info.sample_rate = mFdp.ConsumeIntegral<uint32_t>();
+    config.offload_info.stream_type = getValue(&mFdp, kStreamtypes);
+    config.offload_info.sync_id = mFdp.ConsumeIntegral<uint32_t>();
+    config.offload_info.usage = getValue(&mFdp, kUsages);
+
+    config.format = getValue(&mFdp, kFormats);
+    config.sample_rate = mFdp.ConsumeIntegral<uint32_t>();
+
+    sp<DeviceDescriptorBase> device = new DeviceDescriptorBase(getValue(&mFdp, kDevices));
+    audio_output_flags_t flags = getValue(&mFdp, kOutputFlags);
+
+    media::OpenOutputRequest request{};
+    media::OpenOutputResponse response{};
+
+    request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module));
+    request.config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config));
+    request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_DeviceDescriptorBase(device));
+    request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_output_flags_t_int32_t_mask(flags));
+
+    status_t status = af->openOutput(request, &response);
+    if (status != NO_ERROR) {
+        return NO_ERROR;
+    }
+    output = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_io_handle_t(response.output));
+
+    audio_io_handle_t output1 = mFdp.ConsumeIntegral<int32_t>();
+    af->openDuplicateOutput(output, output1);
+    af->suspendOutput(output);
+    af->restoreOutput(output);
+    af->closeOutput(output);
+    return NO_ERROR;
+}
+
+void AudioFlingerFuzzer::invokeAudioPatch() {
+    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
+    if (!af) {
+        return;
+    }
+    struct audio_patch patch = {};
+    audio_patch_handle_t handle = mFdp.ConsumeIntegral<int32_t>();
+
+    patch.id = mFdp.ConsumeIntegral<int32_t>();
+    patch.num_sources = mFdp.ConsumeIntegral<uint32_t>();
+    patch.num_sinks = mFdp.ConsumeIntegral<uint32_t>();
+
+    for (int i = 0; i < AUDIO_PATCH_PORTS_MAX; ++i) {
+        patch.sources[i].config_mask = mFdp.ConsumeIntegral<uint32_t>();
+        patch.sources[i].channel_mask = getValue(&mFdp, kChannelMasks);
+        patch.sources[i].format = getValue(&mFdp, kFormats);
+        patch.sources[i].gain.channel_mask = getValue(&mFdp, kChannelMasks);
+        patch.sources[i].gain.index = mFdp.ConsumeIntegral<int32_t>();
+        patch.sources[i].gain.mode = getValue(&mFdp, kGainModes);
+        patch.sources[i].gain.ramp_duration_ms = mFdp.ConsumeIntegral<uint32_t>();
+        patch.sources[i].id = static_cast<audio_format_t>(mFdp.ConsumeIntegral<int32_t>());
+        patch.sources[i].role = getValue(&mFdp, kPortRoles);
+        patch.sources[i].sample_rate = mFdp.ConsumeIntegral<uint32_t>();
+        patch.sources[i].type = getValue(&mFdp, kPortTypes);
+
+        patch.sinks[i].config_mask = mFdp.ConsumeIntegral<uint32_t>();
+        patch.sinks[i].channel_mask = getValue(&mFdp, kChannelMasks);
+        patch.sinks[i].format = getValue(&mFdp, kFormats);
+        patch.sinks[i].gain.channel_mask = getValue(&mFdp, kChannelMasks);
+        patch.sinks[i].gain.index = mFdp.ConsumeIntegral<int32_t>();
+        patch.sinks[i].gain.mode = getValue(&mFdp, kGainModes);
+        patch.sinks[i].gain.ramp_duration_ms = mFdp.ConsumeIntegral<uint32_t>();
+        patch.sinks[i].id = static_cast<audio_format_t>(mFdp.ConsumeIntegral<int32_t>());
+        patch.sinks[i].role = getValue(&mFdp, kPortRoles);
+        patch.sinks[i].sample_rate = mFdp.ConsumeIntegral<uint32_t>();
+        patch.sinks[i].type = getValue(&mFdp, kPortTypes);
+    }
+
+    status_t status = af->createAudioPatch(&patch, &handle);
+    if (status != NO_ERROR) {
+        return;
+    }
+
+    unsigned int num_patches = mFdp.ConsumeIntegral<uint32_t>();
+    struct audio_patch patches = {};
+    af->listAudioPatches(&num_patches, &patches);
+    af->releaseAudioPatch(handle);
+}
+
+void AudioFlingerFuzzer::process() {
+    invokeAudioEffect();
+    invokeAudioInputDevice();
+    invokeAudioOutputDevice();
+    invokeAudioPatch();
+    invokeAudioRecord();
+    invokeAudioSystem();
+    invokeAudioTrack();
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    if (size < 1) {
+        return 0;
+    }
+    AudioFlingerFuzzer audioFuzzer(data, size);
+    audioFuzzer.process();
+    return 0;
+}
diff --git a/media/libaudioclient/include/media/AudioTrack.h b/media/libaudioclient/include/media/AudioTrack.h
index d2696c7..e60ed55 100644
--- a/media/libaudioclient/include/media/AudioTrack.h
+++ b/media/libaudioclient/include/media/AudioTrack.h
@@ -662,9 +662,7 @@
      *  handle on audio hardware output, or AUDIO_IO_HANDLE_NONE if the
      *  track needed to be re-created but that failed
      */
-private:
             audio_io_handle_t    getOutput() const;
-public:
 
     /* Selects the audio device to use for output of this AudioTrack. A value of
      * AUDIO_PORT_HANDLE_NONE indicates default (AudioPolicyManager) routing.
diff --git a/media/libaudioclient/include/media/PlayerBase.h b/media/libaudioclient/include/media/PlayerBase.h
index 1a42b88..62cc21d 100644
--- a/media/libaudioclient/include/media/PlayerBase.h
+++ b/media/libaudioclient/include/media/PlayerBase.h
@@ -55,7 +55,7 @@
 
 protected:
 
-            void init(player_type_t playerType, audio_usage_t usage);
+            void init(player_type_t playerType, audio_usage_t usage, audio_session_t sessionId);
             void baseDestroy();
 
     //IPlayer methods handlers for derived classes
diff --git a/media/libaudioclient/include/media/TrackPlayerBase.h b/media/libaudioclient/include/media/TrackPlayerBase.h
index b40d1eb..80124b8 100644
--- a/media/libaudioclient/include/media/TrackPlayerBase.h
+++ b/media/libaudioclient/include/media/TrackPlayerBase.h
@@ -28,7 +28,8 @@
     explicit TrackPlayerBase();
     virtual ~TrackPlayerBase();
 
-            void init(AudioTrack* pat, player_type_t playerType, audio_usage_t usage);
+            void init(AudioTrack* pat, player_type_t playerType, audio_usage_t usage,
+                    audio_session_t sessionId);
     virtual void destroy();
 
     //IPlayer implementation
diff --git a/media/libaudiofoundation/Android.bp b/media/libaudiofoundation/Android.bp
index 9296d0e..a89d086 100644
--- a/media/libaudiofoundation/Android.bp
+++ b/media/libaudiofoundation/Android.bp
@@ -15,10 +15,10 @@
         "libmedia_helper_headers",
     ],
     static_libs: [
-        "audioclient-types-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
     ],
     export_static_lib_headers: [
-        "audioclient-types-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
     ],
     host_supported: true,
     target: {
@@ -43,7 +43,7 @@
     ],
 
     shared_libs: [
-        "audioclient-types-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
         "libaudioclient_aidl_conversion",
         "libaudioutils",
         "libbase",
@@ -54,7 +54,7 @@
     ],
 
     export_shared_lib_headers: [
-        "audioclient-types-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
         "libaudioclient_aidl_conversion",
     ],
 
diff --git a/media/libaudiohal/impl/Android.bp b/media/libaudiohal/impl/Android.bp
index 3727404..8975cc3 100644
--- a/media/libaudiohal/impl/Android.bp
+++ b/media/libaudiohal/impl/Android.bp
@@ -26,7 +26,7 @@
         "android.hardware.audio.common-util",
         "android.hidl.allocator@1.0",
         "android.hidl.memory@1.0",
-        "av-types-aidl-unstable-cpp",
+        "av-types-aidl-cpp",
         "libaudiofoundation",
         "libaudiohal_deathhandler",
         "libaudioutils",
diff --git a/media/libmedia/Android.bp b/media/libmedia/Android.bp
index f68f65d..79d6c0b 100644
--- a/media/libmedia/Android.bp
+++ b/media/libmedia/Android.bp
@@ -324,8 +324,8 @@
 
     shared_libs: [
         "android.hidl.token@1.0-utils",
-        "audioclient-types-aidl-unstable-cpp",
-        "av-types-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
+        "av-types-aidl-cpp",
         "liblog",
         "libcutils",
         "libprocessgroup",
diff --git a/media/libmedia/MediaProfiles.cpp b/media/libmedia/MediaProfiles.cpp
index e8839ba..1705c97 100644
--- a/media/libmedia/MediaProfiles.cpp
+++ b/media/libmedia/MediaProfiles.cpp
@@ -121,6 +121,11 @@
     {"1080p", CAMCORDER_QUALITY_1080P},
     {"2160p", CAMCORDER_QUALITY_2160P},
     {"qvga", CAMCORDER_QUALITY_QVGA},
+    {"vga", CAMCORDER_QUALITY_VGA},
+    {"4kdci", CAMCORDER_QUALITY_4KDCI},
+    {"qhd", CAMCORDER_QUALITY_QHD},
+    {"2k", CAMCORDER_QUALITY_2K},
+    {"8kuhd", CAMCORDER_QUALITY_8KUHD},
 
     {"timelapselow",  CAMCORDER_QUALITY_TIME_LAPSE_LOW},
     {"timelapsehigh", CAMCORDER_QUALITY_TIME_LAPSE_HIGH},
@@ -131,6 +136,10 @@
     {"timelapse1080p", CAMCORDER_QUALITY_TIME_LAPSE_1080P},
     {"timelapse2160p", CAMCORDER_QUALITY_TIME_LAPSE_2160P},
     {"timelapseqvga", CAMCORDER_QUALITY_TIME_LAPSE_QVGA},
+    {"timelapsevga", CAMCORDER_QUALITY_TIME_LAPSE_VGA},
+    {"timelapse4kdci", CAMCORDER_QUALITY_TIME_LAPSE_4KDCI},
+    {"timelapseqhd", CAMCORDER_QUALITY_TIME_LAPSE_QHD},
+    {"timelapse2k", CAMCORDER_QUALITY_TIME_LAPSE_2K},
 
     {"highspeedlow",  CAMCORDER_QUALITY_HIGH_SPEED_LOW},
     {"highspeedhigh", CAMCORDER_QUALITY_HIGH_SPEED_HIGH},
@@ -138,19 +147,11 @@
     {"highspeed720p", CAMCORDER_QUALITY_HIGH_SPEED_720P},
     {"highspeed1080p", CAMCORDER_QUALITY_HIGH_SPEED_1080P},
     {"highspeed2160p", CAMCORDER_QUALITY_HIGH_SPEED_2160P},
-
-    // Vendor-specific profiles
-    {"vga", CAMCORDER_QUALITY_VGA},
-    {"4kdci", CAMCORDER_QUALITY_4KDCI},
-    {"timelapsevga", CAMCORDER_QUALITY_TIME_LAPSE_VGA},
-    {"timelapse4kdci", CAMCORDER_QUALITY_TIME_LAPSE_4KDCI},
     {"highspeedcif", CAMCORDER_QUALITY_HIGH_SPEED_CIF},
     {"highspeedvga", CAMCORDER_QUALITY_HIGH_SPEED_VGA},
     {"highspeed4kdci", CAMCORDER_QUALITY_HIGH_SPEED_4KDCI},
-    {"qhd", CAMCORDER_QUALITY_QHD},
-    {"2k", CAMCORDER_QUALITY_2k},
-    {"timelapseqhd", CAMCORDER_QUALITY_TIME_LAPSE_QHD},
-    {"timelapse2k", CAMCORDER_QUALITY_TIME_LAPSE_2k},
+
+    // Vendor-specific profiles
 };
 
 #if LOG_NDEBUG
diff --git a/media/libmedia/include/media/MediaProfiles.h b/media/libmedia/include/media/MediaProfiles.h
index 4cc5b95..7f0b99d 100644
--- a/media/libmedia/include/media/MediaProfiles.h
+++ b/media/libmedia/include/media/MediaProfiles.h
@@ -37,8 +37,9 @@
     CAMCORDER_QUALITY_VGA = 9,
     CAMCORDER_QUALITY_4KDCI = 10,
     CAMCORDER_QUALITY_QHD = 11,
-    CAMCORDER_QUALITY_2k = 12,
-    CAMCORDER_QUALITY_LIST_END = 12,
+    CAMCORDER_QUALITY_2K = 12,
+    CAMCORDER_QUALITY_8KUHD = 13,
+    CAMCORDER_QUALITY_LIST_END = 13,
 
     CAMCORDER_QUALITY_TIME_LAPSE_LIST_START = 1000,
     CAMCORDER_QUALITY_TIME_LAPSE_LOW  = 1000,
@@ -53,8 +54,9 @@
     CAMCORDER_QUALITY_TIME_LAPSE_VGA = 1009,
     CAMCORDER_QUALITY_TIME_LAPSE_4KDCI = 1010,
     CAMCORDER_QUALITY_TIME_LAPSE_QHD = 1011,
-    CAMCORDER_QUALITY_TIME_LAPSE_2k = 1012,
-    CAMCORDER_QUALITY_TIME_LAPSE_LIST_END = 1012,
+    CAMCORDER_QUALITY_TIME_LAPSE_2K = 1012,
+    CAMCORDER_QUALITY_TIME_LAPSE_8KUHD = 1013,
+    CAMCORDER_QUALITY_TIME_LAPSE_LIST_END = 1013,
 
     CAMCORDER_QUALITY_HIGH_SPEED_LIST_START = 2000,
     CAMCORDER_QUALITY_HIGH_SPEED_LOW  = 2000,
diff --git a/media/libmediaplayerservice/Android.bp b/media/libmediaplayerservice/Android.bp
index b62317a..ab6863f 100644
--- a/media/libmediaplayerservice/Android.bp
+++ b/media/libmediaplayerservice/Android.bp
@@ -15,7 +15,7 @@
     shared_libs: [
         "android.hardware.media.c2@1.0",
         "android.hardware.media.omx@1.0",
-        "av-types-aidl-unstable-cpp",
+        "av-types-aidl-cpp",
         "libbase",
         "libandroid_net",
         "libaudioclient",
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index 4d90d98..1d5ccca 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -2246,6 +2246,12 @@
                       mRecycledTrack->frameCount(), t->frameCount());
                 reuse = false;
             }
+            // If recycled and new tracks are not on the same output,
+            // don't reuse the recycled one.
+            if (mRecycledTrack->getOutput() != t->getOutput()) {
+                ALOGV("output has changed, don't reuse track");
+                reuse = false;
+            }
         }
 
         if (reuse) {
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index b2f1b9b..aca4369 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -100,6 +100,7 @@
         virtual audio_session_t getSessionId() const;
         virtual uint32_t        getSampleRate() const;
         virtual int64_t         getBufferDurationInUs() const;
+        virtual audio_output_flags_t getFlags() const { return mFlags; }
 
         virtual status_t        open(
                 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
diff --git a/media/libmediaplayerservice/include/MediaPlayerInterface.h b/media/libmediaplayerservice/include/MediaPlayerInterface.h
index 8d94698..1cbd8a0 100644
--- a/media/libmediaplayerservice/include/MediaPlayerInterface.h
+++ b/media/libmediaplayerservice/include/MediaPlayerInterface.h
@@ -108,6 +108,7 @@
         virtual audio_stream_type_t getAudioStreamType() const = 0;
         virtual uint32_t    getSampleRate() const = 0;
         virtual int64_t     getBufferDurationInUs() const = 0;
+        virtual audio_output_flags_t getFlags() const = 0;
 
         // If no callback is specified, use the "write" API below to submit
         // audio data.
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index 47362ef..344ee0b 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -871,10 +871,12 @@
             readFromAMessage(msg, &rate);
             status_t err = OK;
             if (mRenderer != NULL) {
-                // AudioSink allows only 1.f and 0.f for offload mode.
-                // For other speed, switch to non-offload mode.
-                if (mOffloadAudio && ((rate.mSpeed != 0.f && rate.mSpeed != 1.f)
-                        || rate.mPitch != 1.f)) {
+                // AudioSink allows only 1.f and 0.f for offload and direct modes.
+                // For other speeds, restart audio to fallback to supported paths
+                bool audioDirectOutput = (mAudioSink->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0;
+                if ((mOffloadAudio || audioDirectOutput) &&
+                        ((rate.mSpeed != 0.f && rate.mSpeed != 1.f) || rate.mPitch != 1.f)) {
+
                     int64_t currentPositionUs;
                     if (getCurrentPosition(&currentPositionUs) != OK) {
                         currentPositionUs = mPreviousSeekTimeUs;
diff --git a/media/libmediatranscoding/Android.bp b/media/libmediatranscoding/Android.bp
index 23e83f9..e98b7ea 100644
--- a/media/libmediatranscoding/Android.bp
+++ b/media/libmediatranscoding/Android.bp
@@ -96,7 +96,7 @@
 
     static_libs: [
         "mediatranscoding_aidl_interface-ndk_platform",
-        "resourceobserver_aidl_interface-ndk_platform",
+        "resourceobserver_aidl_interface-V1-ndk_platform",
     ],
 
     cflags: [
diff --git a/media/libshmem/Android.bp b/media/libshmem/Android.bp
index 62784ed..c715918 100644
--- a/media/libshmem/Android.bp
+++ b/media/libshmem/Android.bp
@@ -21,12 +21,12 @@
         "libbinder",
         "libshmemutil",
         "libutils",
-        "shared-file-region-aidl-unstable-cpp",
+        "shared-file-region-aidl-cpp",
     ],
     export_shared_lib_headers: [
         "libbinder",
         "libutils",
-        "shared-file-region-aidl-unstable-cpp",
+        "shared-file-region-aidl-cpp",
     ],
     target: {
         darwin: {
@@ -43,10 +43,10 @@
     vendor_available: true,
     double_loadable: true,
     shared_libs: [
-        "shared-file-region-aidl-unstable-cpp",
+        "shared-file-region-aidl-cpp",
     ],
     export_shared_lib_headers: [
-        "shared-file-region-aidl-unstable-cpp",
+        "shared-file-region-aidl-cpp",
     ],
     target: {
         darwin: {
@@ -64,7 +64,7 @@
         "libshmemcompat",
         "libshmemutil",
         "libutils",
-        "shared-file-region-aidl-unstable-cpp",
+        "shared-file-region-aidl-cpp",
     ],
     test_suites: ["device-tests"],
 }
diff --git a/media/libstagefright/foundation/ABuffer.cpp b/media/libstagefright/foundation/ABuffer.cpp
index c8965d9..c79384c 100644
--- a/media/libstagefright/foundation/ABuffer.cpp
+++ b/media/libstagefright/foundation/ABuffer.cpp
@@ -67,7 +67,7 @@
 
 void ABuffer::setRange(size_t offset, size_t size) {
     CHECK_LE(offset, mCapacity);
-    CHECK_LE(offset + size, mCapacity);
+    CHECK_LE(size, mCapacity - offset);
 
     mRangeOffset = offset;
     mRangeLength = size;
diff --git a/media/libstagefright/renderfright/Android.bp b/media/libstagefright/renderfright/Android.bp
index c17f84e..7a71f52 100644
--- a/media/libstagefright/renderfright/Android.bp
+++ b/media/libstagefright/renderfright/Android.bp
@@ -23,7 +23,6 @@
         "libEGL",
         "libGLESv1_CM",
         "libGLESv2",
-        "libgui",
         "liblog",
         "libnativewindow",
         "libprocessgroup",
diff --git a/media/libstagefright/renderfright/RenderEngine.cpp b/media/libstagefright/renderfright/RenderEngine.cpp
index c3fbb60..e96ffdb 100644
--- a/media/libstagefright/renderfright/RenderEngine.cpp
+++ b/media/libstagefright/renderfright/RenderEngine.cpp
@@ -18,7 +18,6 @@
 
 #include <cutils/properties.h>
 #include <log/log.h>
-#include <private/gui/SyncFeatures.h>
 #include "gl/GLESRenderEngine.h"
 #include "threaded/RenderEngineThreaded.h"
 
@@ -52,6 +51,39 @@
 
 RenderEngine::~RenderEngine() = default;
 
+// static
+SyncFeatures &SyncFeatures::GetInstance() {
+    static SyncFeatures syncFeatures;
+    return syncFeatures;
+}
+
+bool SyncFeatures::useNativeFenceSync() const { return mHasNativeFenceSync; }
+bool SyncFeatures::useFenceSync() const { return mHasFenceSync; }
+bool SyncFeatures::useWaitSync() const { return mHasWaitSync; }
+
+SyncFeatures::SyncFeatures()
+    : mHasNativeFenceSync(false),
+      mHasFenceSync(false),
+      mHasWaitSync(false) {
+    EGLDisplay dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
+    // This can only be called after EGL has been initialized; otherwise the
+    // check below will abort.
+    const char* exts = eglQueryString(dpy, EGL_EXTENSIONS);
+    LOG_ALWAYS_FATAL_IF(exts == nullptr, "eglQueryString failed");
+    if (strstr(exts, "EGL_ANDROID_native_fence_sync")) {
+        // This makes GLConsumer use the EGL_ANDROID_native_fence_sync
+        // extension to create Android native fences to signal when all
+        // GLES reads for a given buffer have completed.
+        mHasNativeFenceSync = true;
+    }
+    if (strstr(exts, "EGL_KHR_fence_sync")) {
+        mHasFenceSync = true;
+    }
+    if (strstr(exts, "EGL_KHR_wait_sync")) {
+        mHasWaitSync = true;
+    }
+}
+
 namespace impl {
 
 RenderEngine::RenderEngine(const RenderEngineCreationArgs& args) : mArgs(args) {}
@@ -59,11 +91,11 @@
 RenderEngine::~RenderEngine() = default;
 
 bool RenderEngine::useNativeFenceSync() const {
-    return SyncFeatures::getInstance().useNativeFenceSync();
+    return SyncFeatures::GetInstance().useNativeFenceSync();
 }
 
 bool RenderEngine::useWaitSync() const {
-    return SyncFeatures::getInstance().useWaitSync();
+    return SyncFeatures::GetInstance().useWaitSync();
 }
 
 } // namespace impl
diff --git a/media/libstagefright/renderfright/gl/GLESRenderEngine.cpp b/media/libstagefright/renderfright/gl/GLESRenderEngine.cpp
index 824bdd9..b7f8cb4 100644
--- a/media/libstagefright/renderfright/gl/GLESRenderEngine.cpp
+++ b/media/libstagefright/renderfright/gl/GLESRenderEngine.cpp
@@ -30,7 +30,6 @@
 #include <android-base/stringprintf.h>
 #include <cutils/compiler.h>
 #include <cutils/properties.h>
-#include <gui/DebugEGLImageTracker.h>
 #include <renderengine/Mesh.h>
 #include <renderengine/Texture.h>
 #include <renderengine/private/Description.h>
@@ -436,7 +435,6 @@
         EGLImageKHR expired = mFramebufferImageCache.front().second;
         mFramebufferImageCache.pop_front();
         eglDestroyImageKHR(mEGLDisplay, expired);
-        DEBUG_EGL_IMAGE_TRACKER_DESTROY();
     }
     eglDestroyImageKHR(mEGLDisplay, mPlaceholderImage);
     mImageCache.clear();
@@ -1012,15 +1010,11 @@
                 EGLImageKHR expired = mFramebufferImageCache.front().second;
                 mFramebufferImageCache.pop_front();
                 eglDestroyImageKHR(mEGLDisplay, expired);
-                DEBUG_EGL_IMAGE_TRACKER_DESTROY();
             }
             mFramebufferImageCache.push_back({graphicBuffer->getId(), image});
         }
     }
 
-    if (image != EGL_NO_IMAGE_KHR) {
-        DEBUG_EGL_IMAGE_TRACKER_CREATE();
-    }
     return image;
 }
 
diff --git a/media/libstagefright/renderfright/gl/GLFramebuffer.cpp b/media/libstagefright/renderfright/gl/GLFramebuffer.cpp
index 383486b..d6582b3 100644
--- a/media/libstagefright/renderfright/gl/GLFramebuffer.cpp
+++ b/media/libstagefright/renderfright/gl/GLFramebuffer.cpp
@@ -22,7 +22,6 @@
 #include <GLES/glext.h>
 #include <GLES2/gl2ext.h>
 #include <GLES3/gl3.h>
-#include <gui/DebugEGLImageTracker.h>
 #include <nativebase/nativebase.h>
 #include <utils/Trace.h>
 #include "GLESRenderEngine.h"
@@ -48,7 +47,6 @@
     if (mEGLImage != EGL_NO_IMAGE_KHR) {
         if (!usingFramebufferCache) {
             eglDestroyImageKHR(mEGLDisplay, mEGLImage);
-            DEBUG_EGL_IMAGE_TRACKER_DESTROY();
         }
         mEGLImage = EGL_NO_IMAGE_KHR;
         mBufferWidth = 0;
diff --git a/media/libstagefright/renderfright/gl/GLImage.cpp b/media/libstagefright/renderfright/gl/GLImage.cpp
index 8497721..77e648e 100644
--- a/media/libstagefright/renderfright/gl/GLImage.cpp
+++ b/media/libstagefright/renderfright/gl/GLImage.cpp
@@ -20,7 +20,6 @@
 
 #include <vector>
 
-#include <gui/DebugEGLImageTracker.h>
 #include <log/log.h>
 #include <utils/Trace.h>
 #include "GLESRenderEngine.h"
@@ -59,7 +58,6 @@
         if (!eglDestroyImageKHR(mEGLDisplay, mEGLImage)) {
             ALOGE("failed to destroy image: %#x", eglGetError());
         }
-        DEBUG_EGL_IMAGE_TRACKER_DESTROY();
         mEGLImage = EGL_NO_IMAGE_KHR;
     }
 
@@ -71,7 +69,6 @@
             ALOGE("failed to create EGLImage: %#x", eglGetError());
             return false;
         }
-        DEBUG_EGL_IMAGE_TRACKER_CREATE();
         mProtected = isProtected;
     }
 
diff --git a/media/libstagefright/renderfright/include/renderengine/RenderEngine.h b/media/libstagefright/renderfright/include/renderengine/RenderEngine.h
index 40fdff4..af2870f 100644
--- a/media/libstagefright/renderfright/include/renderengine/RenderEngine.h
+++ b/media/libstagefright/renderfright/include/renderengine/RenderEngine.h
@@ -302,6 +302,20 @@
     status_t mStatus;
 };
 
+class SyncFeatures {
+public:
+    static SyncFeatures &GetInstance();
+    bool useNativeFenceSync() const;
+    bool useFenceSync() const;
+    bool useWaitSync() const;
+
+private:
+    SyncFeatures();
+    bool mHasNativeFenceSync;
+    bool mHasFenceSync;
+    bool mHasWaitSync;
+};
+
 namespace impl {
 
 // impl::RenderEngine contains common implementation that is graphics back-end agnostic.
diff --git a/media/libstagefright/renderfright/threaded/RenderEngineThreaded.cpp b/media/libstagefright/renderfright/threaded/RenderEngineThreaded.cpp
index d4184fd..222d3ee 100644
--- a/media/libstagefright/renderfright/threaded/RenderEngineThreaded.cpp
+++ b/media/libstagefright/renderfright/threaded/RenderEngineThreaded.cpp
@@ -23,7 +23,6 @@
 #include <future>
 
 #include <android-base/stringprintf.h>
-#include <private/gui/SyncFeatures.h>
 #include <utils/Trace.h>
 
 #include "gl/GLESRenderEngine.h"
@@ -123,7 +122,7 @@
         std::lock_guard lock(mThreadMutex);
         mFunctionCalls.push([&resultPromise](renderengine::RenderEngine& /*instance*/) {
             ATRACE_NAME("REThreaded::useNativeFenceSync");
-            bool returnValue = SyncFeatures::getInstance().useNativeFenceSync();
+            bool returnValue = SyncFeatures::GetInstance().useNativeFenceSync();
             resultPromise.set_value(returnValue);
         });
     }
@@ -138,7 +137,7 @@
         std::lock_guard lock(mThreadMutex);
         mFunctionCalls.push([&resultPromise](renderengine::RenderEngine& /*instance*/) {
             ATRACE_NAME("REThreaded::useWaitSync");
-            bool returnValue = SyncFeatures::getInstance().useWaitSync();
+            bool returnValue = SyncFeatures::GetInstance().useWaitSync();
             resultPromise.set_value(returnValue);
         });
     }
diff --git a/media/libstagefright/rtsp/AAVCAssembler.cpp b/media/libstagefright/rtsp/AAVCAssembler.cpp
index cccb63a..72a377d 100644
--- a/media/libstagefright/rtsp/AAVCAssembler.cpp
+++ b/media/libstagefright/rtsp/AAVCAssembler.cpp
@@ -28,6 +28,8 @@
 #include <media/stagefright/foundation/avc_utils.h>
 #include <media/stagefright/foundation/hexdump.h>
 
+#include <android-base/properties.h>
+
 #include <stdint.h>
 
 namespace android {
@@ -513,7 +515,11 @@
 void AAVCAssembler::submitAccessUnit() {
     CHECK(!mNALUnits.empty());
 
-    ALOGV("Access unit complete (%zu nal units)", mNALUnits.size());
+    if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
+        ALOGD("Access unit complete (%zu nal units)", mNALUnits.size());
+    } else {
+        ALOGV("Access unit complete (%zu nal units)", mNALUnits.size());
+    }
 
     size_t totalSize = 0;
     for (List<sp<ABuffer> >::iterator it = mNALUnits.begin();
diff --git a/media/libstagefright/tests/Android.bp b/media/libstagefright/tests/Android.bp
index 5f3f72c..4a505d4 100644
--- a/media/libstagefright/tests/Android.bp
+++ b/media/libstagefright/tests/Android.bp
@@ -9,7 +9,6 @@
         "libmedia",
         "libstagefright",
         "libstagefright_foundation",
-        "libstagefright_omx",
         "libutils",
         "liblog",
     ],
@@ -17,11 +16,8 @@
     include_dirs: [
         "frameworks/av/media/libstagefright",
         "frameworks/av/media/libstagefright/include",
-        "frameworks/native/include/media/openmax",
     ],
 
-    compile_multilib: "prefer32",
-
     cflags: [
         "-Werror",
         "-Wall",
diff --git a/media/mtp/MtpServer.cpp b/media/mtp/MtpServer.cpp
index a92848c..becbe6e 100644
--- a/media/mtp/MtpServer.cpp
+++ b/media/mtp/MtpServer.cpp
@@ -793,7 +793,7 @@
     mtp_file_range mfr;
     struct stat sstat;
     uint64_t finalsize;
-    bool transcode = android::base::GetBoolProperty("sys.fuse.transcode_mtp", true);
+    bool transcode = android::base::GetBoolProperty("sys.fuse.transcode_mtp", false);
     ALOGD("Mtp transcode = %d", transcode);
     mfr.fd = mDatabase->openFilePath(filePath, transcode);
     // Doing this here because we want to update fileLength only for this case and leave the
diff --git a/media/ndk/include/media/NdkImage.h b/media/ndk/include/media/NdkImage.h
index 62b8624..e19dd3a 100644
--- a/media/ndk/include/media/NdkImage.h
+++ b/media/ndk/include/media/NdkImage.h
@@ -559,8 +559,6 @@
     int32_t bottom;
 } AImageCropRect;
 
-#if __ANDROID_API__ >= 24
-
 /**
  * Return the image back the the system and delete the AImage object from memory.
  *
@@ -777,10 +775,6 @@
         const AImage* image, int planeIdx,
         /*out*/uint8_t** data, /*out*/int* dataLength) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 26
-
 /**
  * Return the image back the the system and delete the AImage object from memory asynchronously.
  *
@@ -829,8 +823,6 @@
  */
 media_status_t AImage_getHardwareBuffer(const AImage* image, /*out*/AHardwareBuffer** buffer) __INTRODUCED_IN(26);
 
-#endif /* __ANDROID_API__ >= 26 */
-
 __END_DECLS
 
 #endif //_NDK_IMAGE_H
diff --git a/media/ndk/include/media/NdkImageReader.h b/media/ndk/include/media/NdkImageReader.h
index 600ffc9..d86f3c7 100644
--- a/media/ndk/include/media/NdkImageReader.h
+++ b/media/ndk/include/media/NdkImageReader.h
@@ -53,8 +53,6 @@
  */
 typedef struct AImageReader AImageReader;
 
-#if __ANDROID_API__ >= 24
-
 /**
  * Create a new reader for images of the desired size and format.
  *
@@ -320,10 +318,6 @@
 media_status_t AImageReader_setImageListener(
         AImageReader* reader, AImageReader_ImageListener* listener) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 26
-
 /**
  * AImageReader constructor similar to {@link AImageReader_new} that takes an additional parameter
  * for the consumer usage. All other parameters and the return values are identical to those passed
@@ -510,8 +504,6 @@
     AImageReader *reader, /* out */native_handle_t **handle);
 #endif
 
-#endif /* __ANDROID_API__ >= 26 */
-
 __END_DECLS
 
 #endif //_NDK_IMAGE_READER_H
diff --git a/media/ndk/include/media/NdkMediaCodec.h b/media/ndk/include/media/NdkMediaCodec.h
index 1f9904a..519148e 100644
--- a/media/ndk/include/media/NdkMediaCodec.h
+++ b/media/ndk/include/media/NdkMediaCodec.h
@@ -121,8 +121,6 @@
       AMediaCodecOnAsyncError           onAsyncError;
 } AMediaCodecOnAsyncNotifyCallback;
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Create codec by name. Use this if you know the exact codec you want to use.
  * When configuring, you will need to specify whether to use the codec as an
@@ -311,8 +309,6 @@
 media_status_t AMediaCodec_releaseOutputBufferAtTime(
         AMediaCodec *mData, size_t idx, int64_t timestampNs) __INTRODUCED_IN(21);
 
-#if __ANDROID_API__ >= 26
-
 /**
  * Creates a Surface that can be used as the input to encoder, in place of input buffers
  *
@@ -393,10 +389,6 @@
  */
 media_status_t AMediaCodec_signalEndOfInputStream(AMediaCodec *mData) __INTRODUCED_IN(26);
 
-#endif /* __ANDROID_API__ >= 26 */
-
-#if __ANDROID_API__ >= 28
-
 /**
  * Get format of the buffer. The specified buffer index must have been previously obtained from
  * dequeueOutputBuffer.
@@ -482,8 +474,6 @@
  */
 bool AMediaCodecActionCode_isTransient(int32_t actionCode) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
 typedef enum {
     AMEDIACODECRYPTOINFO_MODE_CLEAR = 0,
     AMEDIACODECRYPTOINFO_MODE_AES_CTR = 1,
@@ -580,9 +570,6 @@
  */
 media_status_t AMediaCodecCryptoInfo_getEncryptedBytes(AMediaCodecCryptoInfo*, size_t *dst) __INTRODUCED_IN(21);
 
-#endif /* __ANDROID_API__ >= 21 */
-
-#if __ANDROID_API__ >= 31
 extern const char* AMEDIACODEC_KEY_HDR10_PLUS_INFO __INTRODUCED_IN(31);
 extern const char* AMEDIACODEC_KEY_LOW_LATENCY __INTRODUCED_IN(31);
 extern const char* AMEDIACODEC_KEY_OFFSET_TIME __INTRODUCED_IN(31);
@@ -590,7 +577,6 @@
 extern const char* AMEDIACODEC_KEY_SUSPEND __INTRODUCED_IN(31);
 extern const char* AMEDIACODEC_KEY_SUSPEND_TIME __INTRODUCED_IN(31);
 extern const char* AMEDIACODEC_KEY_VIDEO_BITRATE __INTRODUCED_IN(31);
-#endif /* __ANDROID_API__ >= 31 */
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaCrypto.h b/media/ndk/include/media/NdkMediaCrypto.h
index 3fa07c7..590d51d 100644
--- a/media/ndk/include/media/NdkMediaCrypto.h
+++ b/media/ndk/include/media/NdkMediaCrypto.h
@@ -47,8 +47,6 @@
 
 typedef uint8_t AMediaUUID[16];
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Available since API level 21.
  */
@@ -69,8 +67,6 @@
  */
 void AMediaCrypto_delete(AMediaCrypto* crypto) __INTRODUCED_IN(21);
 
-#endif /* __ANDROID_API__ >= 21 */
-
 __END_DECLS
 
 #endif // _NDK_MEDIA_CRYPTO_H
diff --git a/media/ndk/include/media/NdkMediaDataSource.h b/media/ndk/include/media/NdkMediaDataSource.h
index 0577df2..4158a97 100644
--- a/media/ndk/include/media/NdkMediaDataSource.h
+++ b/media/ndk/include/media/NdkMediaDataSource.h
@@ -38,8 +38,6 @@
 struct AMediaDataSource;
 typedef struct AMediaDataSource AMediaDataSource;
 
-#if __ANDROID_API__ >= 28
-
 /*
  * AMediaDataSource's callbacks will be invoked on an implementation-defined thread
  * or thread pool. No guarantees are provided about which thread(s) will be used for
@@ -93,8 +91,6 @@
  */
 AMediaDataSource* AMediaDataSource_new() __INTRODUCED_IN(28);
 
-#if __ANDROID_API__ >= 29
-
 /**
  * Called to get an estimate of the number of bytes that can be read from this data source
  * starting at |offset| without blocking for I/O.
@@ -124,8 +120,6 @@
         int numheaders,
         const char * const *key_values) __INTRODUCED_IN(29);
 
-#endif  /*__ANDROID_API__ >= 29 */
-
 /**
  * Delete a previously created media data source.
  *
@@ -185,10 +179,6 @@
         AMediaDataSource*,
         AMediaDataSourceClose) __INTRODUCED_IN(28);
 
-#endif  /*__ANDROID_API__ >= 28 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Close the data source, unblock reads, and release associated resources.
  *
@@ -213,8 +203,6 @@
         AMediaDataSource*,
         AMediaDataSourceGetAvailableSize) __INTRODUCED_IN(29);
 
-#endif  /*__ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif // _NDK_MEDIA_DATASOURCE_H
diff --git a/media/ndk/include/media/NdkMediaDrm.h b/media/ndk/include/media/NdkMediaDrm.h
index 31f5c7d..849a8f9 100644
--- a/media/ndk/include/media/NdkMediaDrm.h
+++ b/media/ndk/include/media/NdkMediaDrm.h
@@ -165,8 +165,6 @@
         const AMediaDrmSessionId *sessionId, const AMediaDrmKeyStatus *keyStatus,
         size_t numKeys, bool hasNewUsableKey);
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Query if the given scheme identified by its UUID is supported on this device, and
  * whether the drm plugin is able to handle the media container format specified by mimeType.
@@ -576,8 +574,6 @@
         const char *macAlgorithm, uint8_t *keyId, const uint8_t *message, size_t messageSize,
         const uint8_t *signature, size_t signatureSize) __INTRODUCED_IN(21);
 
-#endif /* __ANDROID_API__ >= 21 */
-
 __END_DECLS
 
 #endif //_NDK_MEDIA_DRM_H
diff --git a/media/ndk/include/media/NdkMediaExtractor.h b/media/ndk/include/media/NdkMediaExtractor.h
index a1cd9e3..e429820 100644
--- a/media/ndk/include/media/NdkMediaExtractor.h
+++ b/media/ndk/include/media/NdkMediaExtractor.h
@@ -50,8 +50,6 @@
 struct AMediaExtractor;
 typedef struct AMediaExtractor AMediaExtractor;
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Create new media extractor.
  *
@@ -82,8 +80,6 @@
 media_status_t AMediaExtractor_setDataSource(AMediaExtractor*,
         const char *location) __INTRODUCED_IN(21);
 
-#if __ANDROID_API__ >= 28
-
 /**
  * Set the custom data source implementation from which the extractor will read.
  *
@@ -92,8 +88,6 @@
 media_status_t AMediaExtractor_setDataSourceCustom(AMediaExtractor*,
         AMediaDataSource *src) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
 /**
  * Return the number of tracks in the previously specified media file
  *
@@ -211,8 +205,6 @@
     AMEDIAEXTRACTOR_SAMPLE_FLAG_ENCRYPTED = 2,
 };
 
-#if __ANDROID_API__ >= 28
-
 /**
  * Returns the format of the extractor. The caller must free the returned format
  * using AMediaFormat_delete(format).
@@ -266,10 +258,6 @@
 media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex,
         AMediaFormat *fmt) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
-#endif /* __ANDROID_API__ >= 21 */
-
 __END_DECLS
 
 #endif // _NDK_MEDIA_EXTRACTOR_H
diff --git a/media/ndk/include/media/NdkMediaFormat.h b/media/ndk/include/media/NdkMediaFormat.h
index 18092f0..4d0eba5 100644
--- a/media/ndk/include/media/NdkMediaFormat.h
+++ b/media/ndk/include/media/NdkMediaFormat.h
@@ -61,8 +61,6 @@
 struct AMediaFormat;
 typedef struct AMediaFormat AMediaFormat;
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Available since API level 21.
  */
@@ -205,9 +203,7 @@
 extern const char* AMEDIAFORMAT_KEY_TRACK_ID __INTRODUCED_IN(28);
 extern const char* AMEDIAFORMAT_KEY_TRACK_INDEX __INTRODUCED_IN(28);
 extern const char* AMEDIAFORMAT_KEY_WIDTH __INTRODUCED_IN(21);
-#endif /* __ANDROID_API__ >= 21 */
 
-#if __ANDROID_API__ >= 28
 /**
  * Available since API level 28.
  */
@@ -231,9 +227,7 @@
  */
 void AMediaFormat_setRect(AMediaFormat*, const char* name,
         int32_t left, int32_t top, int32_t right, int32_t bottom) __INTRODUCED_IN(28);
-#endif /* __ANDROID_API__ >= 28 */
 
-#if __ANDROID_API__ >= 29
 /**
  * Remove all key/value pairs from the given AMediaFormat.
  *
@@ -307,9 +301,6 @@
 extern const char* AMEDIAFORMAT_KEY_VALID_SAMPLES __INTRODUCED_IN(29);
 extern const char* AMEDIAFORMAT_KEY_YEAR __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
-#if __ANDROID_API__ >= 30
 /**
  * An optional key describing the low latency decoding mode. This is an optional parameter
  * that applies only to decoders. If enabled, the decoder doesn't hold input and output
@@ -320,15 +311,12 @@
  * Available since API level 30.
  */
 extern const char* AMEDIAFORMAT_KEY_LOW_LATENCY __INTRODUCED_IN(30);
-#endif /* __ANDROID_API__ >= 30 */
 
-#if __ANDROID_API__ >= 31
 extern const char* AMEDIAFORMAT_KEY_HDR10_PLUS_INFO __INTRODUCED_IN(31);
 extern const char* AMEDIAFORMAT_KEY_SLOW_MOTION_MARKERS __INTRODUCED_IN(31);
 extern const char* AMEDIAFORMAT_KEY_THUMBNAIL_CSD_AV1C __INTRODUCED_IN(31);
 extern const char* AMEDIAFORMAT_KEY_XMP_OFFSET __INTRODUCED_IN(31);
 extern const char* AMEDIAFORMAT_KEY_XMP_SIZE __INTRODUCED_IN(31);
-#endif /* __ANDROID_API__ >= 31 */
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaMuxer.h b/media/ndk/include/media/NdkMediaMuxer.h
index 9de3fbf..519e249 100644
--- a/media/ndk/include/media/NdkMediaMuxer.h
+++ b/media/ndk/include/media/NdkMediaMuxer.h
@@ -54,8 +54,6 @@
     AMEDIAMUXER_OUTPUT_FORMAT_THREE_GPP   = 2,
 } OutputFormat;
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Create new media muxer.
  *
@@ -140,8 +138,6 @@
         size_t trackIdx, const uint8_t *data,
         const AMediaCodecBufferInfo *info) __INTRODUCED_IN(21);
 
-#endif /* __ANDROID_API__ >= 21 */
-
 __END_DECLS
 
 #endif // _NDK_MEDIA_MUXER_H
diff --git a/services/audioflinger/Android.bp b/services/audioflinger/Android.bp
index a005250..09d3871 100644
--- a/services/audioflinger/Android.bp
+++ b/services/audioflinger/Android.bp
@@ -35,10 +35,10 @@
     ],
 
     shared_libs: [
-        "audioflinger-aidl-unstable-cpp",
-        "audioclient-types-aidl-unstable-cpp",
-        "av-types-aidl-unstable-cpp",
-        "effect-aidl-unstable-cpp",
+        "audioflinger-aidl-cpp",
+        "audioclient-types-aidl-cpp",
+        "av-types-aidl-cpp",
+        "effect-aidl-cpp",
         "libaudioclient_aidl_conversion",
         "libaudiofoundation",
         "libaudiohal",
diff --git a/services/audiopolicy/AudioPolicyInterface.h b/services/audiopolicy/AudioPolicyInterface.h
index 630c423..7c0f2ce 100644
--- a/services/audiopolicy/AudioPolicyInterface.h
+++ b/services/audiopolicy/AudioPolicyInterface.h
@@ -450,9 +450,11 @@
     virtual status_t getAudioPort(struct audio_port_v7 *port) = 0;
 };
 
-extern "C" AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface);
-extern "C" void destroyAudioPolicyManager(AudioPolicyInterface *interface);
-
+    // These are the signatures of createAudioPolicyManager/destroyAudioPolicyManager
+    // methods respectively, expected by AudioPolicyService, needs to be exposed by
+    // libaudiopolicymanagercustom.
+    using CreateAudioPolicyManagerInstance = AudioPolicyInterface* (*)(AudioPolicyClientInterface*);
+    using DestroyAudioPolicyManagerInstance = void (*)(AudioPolicyInterface*);
 
 } // namespace android
 
diff --git a/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h
index 82cd6cf..05ec69e 100644
--- a/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h
+++ b/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h
@@ -278,6 +278,8 @@
 
     void dump(String8 *dst, const String8 &tag, int spaces = 0, bool verbose = true) const;
 
+protected:
+    int     do_compare(const void* lhs, const void* rhs) const;
 private:
     void refreshTypes();
     void refreshAudioProfiles();
diff --git a/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp
index 3cfceba..a92d31e 100644
--- a/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp
@@ -279,6 +279,23 @@
     return ret;
 }
 
+int DeviceVector::do_compare(const void* lhs, const void* rhs) const {
+    const auto ldevice = *reinterpret_cast<const sp<DeviceDescriptor>*>(lhs);
+    const auto rdevice = *reinterpret_cast<const sp<DeviceDescriptor>*>(rhs);
+    int ret = 0;
+
+    // sort by type.
+    ret = compare_type(ldevice->type(), rdevice->type());
+    if (ret != 0)
+        return ret;
+    // for same type higher priority for latest device.
+    ret = compare_type(rdevice->getId(), ldevice->getId());
+    if (ret != 0)
+        return ret;
+    // fallback to default sort using pointer address
+    return SortedVector::do_compare(lhs, rhs);
+}
+
 ssize_t DeviceVector::remove(const sp<DeviceDescriptor>& item)
 {
     ssize_t ret = indexOf(item);
diff --git a/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp b/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp
index 0cc3a68..129f6f6 100644
--- a/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp
@@ -39,6 +39,7 @@
 // TODO(mnaganov): Consider finding an alternative for using HIDL code.
 using hardware::Return;
 using hardware::Status;
+using hardware::Void;
 using utilities::convertTo;
 
 template<typename E, typename C>
@@ -89,7 +90,6 @@
 
     };
 
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
     // No children
 };
 
@@ -106,8 +106,6 @@
         static constexpr const char *format = "format";
         static constexpr const char *channelMasks = "channelMasks";
     };
-
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
 };
 
 struct MixPortTraits : public AndroidCollectionTraits<IOProfile, IOProfileCollection>
@@ -125,7 +123,6 @@
         static constexpr const char *maxActiveCount = "maxActiveCount";
     };
 
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
     // Children: GainTraits
 };
 
@@ -147,7 +144,6 @@
         static constexpr const char *encodedFormats = "encodedFormats";
     };
 
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
     // Children: GainTraits (optional)
 };
 
@@ -166,8 +162,6 @@
     };
 
     typedef HwModule *PtrSerializingCtx;
-
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
 };
 
 struct ModuleTraits : public AndroidCollectionTraits<HwModule, HwModuleCollection>
@@ -187,13 +181,14 @@
 
     typedef AudioPolicyConfig *PtrSerializingCtx;
 
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
     // Children: mixPortTraits, devicePortTraits, and routeTraits
     // Need to call deserialize on each child
 };
 
 struct GlobalConfigTraits
 {
+    typedef void Element;
+
     static constexpr const char *tag = "globalConfiguration";
 
     struct Attributes
@@ -203,14 +198,16 @@
         static constexpr const char *engineLibrarySuffix = "engine_library";
     };
 
-    static status_t deserialize(const xmlNode *root, AudioPolicyConfig *config);
+    typedef AudioPolicyConfig *PtrSerializingCtx;
 };
 
 struct SurroundSoundTraits
 {
+    typedef void Element;
+
     static constexpr const char *tag = "surroundSound";
 
-    static status_t deserialize(const xmlNode *root, AudioPolicyConfig *config);
+    typedef AudioPolicyConfig *PtrSerializingCtx;
     // Children: SurroundSoundFormatTraits
 };
 
@@ -224,28 +221,30 @@
         static constexpr const char *name = "name";
         static constexpr const char *subformats = "subformats";
     };
-
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
 };
 
 class PolicySerializer
 {
 public:
-    PolicySerializer() : mVersion{std::to_string(gMajor) + "." + std::to_string(gMinor)}
-    {
-        ALOGV("%s: Version=%s Root=%s", __func__, mVersion.c_str(), rootName);
-    }
     status_t deserialize(const char *configFile, AudioPolicyConfig *config);
 
+    template <class Trait>
+    status_t deserializeCollection(const xmlNode *cur,
+            typename Trait::Collection *collection,
+            typename Trait::PtrSerializingCtx serializingContext);
+    template <class Trait>
+    Return<typename Trait::Element> deserialize(const xmlNode *cur,
+            typename Trait::PtrSerializingCtx serializingContext);
+
 private:
     static constexpr const char *rootName = "audioPolicyConfiguration";
     static constexpr const char *versionAttribute = "version";
-    static constexpr uint32_t gMajor = 1; /**< the major number of the policy xml format version. */
-    static constexpr uint32_t gMinor = 0; /**< the minor number of the policy xml format version. */
 
     typedef AudioPolicyConfig Element;
 
-    const std::string mVersion;
+    std::string mChannelMasksSeparator = ",";
+    std::string mSamplingRatesSeparator = ",";
+    std::string mFlagsSeparator = "|";
 
     // Children: ModulesTraits, VolumeTraits, SurroundSoundTraits (optional)
 };
@@ -295,7 +294,7 @@
 }
 
 template <class Trait>
-status_t deserializeCollection(const xmlNode *cur,
+status_t PolicySerializer::deserializeCollection(const xmlNode *cur,
         typename Trait::Collection *collection,
         typename Trait::PtrSerializingCtx serializingContext)
 {
@@ -308,7 +307,7 @@
         }
         for (; child != NULL; child = child->next) {
             if (!xmlStrcmp(child->name, reinterpret_cast<const xmlChar*>(Trait::tag))) {
-                auto element = Trait::deserialize(child, serializingContext);
+                auto element = deserialize<Trait>(child, serializingContext);
                 if (element.isOk()) {
                     status_t status = Trait::addElementToCollection(element, collection);
                     if (status != NO_ERROR) {
@@ -328,11 +327,14 @@
     return NO_ERROR;
 }
 
-Return<AudioGainTraits::Element> AudioGainTraits::deserialize(const xmlNode *cur,
-        PtrSerializingCtx /*serializingContext*/)
+template<>
+Return<AudioGainTraits::Element> PolicySerializer::deserialize<AudioGainTraits>(const xmlNode *cur,
+        AudioGainTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = AudioGainTraits::Attributes;
+
     static uint32_t index = 0;
-    Element gain = new AudioGain(index++, true);
+    AudioGainTraits::Element gain = new AudioGain(index++, true);
 
     std::string mode = getXmlAttribute(cur, Attributes::mode);
     if (!mode.empty()) {
@@ -395,16 +397,19 @@
     }
 }
 
-Return<AudioProfileTraits::Element> AudioProfileTraits::deserialize(const xmlNode *cur,
-        PtrSerializingCtx /*serializingContext*/)
+template<>
+Return<AudioProfileTraits::Element> PolicySerializer::deserialize<AudioProfileTraits>(
+        const xmlNode *cur, AudioProfileTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = AudioProfileTraits::Attributes;
+
     std::string samplingRates = getXmlAttribute(cur, Attributes::samplingRates);
     std::string format = getXmlAttribute(cur, Attributes::format);
     std::string channels = getXmlAttribute(cur, Attributes::channelMasks);
 
-    Element profile = new AudioProfile(formatFromString(format, gDynamicFormat),
-            channelMasksFromString(channels, ","),
-            samplingRatesFromString(samplingRates, ","));
+    AudioProfileTraits::Element profile = new AudioProfile(formatFromString(format, gDynamicFormat),
+            channelMasksFromString(channels, mChannelMasksSeparator.c_str()),
+            samplingRatesFromString(samplingRates, mSamplingRatesSeparator.c_str()));
 
     profile->setDynamicFormat(profile->getFormat() == gDynamicFormat);
     profile->setDynamicChannels(profile->getChannels().empty());
@@ -413,15 +418,18 @@
     return profile;
 }
 
-Return<MixPortTraits::Element> MixPortTraits::deserialize(const xmlNode *child,
-        PtrSerializingCtx /*serializingContext*/)
+template<>
+Return<MixPortTraits::Element> PolicySerializer::deserialize<MixPortTraits>(const xmlNode *child,
+        MixPortTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = MixPortTraits::Attributes;
+
     std::string name = getXmlAttribute(child, Attributes::name);
     if (name.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::name);
         return Status::fromStatusT(BAD_VALUE);
     }
-    ALOGV("%s: %s %s=%s", __func__, tag, Attributes::name, name.c_str());
+    ALOGV("%s: %s %s=%s", __func__, MixPortTraits::tag, Attributes::name, name.c_str());
     std::string role = getXmlAttribute(child, Attributes::role);
     if (role.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::role);
@@ -431,7 +439,7 @@
     audio_port_role_t portRole = (role == Attributes::roleSource) ?
             AUDIO_PORT_ROLE_SOURCE : AUDIO_PORT_ROLE_SINK;
 
-    Element mixPort = new IOProfile(name, portRole);
+    MixPortTraits::Element mixPort = new IOProfile(name, portRole);
 
     AudioProfileTraits::Collection profiles;
     status_t status = deserializeCollection<AudioProfileTraits>(child, &profiles, NULL);
@@ -450,10 +458,10 @@
     if (!flags.empty()) {
         // Source role
         if (portRole == AUDIO_PORT_ROLE_SOURCE) {
-            mixPort->setFlags(OutputFlagConverter::maskFromString(flags));
+            mixPort->setFlags(OutputFlagConverter::maskFromString(flags, mFlagsSeparator.c_str()));
         } else {
             // Sink role
-            mixPort->setFlags(InputFlagConverter::maskFromString(flags));
+            mixPort->setFlags(InputFlagConverter::maskFromString(flags, mFlagsSeparator.c_str()));
         }
     }
     std::string maxOpenCount = getXmlAttribute(child, Attributes::maxOpenCount);
@@ -475,9 +483,13 @@
     return mixPort;
 }
 
-Return<DevicePortTraits::Element> DevicePortTraits::deserialize(const xmlNode *cur,
-        PtrSerializingCtx /*serializingContext*/)
+template<>
+Return<DevicePortTraits::Element> PolicySerializer::deserialize<DevicePortTraits>(
+        const xmlNode *cur, DevicePortTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = DevicePortTraits::Attributes;
+    auto& tag = DevicePortTraits::tag;
+
     std::string name = getXmlAttribute(cur, Attributes::tagName);
     if (name.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::tagName);
@@ -513,7 +525,8 @@
         encodedFormats = formatsFromString(encodedFormatsLiteral, " ");
     }
     std::string address = getXmlAttribute(cur, Attributes::address);
-    Element deviceDesc = new DeviceDescriptor(type, name, address, encodedFormats);
+    DevicePortTraits::Element deviceDesc =
+            new DeviceDescriptor(type, name, address, encodedFormats);
 
     AudioProfileTraits::Collection profiles;
     status_t status = deserializeCollection<AudioProfileTraits>(cur, &profiles, NULL);
@@ -538,8 +551,12 @@
     return deviceDesc;
 }
 
-Return<RouteTraits::Element> RouteTraits::deserialize(const xmlNode *cur, PtrSerializingCtx ctx)
+template<>
+Return<RouteTraits::Element> PolicySerializer::deserialize<RouteTraits>(
+        const xmlNode *cur, RouteTraits::PtrSerializingCtx ctx)
 {
+    using Attributes = RouteTraits::Attributes;
+
     std::string type = getXmlAttribute(cur, Attributes::type);
     if (type.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::type);
@@ -548,8 +565,8 @@
     audio_route_type_t routeType = (type == Attributes::typeMix) ?
                 AUDIO_ROUTE_MIX : AUDIO_ROUTE_MUX;
 
-    ALOGV("%s: %s %s=%s", __func__, tag, Attributes::type, type.c_str());
-    Element route = new AudioRoute(routeType);
+    ALOGV("%s: %s %s=%s", __func__, RouteTraits::tag, Attributes::type, type.c_str());
+    RouteTraits::Element route = new AudioRoute(routeType);
 
     std::string sinkAttr = getXmlAttribute(cur, Attributes::sink);
     if (sinkAttr.empty()) {
@@ -595,8 +612,16 @@
     return route;
 }
 
-Return<ModuleTraits::Element> ModuleTraits::deserialize(const xmlNode *cur, PtrSerializingCtx ctx)
+template<>
+Return<ModuleTraits::Element> PolicySerializer::deserialize<ModuleTraits>(
+        const xmlNode *cur, ModuleTraits::PtrSerializingCtx ctx)
 {
+    using Attributes = ModuleTraits::Attributes;
+    auto& tag = ModuleTraits::tag;
+    auto& childAttachedDevicesTag = ModuleTraits::childAttachedDevicesTag;
+    auto& childAttachedDeviceTag = ModuleTraits::childAttachedDeviceTag;
+    auto& childDefaultOutputDeviceTag = ModuleTraits::childDefaultOutputDeviceTag;
+
     std::string name = getXmlAttribute(cur, Attributes::name);
     if (name.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::name);
@@ -610,11 +635,11 @@
               versionMajor, versionMajor);
     }
 
-    ALOGV("%s: %s %s=%s", __func__, tag, Attributes::name, name.c_str());
+    ALOGV("%s: %s %s=%s", __func__, ModuleTraits::tag, Attributes::name, name.c_str());
 
-    Element module = new HwModule(name.c_str(), versionMajor, versionMinor);
+    ModuleTraits::Element module = new HwModule(name.c_str(), versionMajor, versionMinor);
 
-    // Deserialize childrens: Audio Mix Port, Audio Device Ports (Source/Sink), Audio Routes
+    // Deserialize children: Audio Mix Port, Audio Device Ports (Source/Sink), Audio Routes
     MixPortTraits::Collection mixPorts;
     status_t status = deserializeCollection<MixPortTraits>(cur, &mixPorts, NULL);
     if (status != NO_ERROR) {
@@ -677,10 +702,14 @@
     return module;
 }
 
-status_t GlobalConfigTraits::deserialize(const xmlNode *root, AudioPolicyConfig *config)
+template<>
+Return<GlobalConfigTraits::Element> PolicySerializer::deserialize<GlobalConfigTraits>(
+        const xmlNode *root, GlobalConfigTraits::PtrSerializingCtx config)
 {
+    using Attributes = GlobalConfigTraits::Attributes;
+
     for (const xmlNode *cur = root->xmlChildrenNode; cur != NULL; cur = cur->next) {
-        if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>(tag))) {
+        if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>(GlobalConfigTraits::tag))) {
             bool value;
             std::string attr = getXmlAttribute(cur, Attributes::speakerDrcEnabled);
             if (!attr.empty() &&
@@ -696,33 +725,38 @@
             if (!engineLibrarySuffix.empty()) {
                 config->setEngineLibraryNameSuffix(engineLibrarySuffix);
             }
-            return NO_ERROR;
+            return Void();
         }
     }
-    return NO_ERROR;
+    return Void();
 }
 
-status_t SurroundSoundTraits::deserialize(const xmlNode *root, AudioPolicyConfig *config)
+template<>
+Return<SurroundSoundTraits::Element> PolicySerializer::deserialize<SurroundSoundTraits>(
+        const xmlNode *root, SurroundSoundTraits::PtrSerializingCtx config)
 {
     config->setDefaultSurroundFormats();
 
     for (const xmlNode *cur = root->xmlChildrenNode; cur != NULL; cur = cur->next) {
-        if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>(tag))) {
+        if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>(SurroundSoundTraits::tag))) {
             AudioPolicyConfig::SurroundFormats formats;
             status_t status = deserializeCollection<SurroundSoundFormatTraits>(
                     cur, &formats, nullptr);
             if (status == NO_ERROR) {
                 config->setSurroundFormats(formats);
             }
-            return NO_ERROR;
+            return Void();
         }
     }
-    return NO_ERROR;
+    return Void();
 }
 
-Return<SurroundSoundFormatTraits::Element> SurroundSoundFormatTraits::deserialize(
-        const xmlNode *cur, PtrSerializingCtx /*serializingContext*/)
+template<>
+Return<SurroundSoundFormatTraits::Element> PolicySerializer::deserialize<SurroundSoundFormatTraits>(
+        const xmlNode *cur, SurroundSoundFormatTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = SurroundSoundFormatTraits::Attributes;
+
     std::string formatLiteral = getXmlAttribute(cur, Attributes::name);
     if (formatLiteral.empty()) {
         ALOGE("%s: No %s found for a surround format", __func__, Attributes::name);
@@ -733,7 +767,8 @@
         ALOGE("%s: Unrecognized format %s", __func__, formatLiteral.c_str());
         return Status::fromStatusT(BAD_VALUE);
     }
-    Element pair = std::make_pair(format, Collection::mapped_type{});
+    SurroundSoundFormatTraits::Element pair = std::make_pair(
+            format, SurroundSoundFormatTraits::Collection::mapped_type{});
 
     std::string subformatsLiteral = getXmlAttribute(cur, Attributes::subformats);
     if (subformatsLiteral.empty()) return pair;
@@ -775,12 +810,14 @@
         ALOGE("%s: No version found in root node %s", __func__, rootName);
         return BAD_VALUE;
     }
-    if (version != mVersion) {
-        ALOGE("%s: Version does not match; expect %s got %s", __func__, mVersion.c_str(),
-              version.c_str());
+    if (version == "7.0") {
+        mChannelMasksSeparator = mSamplingRatesSeparator = mFlagsSeparator = " ";
+    } else if (version != "1.0") {
+        ALOGE("%s: Version does not match; expected \"1.0\" or \"7.0\" got \"%s\"",
+                __func__, version.c_str());
         return BAD_VALUE;
     }
-    // Lets deserialize children
+    // Let's deserialize children
     // Modules
     ModuleTraits::Collection modules;
     status_t status = deserializeCollection<ModuleTraits>(root, &modules, config);
@@ -790,10 +827,10 @@
     config->setHwModules(modules);
 
     // Global Configuration
-    GlobalConfigTraits::deserialize(root, config);
+    deserialize<GlobalConfigTraits>(root, config);
 
     // Surround configuration
-    SurroundSoundTraits::deserialize(root, config);
+    deserialize<SurroundSoundTraits>(root, config);
 
     return android::OK;
 }
diff --git a/services/audiopolicy/config/audio_policy_configuration_7_0.xml b/services/audiopolicy/config/audio_policy_configuration_7_0.xml
index 31c8954..9961a00 100644
--- a/services/audiopolicy/config/audio_policy_configuration_7_0.xml
+++ b/services/audiopolicy/config/audio_policy_configuration_7_0.xml
@@ -14,7 +14,7 @@
      limitations under the License.
 -->
 
-<audioPolicyConfiguration version="1.0" xmlns:xi="http://www.w3.org/2001/XInclude">
+<audioPolicyConfiguration version="7.0" xmlns:xi="http://www.w3.org/2001/XInclude">
     <!-- version section contains a “version” tag in the form “major.minor” e.g version=”1.0” -->
 
     <!-- Global configuration Decalaration -->
diff --git a/services/audiopolicy/config/bluetooth_audio_policy_configuration.xml b/services/audiopolicy/config/bluetooth_audio_policy_configuration.xml
index 7238317..98415b7 100644
--- a/services/audiopolicy/config/bluetooth_audio_policy_configuration.xml
+++ b/services/audiopolicy/config/bluetooth_audio_policy_configuration.xml
@@ -12,7 +12,13 @@
         </mixPort>
         <!-- Le Audio Audio Ports -->
         <mixPort name="le audio output" role="source">
-            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT,AUDIO_FORMAT_PCM_24_BIT,AUDIO_FORMAT_PCM_32_BIT"
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="8000,16000,24000,32000,44100,48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO,AUDIO_CHANNEL_OUT_STEREO"/>
+            <profile name="" format="AUDIO_FORMAT_PCM_24_BIT_PACKED"
+                     samplingRates="8000,16000,24000,32000,44100,48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO,AUDIO_CHANNEL_OUT_STEREO"/>
+            <profile name="" format="AUDIO_FORMAT_PCM_32_BIT"
                      samplingRates="8000,16000,24000,32000,44100,48000"
                      channelMasks="AUDIO_CHANNEL_OUT_MONO,AUDIO_CHANNEL_OUT_STEREO"/>
         </mixPort>
@@ -37,6 +43,10 @@
         <!-- Hearing AIDs Audio Ports -->
         <devicePort tagName="BT Hearing Aid Out" type="AUDIO_DEVICE_OUT_HEARING_AID" role="sink"/>
         <!-- BLE Audio Ports -->
+        <!-- Note that these device types are not valid in HAL versions < 7. Any device
+             running pre-V7 HAL and using this file will not pass VTS. Need to use
+             bluetooth_audio_policy_configuration_7_0.xml instead.
+        -->
         <devicePort tagName="BLE Headset Out" type="AUDIO_DEVICE_OUT_BLE_HEADSET" role="sink"/>
         <devicePort tagName="BLE Speaker Out" type="AUDIO_DEVICE_OUT_BLE_SPEAKER" role="sink"/>
     </devicePorts>
diff --git a/services/audiopolicy/config/bluetooth_audio_policy_configuration_7_0.xml b/services/audiopolicy/config/bluetooth_audio_policy_configuration_7_0.xml
index 2dffe02..fbe7571 100644
--- a/services/audiopolicy/config/bluetooth_audio_policy_configuration_7_0.xml
+++ b/services/audiopolicy/config/bluetooth_audio_policy_configuration_7_0.xml
@@ -10,6 +10,18 @@
                      samplingRates="24000 16000"
                      channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
         </mixPort>
+        <!-- Le Audio Audio Ports -->
+        <mixPort name="le audio output" role="source">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="8000 16000 24000 32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO"/>
+            <profile name="" format="AUDIO_FORMAT_PCM_24_BIT_PACKED"
+                     samplingRates="8000 16000 24000 32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO"/>
+            <profile name="" format="AUDIO_FORMAT_PCM_32_BIT"
+                     samplingRates="8000 16000 24000 32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO"/>
+        </mixPort>
     </mixPorts>
     <devicePorts>
         <!-- A2DP Audio Ports -->
@@ -30,6 +42,9 @@
         </devicePort>
         <!-- Hearing AIDs Audio Ports -->
         <devicePort tagName="BT Hearing Aid Out" type="AUDIO_DEVICE_OUT_HEARING_AID" role="sink"/>
+        <!-- BLE Audio Ports -->
+        <devicePort tagName="BLE Headset Out" type="AUDIO_DEVICE_OUT_BLE_HEADSET" role="sink"/>
+        <devicePort tagName="BLE Speaker Out" type="AUDIO_DEVICE_OUT_BLE_SPEAKER" role="sink"/>
     </devicePorts>
     <routes>
         <route type="mix" sink="BT A2DP Out"
@@ -40,5 +55,9 @@
                sources="a2dp output"/>
         <route type="mix" sink="BT Hearing Aid Out"
                sources="hearing aid output"/>
+        <route type="mix" sink="BLE Headset Out"
+               sources="le audio output"/>
+        <route type="mix" sink="BLE Speaker Out"
+               sources="le audio output"/>
     </routes>
 </module>
diff --git a/services/audiopolicy/fuzzer/Android.bp b/services/audiopolicy/fuzzer/Android.bp
new file mode 100644
index 0000000..21f6515
--- /dev/null
+++ b/services/audiopolicy/fuzzer/Android.bp
@@ -0,0 +1,55 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************************/
+
+cc_fuzz {
+    name: "audiopolicy_fuzzer",
+    srcs: [
+        "audiopolicy_fuzzer.cpp",
+    ],
+    include_dirs: [
+        "frameworks/av/services/audiopolicy",
+    ],
+    shared_libs: [
+        "android.hardware.audio.common-util",
+        "capture_state_listener-aidl-cpp",
+        "libaudioclient",
+        "libaudiofoundation",
+        "libbase",
+        "libcutils",
+        "libhidlbase",
+        "libdl",
+        "liblog",
+        "libmedia_helper",
+        "libmediametrics",
+        "libutils",
+        "libxml2",
+        "libbinder",
+        "libaudiopolicy",
+        "libaudiopolicymanagerdefault",
+    ],
+    static_libs: [
+        "android.hardware.audio.common@7.0-enums",
+        "libaudiopolicycomponents",
+    ],
+    header_libs: [
+        "libaudiopolicycommon",
+        "libaudiopolicyengine_interface_headers",
+        "libaudiopolicymanager_interface_headers",
+    ],
+    data: [":audiopolicyfuzzer_configuration_files"],
+}
diff --git a/services/audiopolicy/fuzzer/README.md b/services/audiopolicy/fuzzer/README.md
new file mode 100644
index 0000000..08d7213
--- /dev/null
+++ b/services/audiopolicy/fuzzer/README.md
@@ -0,0 +1,63 @@
+# Fuzzer for libaudiopolicy
+
+## Plugin Design Considerations
+The fuzzer plugin for libaudiopolicy is designed based on the
+understanding of the service and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+AudioPolicy APIs contain the following parameters:
+1. AudioFormats
+2. AudioChannelMasks
+3. AudioOutputFlags
+4. AudioDevices
+5. MixTypes
+6. MixRouteFlags
+7. SampleRates
+8. AudioUsages
+9. AudioContentTypes
+10. AudioSources
+11. AudioFlagMasks
+12. AudioPolicyDeviceStates
+
+| Parameter| Valid Input Values| Configured Value|
+|------------- |-------------| ----- |
+| `AudioFormat` | 77 values of type `audio_format_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `AudioChannelMask` | 83 values of type `audio_channel_mask_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `AudioOutputFlag` | 16 values of type `audio_output_flags_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `AudioDevice`   | `AUDIO_DEVICE_OUT_AUX_DIGITAL`, `AUDIO_DEVICE_OUT_STUB`, `AUDIO_DEVICE_IN_VOICE_CALL`, `AUDIO_DEVICE_IN_AUX_DIGITAL`, `AUDIO_DEVICE_IN_STUB` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `MixType`   | `MIX_TYPE_PLAYERS`, `MIX_TYPE_RECORDERS` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `MixRouteFlag`   | `MIX_ROUTE_FLAG_RENDER`, `MIX_ROUTE_FLAG_LOOP_BACK`, `MIX_ROUTE_FLAG_LOOP_BACK_AND_RENDER`, `MIX_ROUTE_FLAG_ALL` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `SampleRate` | `0` to `UINT32_MAX` | Value obtained from FuzzedDataProvider |
+| `AudioUsage` | `AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST`, `AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT`, `AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED`, `AUDIO_USAGE_NOTIFICATION_EVENT` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `AudioContentType` | `AUDIO_CONTENT_TYPE_UNKNOWN`, `AUDIO_CONTENT_TYPE_SPEECH`, `AUDIO_CONTENT_TYPE_MUSIC`, `AUDIO_CONTENT_TYPE_MOVIE`, `AUDIO_CONTENT_TYPE_SONIFICATION` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `AudioSource` | 14 values of type `audio_source_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `AudioFlagMask` | 15 values of type `audio_flags_mask_t` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+| `AudioPolicyDeviceStates` | `AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE`, `AUDIO_POLICY_DEVICE_STATE_AVAILABLE`, `AUDIO_POLICY_DEVICE_STATE_CNT` | Value chosen from valid values by obtaining index from FuzzedDataProvider |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+## Build
+
+This describes steps to build audiopolicy_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) audiopolicy_fuzzer
+```
+
+#### Steps to run
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/audiopolicy_fuzzer/audiopolicy_fuzzer
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/services/audiopolicy/fuzzer/audiopolicy_fuzzer.cpp b/services/audiopolicy/fuzzer/audiopolicy_fuzzer.cpp
new file mode 100644
index 0000000..c1f2aa8
--- /dev/null
+++ b/services/audiopolicy/fuzzer/audiopolicy_fuzzer.cpp
@@ -0,0 +1,972 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************************/
+#include <stdint.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <algorithm>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <Serializer.h>
+#include <android-base/file.h>
+#include <libxml/parser.h>
+#include <libxml/xinclude.h>
+#include <media/AudioPolicy.h>
+#include <media/PatchBuilder.h>
+#include <media/RecordingActivityTracker.h>
+
+#include <AudioPolicyInterface.h>
+#include <android_audio_policy_configuration_V7_0-enums.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include <tests/AudioPolicyManagerTestClient.h>
+#include <tests/AudioPolicyTestClient.h>
+#include <tests/AudioPolicyTestManager.h>
+#include <xsdc/XsdcSupport.h>
+
+using namespace android;
+
+namespace xsd {
+using namespace ::android::audio::policy::configuration::V7_0;
+}
+
+static const std::vector<audio_format_t> kAudioFormats = [] {
+    std::vector<audio_format_t> result;
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioFormat>{}) {
+        audio_format_t audioFormatHal;
+        std::string audioFormat = toString(enumVal);
+        if (audio_format_from_string(audioFormat.c_str(), &audioFormatHal)) {
+            result.push_back(audioFormatHal);
+        }
+    }
+    return result;
+}();
+
+static const std::vector<audio_channel_mask_t> kAudioChannelOutMasks = [] {
+    std::vector<audio_channel_mask_t> result;
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioChannelMask>{}) {
+        audio_channel_mask_t audioChannelMaskHal;
+        std::string audioChannelMask = toString(enumVal);
+        if (enumVal != xsd::AudioChannelMask::AUDIO_CHANNEL_NONE &&
+            audioChannelMask.find("_IN_") == std::string::npos &&
+            audio_channel_mask_from_string(audioChannelMask.c_str(), &audioChannelMaskHal)) {
+            result.push_back(audioChannelMaskHal);
+        }
+    }
+    return result;
+}();
+
+static const std::vector<audio_channel_mask_t> kAudioChannelInMasks = [] {
+    std::vector<audio_channel_mask_t> result;
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioChannelMask>{}) {
+        audio_channel_mask_t audioChannelMaskHal;
+        std::string audioChannelMask = toString(enumVal);
+        if (enumVal != xsd::AudioChannelMask::AUDIO_CHANNEL_NONE &&
+            audioChannelMask.find("_OUT_") == std::string::npos &&
+            audio_channel_mask_from_string(audioChannelMask.c_str(), &audioChannelMaskHal)) {
+            result.push_back(audioChannelMaskHal);
+        }
+    }
+    return result;
+}();
+
+static const std::vector<audio_output_flags_t> kAudioOutputFlags = [] {
+    std::vector<audio_output_flags_t> result;
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioInOutFlag>{}) {
+        audio_output_flags_t audioOutputFlagHal;
+        std::string audioOutputFlag = toString(enumVal);
+        if (audioOutputFlag.find("_OUTPUT_") != std::string::npos &&
+            audio_output_flag_from_string(audioOutputFlag.c_str(), &audioOutputFlagHal)) {
+            result.push_back(audioOutputFlagHal);
+        }
+    }
+    return result;
+}();
+
+static const std::vector<audio_devices_t> kAudioDevices = [] {
+    std::vector<audio_devices_t> result;
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioDevice>{}) {
+        audio_devices_t audioDeviceHal;
+        std::string audioDevice = toString(enumVal);
+        if (audio_device_from_string(audioDevice.c_str(), &audioDeviceHal)) {
+            result.push_back(audioDeviceHal);
+        }
+    }
+    return result;
+}();
+
+static const std::vector<audio_usage_t> kAudioUsages = [] {
+    std::vector<audio_usage_t> result;
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioUsage>{}) {
+        audio_usage_t audioUsageHal;
+        std::string audioUsage = toString(enumVal);
+        if (audio_usage_from_string(audioUsage.c_str(), &audioUsageHal)) {
+            result.push_back(audioUsageHal);
+        }
+    }
+    return result;
+}();
+
+static const std::vector<audio_source_t> kAudioSources = [] {
+    std::vector<audio_source_t> result;
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioSource>{}) {
+        audio_source_t audioSourceHal;
+        std::string audioSource = toString(enumVal);
+        if (audio_source_from_string(audioSource.c_str(), &audioSourceHal)) {
+            result.push_back(audioSourceHal);
+        }
+    }
+    return result;
+}();
+
+static const std::vector<audio_content_type_t> kAudioContentTypes = [] {
+    std::vector<audio_content_type_t> result;
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioContentType>{}) {
+        audio_content_type_t audioContentTypeHal;
+        std::string audioContentType = toString(enumVal);
+        if (audio_content_type_from_string(audioContentType.c_str(), &audioContentTypeHal)) {
+            result.push_back(audioContentTypeHal);
+        }
+    }
+    return result;
+}();
+
+std::vector<int> kMixTypes = {MIX_TYPE_PLAYERS, MIX_TYPE_RECORDERS};
+
+std::vector<int> kMixRouteFlags = {MIX_ROUTE_FLAG_RENDER, MIX_ROUTE_FLAG_LOOP_BACK,
+                                   MIX_ROUTE_FLAG_LOOP_BACK_AND_RENDER, MIX_ROUTE_FLAG_ALL};
+
+std::vector<audio_flags_mask_t> kAudioFlagMasks = {
+    AUDIO_FLAG_NONE,           AUDIO_FLAG_AUDIBILITY_ENFORCED,
+    AUDIO_FLAG_SECURE,         AUDIO_FLAG_SCO,
+    AUDIO_FLAG_BEACON,         AUDIO_FLAG_HW_AV_SYNC,
+    AUDIO_FLAG_HW_HOTWORD,     AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY,
+    AUDIO_FLAG_BYPASS_MUTE,    AUDIO_FLAG_LOW_LATENCY,
+    AUDIO_FLAG_DEEP_BUFFER,    AUDIO_FLAG_NO_MEDIA_PROJECTION,
+    AUDIO_FLAG_MUTE_HAPTIC,    AUDIO_FLAG_NO_SYSTEM_CAPTURE,
+    AUDIO_FLAG_CAPTURE_PRIVATE};
+
+std::vector<audio_policy_dev_state_t> kAudioPolicyDeviceStates = {
+    AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
+    AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
+    AUDIO_POLICY_DEVICE_STATE_CNT,
+};
+
+std::vector<uint32_t> kSamplingRates = {8000, 16000, 44100, 48000, 88200, 96000};
+
+template <typename T>
+T getValueFromVector(FuzzedDataProvider *fdp, std::vector<T> arr) {
+    if (fdp->ConsumeBool()) {
+        return arr[fdp->ConsumeIntegralInRange<int32_t>(0, arr.size() - 1)];
+    } else {
+        return (T)fdp->ConsumeIntegral<uint32_t>();
+    }
+}
+
+class AudioPolicyManagerFuzzer {
+   public:
+    explicit AudioPolicyManagerFuzzer(FuzzedDataProvider *fdp);
+    virtual ~AudioPolicyManagerFuzzer() = default;
+    virtual bool initialize();
+    virtual void SetUpManagerConfig();
+    bool getOutputForAttr(audio_port_handle_t *selectedDeviceId, audio_format_t format,
+                          audio_channel_mask_t channelMask, int sampleRate,
+                          audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
+                          audio_io_handle_t *output = nullptr,
+                          audio_port_handle_t *portId = nullptr, audio_attributes_t attr = {});
+    bool getInputForAttr(const audio_attributes_t &attr, audio_unique_id_t riid,
+                         audio_port_handle_t *selectedDeviceId, audio_format_t format,
+                         audio_channel_mask_t channelMask, int sampleRate,
+                         audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE,
+                         audio_port_handle_t *portId = nullptr);
+    bool findDevicePort(audio_port_role_t role, audio_devices_t deviceType,
+                        const std::string &address, audio_port_v7 *foundPort);
+    static audio_port_handle_t getDeviceIdFromPatch(const struct audio_patch *patch);
+    audio_patch createFuzzedPatch();
+    void fuzzPatchCreation();
+    virtual void process();
+
+   protected:
+    std::unique_ptr<AudioPolicyManagerTestClient> mClient{new AudioPolicyManagerTestClient};
+    std::unique_ptr<AudioPolicyTestManager> mManager{new AudioPolicyTestManager(mClient.get())};
+    FuzzedDataProvider *mFdp;
+};
+
+AudioPolicyManagerFuzzer::AudioPolicyManagerFuzzer(FuzzedDataProvider *fdp)
+        : mFdp(fdp) {}
+
+bool AudioPolicyManagerFuzzer::initialize() {
+    if (mFdp->remaining_bytes() < 1) {
+        return false;
+    }
+    // init code
+    SetUpManagerConfig();
+
+    if (mManager->initialize() != NO_ERROR) {
+        return false;
+    }
+    if (mManager->initCheck() != NO_ERROR) {
+        return false;
+    }
+    return true;
+}
+
+void AudioPolicyManagerFuzzer::SetUpManagerConfig() { mManager->getConfig().setDefault(); }
+
+bool AudioPolicyManagerFuzzer::getOutputForAttr(
+    audio_port_handle_t *selectedDeviceId, audio_format_t format, audio_channel_mask_t channelMask,
+    int sampleRate, audio_output_flags_t flags, audio_io_handle_t *output,
+    audio_port_handle_t *portId, audio_attributes_t attr) {
+    audio_io_handle_t localOutput;
+    if (!output) output = &localOutput;
+    *output = AUDIO_IO_HANDLE_NONE;
+    audio_stream_type_t stream = AUDIO_STREAM_DEFAULT;
+    audio_config_t config = AUDIO_CONFIG_INITIALIZER;
+    config.sample_rate = sampleRate;
+    config.channel_mask = channelMask;
+    config.format = format;
+    audio_port_handle_t localPortId;
+    if (!portId) portId = &localPortId;
+    *portId = AUDIO_PORT_HANDLE_NONE;
+    AudioPolicyInterface::output_type_t outputType;
+
+    if (mManager->getOutputForAttr(&attr, output, AUDIO_SESSION_NONE, &stream, 0 /*uid*/, &config,
+                                   &flags, selectedDeviceId, portId, {}, &outputType) != OK) {
+        return false;
+    }
+    if (*output == AUDIO_IO_HANDLE_NONE || *portId == AUDIO_PORT_HANDLE_NONE) {
+        return false;
+    }
+    return true;
+}
+
+bool AudioPolicyManagerFuzzer::getInputForAttr(
+    const audio_attributes_t &attr, audio_unique_id_t riid, audio_port_handle_t *selectedDeviceId,
+    audio_format_t format, audio_channel_mask_t channelMask, int sampleRate,
+    audio_input_flags_t flags, audio_port_handle_t *portId) {
+    audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
+    audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
+    config.sample_rate = sampleRate;
+    config.channel_mask = channelMask;
+    config.format = format;
+    audio_port_handle_t localPortId;
+    if (!portId) portId = &localPortId;
+    *portId = AUDIO_PORT_HANDLE_NONE;
+    AudioPolicyInterface::input_type_t inputType;
+
+    if (mManager->getInputForAttr(&attr, &input, riid, AUDIO_SESSION_NONE, 0 /*uid*/, &config,
+                                  flags, selectedDeviceId, &inputType, portId) != OK) {
+        return false;
+    }
+    if (*portId == AUDIO_PORT_HANDLE_NONE || input == AUDIO_IO_HANDLE_NONE) {
+        return false;
+    }
+    return true;
+}
+
+bool AudioPolicyManagerFuzzer::findDevicePort(audio_port_role_t role, audio_devices_t deviceType,
+                                              const std::string &address,
+                                              audio_port_v7 *foundPort) {
+    uint32_t numPorts = 0;
+    uint32_t generation1;
+    status_t ret;
+
+    ret = mManager->listAudioPorts(role, AUDIO_PORT_TYPE_DEVICE, &numPorts, nullptr, &generation1);
+    if (ret != NO_ERROR) {
+        return false;
+    }
+
+    uint32_t generation2;
+    struct audio_port_v7 ports[numPorts];
+    ret = mManager->listAudioPorts(role, AUDIO_PORT_TYPE_DEVICE, &numPorts, ports, &generation2);
+    if (ret != NO_ERROR) {
+        return false;
+    }
+
+    for (const auto &port : ports) {
+        if (port.role == role && port.ext.device.type == deviceType &&
+            (strncmp(port.ext.device.address, address.c_str(), AUDIO_DEVICE_MAX_ADDRESS_LEN) ==
+             0)) {
+            if (foundPort) *foundPort = port;
+            return true;
+        }
+    }
+    return false;
+}
+
+audio_port_handle_t AudioPolicyManagerFuzzer::getDeviceIdFromPatch(
+    const struct audio_patch *patch) {
+    if (patch->num_sources != 0 && patch->num_sinks != 0) {
+        if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
+            return patch->sinks[0].id;
+        } else {
+            return patch->sources[0].id;
+        }
+    }
+    return AUDIO_PORT_HANDLE_NONE;
+}
+
+audio_patch AudioPolicyManagerFuzzer::createFuzzedPatch() {
+    audio_patch patch{};
+    patch.id = mFdp->ConsumeIntegral<uint32_t>();
+    patch.num_sources = mFdp->ConsumeIntegralInRange(0, AUDIO_PATCH_PORTS_MAX);
+    for (int i = 0; i < patch.num_sources; ++i) {
+        audio_port_config config{};
+        std::vector<uint8_t> bytes = mFdp->ConsumeBytes<uint8_t>(sizeof(config));
+        memcpy(reinterpret_cast<uint8_t *>(&config), &bytes[0], bytes.size());
+        patch.sources[i] = config;
+    }
+    patch.num_sinks = mFdp->ConsumeIntegralInRange(0, AUDIO_PATCH_PORTS_MAX);
+    for (int i = 0; i < patch.num_sinks; ++i) {
+        audio_port_config config{};
+        std::vector<uint8_t> bytes = mFdp->ConsumeBytes<uint8_t>(sizeof(config));
+        memcpy(reinterpret_cast<uint8_t *>(&config), &bytes[0], bytes.size());
+        patch.sinks[i] = config;
+    }
+    return patch;
+}
+
+void AudioPolicyManagerFuzzer::fuzzPatchCreation() {
+    if (mFdp->remaining_bytes()) {
+        audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
+        uid_t uid = mFdp->ConsumeIntegral<uint32_t>();
+
+        // create a fuzzed patch
+        handle = AUDIO_PATCH_HANDLE_NONE;
+        audio_patch patch = createFuzzedPatch();
+        uid = mFdp->ConsumeIntegral<uint32_t>();
+        if (mManager->createAudioPatch(&patch, &handle, uid) == NO_ERROR) {
+            mManager->releaseAudioPatch(handle, uid);
+        }
+    }
+}
+
+void AudioPolicyManagerFuzzer::process() {
+    if (initialize()) {
+        fuzzPatchCreation();
+    }
+}
+
+class AudioPolicyManagerFuzzerWithConfigurationFile : public AudioPolicyManagerFuzzer {
+   public:
+    explicit AudioPolicyManagerFuzzerWithConfigurationFile(FuzzedDataProvider *fdp)
+        : AudioPolicyManagerFuzzer(fdp){};
+
+   protected:
+    void SetUpManagerConfig() override;
+    virtual std::string getConfigFile();
+    void traverseAndFuzzXML(xmlDocPtr pDoc, xmlNodePtr curr);
+    std::string fuzzXML(std::string xmlPath);
+
+    static inline const std::string sExecutableDir = base::GetExecutableDirectory() + "/";
+    static inline const std::string sDefaultConfig =
+            sExecutableDir + "data/test_audio_policy_configuration.xml";
+    static inline const std::string sFuzzedConfig = sExecutableDir + "fuzzed.xml";;
+};
+
+std::string AudioPolicyManagerFuzzerWithConfigurationFile::getConfigFile() {
+    return fuzzXML(sDefaultConfig);
+}
+
+void AudioPolicyManagerFuzzerWithConfigurationFile::SetUpManagerConfig() {
+    deserializeAudioPolicyFile(getConfigFile().c_str(), &mManager->getConfig());
+}
+
+void AudioPolicyManagerFuzzerWithConfigurationFile::traverseAndFuzzXML(xmlDocPtr pDoc,
+                                                                       xmlNodePtr curr) {
+    if (curr == nullptr) {
+        return;
+    }
+
+    xmlAttr *attribute = curr->properties;
+    while (attribute) {
+        if (!xmlStrcmp(attribute->name, reinterpret_cast<const xmlChar *>("format"))) {
+            const char *newFormat =
+                audio_format_to_string(getValueFromVector<audio_format_t>(mFdp, kAudioFormats));
+            xmlSetProp(curr, attribute->name, reinterpret_cast<const xmlChar *>(newFormat));
+        }
+        if (!xmlStrcmp(attribute->name, reinterpret_cast<const xmlChar *>("flags"))) {
+            std::string newFlag = "";
+            uint16_t numFlags = std::max((uint16_t)1, mFdp->ConsumeIntegral<uint16_t>());
+            for (uint16_t i = 0; i < numFlags; ++i) {
+                newFlag += std::string(audio_output_flag_to_string(
+                    getValueFromVector<audio_output_flags_t>(mFdp, kAudioOutputFlags)));
+                if (i != (numFlags - 1)) {
+                    newFlag += std::string("|");
+                }
+            }
+            xmlSetProp(curr, attribute->name, reinterpret_cast<const xmlChar *>(newFlag.c_str()));
+        }
+        if (!xmlStrcmp(attribute->name, reinterpret_cast<const xmlChar *>("samplingRates"))) {
+            std::string newRate = "";
+            uint16_t numRates = std::max((uint16_t)1, mFdp->ConsumeIntegral<uint16_t>());
+            for (uint16_t i = 0; i < numRates; ++i) {
+                newRate += std::to_string(getValueFromVector<uint32_t>(mFdp, kSamplingRates));
+                if (i != (numRates - 1)) {
+                    newRate += std::string(",");
+                }
+            }
+            xmlSetProp(curr, attribute->name, reinterpret_cast<const xmlChar *>(newRate.c_str()));
+        }
+        if (!xmlStrcmp(attribute->name, reinterpret_cast<const xmlChar *>("channelMasks"))) {
+            int isOutMask = -1;
+            char *value =
+                reinterpret_cast<char *>(xmlNodeListGetString(pDoc, attribute->children, 1));
+            if (std::string(value).find(std::string("_OUT_")) != std::string::npos) {
+                // OUT mask
+                isOutMask = 1;
+            } else if (std::string(value).find(std::string("_IN_")) != std::string::npos) {
+                // IN mask
+                isOutMask = 0;
+            }
+            if (isOutMask != -1) {
+                std::string newMask = "";
+                uint16_t numMasks = std::max((uint16_t)1, mFdp->ConsumeIntegral<uint16_t>());
+                for (uint16_t i = 0; i < numMasks; ++i) {
+                    if (isOutMask) {
+                        newMask += std::string(audio_channel_out_mask_to_string(
+                            getValueFromVector<audio_channel_mask_t>(mFdp, kAudioChannelOutMasks)));
+                    } else {
+                        newMask += std::string(audio_channel_in_mask_to_string(
+                            getValueFromVector<audio_channel_mask_t>(mFdp, kAudioChannelInMasks)));
+                    }
+                    if (i != (numMasks - 1)) {
+                        newMask += std::string(",");
+                    }
+                }
+                xmlSetProp(curr, attribute->name,
+                           reinterpret_cast<const xmlChar *>(newMask.c_str()));
+            }
+            xmlFree(value);
+        }
+        attribute = attribute->next;
+    }
+
+    curr = curr->xmlChildrenNode;
+    while (curr != nullptr) {
+        traverseAndFuzzXML(pDoc, curr);
+        curr = curr->next;
+    }
+}
+
+std::string AudioPolicyManagerFuzzerWithConfigurationFile::fuzzXML(std::string xmlPath) {
+    std::string outPath = sFuzzedConfig;
+
+    // Load in the xml file from disk
+    xmlDocPtr pDoc = xmlParseFile(xmlPath.c_str());
+    xmlNodePtr root = xmlDocGetRootElement(pDoc);
+
+    traverseAndFuzzXML(pDoc, root);
+
+    // Save the document back out to disk.
+    xmlSaveFileEnc(outPath.c_str(), pDoc, "UTF-8");
+    xmlFreeDoc(pDoc);
+
+    return outPath;
+}
+
+class AudioPolicyManagerFuzzerMsd : public AudioPolicyManagerFuzzerWithConfigurationFile {
+   public:
+    explicit AudioPolicyManagerFuzzerMsd(FuzzedDataProvider *fdp)
+        : AudioPolicyManagerFuzzerWithConfigurationFile(fdp) {}
+
+   protected:
+    std::string getConfigFile() override;
+
+    static inline const std::string sMsdConfig =
+            sExecutableDir + "data/test_audio_policy_msd_configuration.xml";
+};
+
+std::string AudioPolicyManagerFuzzerMsd::getConfigFile() { return fuzzXML(sMsdConfig); }
+
+using PolicyMixTuple = std::tuple<audio_usage_t, audio_source_t, uint32_t>;
+
+class AudioPolicyManagerFuzzerDynamicPolicy : public AudioPolicyManagerFuzzerWithConfigurationFile {
+   public:
+    explicit AudioPolicyManagerFuzzerDynamicPolicy(FuzzedDataProvider *fdp)
+        : AudioPolicyManagerFuzzerWithConfigurationFile(fdp){};
+    ~AudioPolicyManagerFuzzerDynamicPolicy() override;
+    void process() override;
+
+   protected:
+    status_t addPolicyMix(int mixType, int mixFlag, audio_devices_t deviceType,
+                          std::string mixAddress, const audio_config_t &audioConfig,
+                          const std::vector<PolicyMixTuple> &rules);
+    void clearPolicyMix();
+    void registerPolicyMixes();
+    void unregisterPolicyMixes();
+
+    Vector<AudioMix> mAudioMixes;
+    const std::string mMixAddress = "remote_submix_media";
+};
+
+AudioPolicyManagerFuzzerDynamicPolicy::~AudioPolicyManagerFuzzerDynamicPolicy() {
+    clearPolicyMix();
+}
+
+status_t AudioPolicyManagerFuzzerDynamicPolicy::addPolicyMix(
+    int mixType, int mixFlag, audio_devices_t deviceType, std::string mixAddress,
+    const audio_config_t &audioConfig, const std::vector<PolicyMixTuple> &rules) {
+    Vector<AudioMixMatchCriterion> myMixMatchCriteria;
+
+    for (const auto &rule : rules) {
+        myMixMatchCriteria.add(
+            AudioMixMatchCriterion(std::get<0>(rule), std::get<1>(rule), std::get<2>(rule)));
+    }
+
+    AudioMix myAudioMix(myMixMatchCriteria, mixType, audioConfig, mixFlag,
+                        String8(mixAddress.c_str()), 0);
+    myAudioMix.mDeviceType = deviceType;
+    // Clear mAudioMix before add new one to make sure we don't add already existing mixes.
+    mAudioMixes.clear();
+    mAudioMixes.add(myAudioMix);
+
+    // As the policy mixes registration may fail at some case,
+    // caller need to check the returned status.
+    status_t ret = mManager->registerPolicyMixes(mAudioMixes);
+    return ret;
+}
+
+void AudioPolicyManagerFuzzerDynamicPolicy::clearPolicyMix() {
+    if (mManager != nullptr) {
+        mManager->unregisterPolicyMixes(mAudioMixes);
+    }
+    mAudioMixes.clear();
+}
+
+void AudioPolicyManagerFuzzerDynamicPolicy::registerPolicyMixes() {
+    const uint32_t numPolicies = mFdp->ConsumeIntegralInRange<uint32_t>(1, MAX_MIXES_PER_POLICY);
+
+    for (int i = 0; i < numPolicies; ++i) {
+        audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
+        audioConfig.channel_mask = getValueFromVector<audio_channel_mask_t>(
+            mFdp, mFdp->ConsumeBool() ? kAudioChannelInMasks : kAudioChannelOutMasks);
+        audioConfig.format = getValueFromVector<audio_format_t>(mFdp, kAudioFormats);
+        audioConfig.sample_rate = getValueFromVector<uint32_t>(mFdp, kSamplingRates);
+        addPolicyMix(getValueFromVector<int>(mFdp, kMixTypes),
+                     getValueFromVector<int>(mFdp, kMixRouteFlags),
+                     getValueFromVector<audio_devices_t>(mFdp, kAudioDevices), "", audioConfig,
+                     std::vector<PolicyMixTuple>());
+    }
+}
+
+void AudioPolicyManagerFuzzerDynamicPolicy::unregisterPolicyMixes() {
+    mManager->unregisterPolicyMixes(mAudioMixes);
+}
+
+void AudioPolicyManagerFuzzerDynamicPolicy::process() {
+    if (initialize()) {
+        registerPolicyMixes();
+        fuzzPatchCreation();
+        unregisterPolicyMixes();
+    }
+}
+
+class AudioPolicyManagerFuzzerDPNoRemoteSubmixModule
+    : public AudioPolicyManagerFuzzerDynamicPolicy {
+   public:
+    explicit AudioPolicyManagerFuzzerDPNoRemoteSubmixModule(FuzzedDataProvider *fdp)
+        : AudioPolicyManagerFuzzerDynamicPolicy(fdp){};
+
+   protected:
+    std::string getConfigFile() override;
+
+    static inline const std::string sPrimaryOnlyConfig =
+            sExecutableDir + "data/test_audio_policy_primary_only_configuration.xml";
+};
+
+std::string AudioPolicyManagerFuzzerDPNoRemoteSubmixModule::getConfigFile() {
+    return fuzzXML(sPrimaryOnlyConfig);
+}
+
+class AudioPolicyManagerFuzzerDPPlaybackReRouting : public AudioPolicyManagerFuzzerDynamicPolicy {
+   public:
+    explicit AudioPolicyManagerFuzzerDPPlaybackReRouting(FuzzedDataProvider *fdp);
+    ~AudioPolicyManagerFuzzerDPPlaybackReRouting() override;
+    void process() override;
+
+   protected:
+    bool initialize() override;
+    void playBackReRouting();
+
+    std::unique_ptr<RecordingActivityTracker> mTracker;
+
+    std::vector<PolicyMixTuple> mUsageRules = {
+        {AUDIO_USAGE_MEDIA, AUDIO_SOURCE_DEFAULT, RULE_MATCH_ATTRIBUTE_USAGE},
+        {AUDIO_USAGE_ALARM, AUDIO_SOURCE_DEFAULT, RULE_MATCH_ATTRIBUTE_USAGE}};
+
+    struct audio_port_v7 mInjectionPort;
+    audio_port_handle_t mPortId = AUDIO_PORT_HANDLE_NONE;
+    audio_config_t mAudioConfig;
+};
+
+AudioPolicyManagerFuzzerDPPlaybackReRouting::AudioPolicyManagerFuzzerDPPlaybackReRouting(
+        FuzzedDataProvider *fdp)
+        : AudioPolicyManagerFuzzerDynamicPolicy(fdp) {
+    const uint32_t numRules = mFdp->ConsumeIntegralInRange<uint32_t>(1, 10);
+    for (int i = 0; i < numRules; ++i) {
+        PolicyMixTuple rule = {getValueFromVector<audio_usage_t>(mFdp, kAudioUsages),
+                               getValueFromVector<audio_source_t>(mFdp, kAudioSources),
+                               RULE_MATCH_ATTRIBUTE_USAGE};
+        mUsageRules.push_back(rule);
+    }
+}
+
+AudioPolicyManagerFuzzerDPPlaybackReRouting::~AudioPolicyManagerFuzzerDPPlaybackReRouting() {
+    mManager->stopInput(mPortId);
+}
+
+bool AudioPolicyManagerFuzzerDPPlaybackReRouting::initialize() {
+    AudioPolicyManagerFuzzerDynamicPolicy::initialize();
+    mTracker.reset(new RecordingActivityTracker());
+
+    mAudioConfig = AUDIO_CONFIG_INITIALIZER;
+    mAudioConfig.channel_mask =
+        getValueFromVector<audio_channel_mask_t>(mFdp, kAudioChannelOutMasks);
+    mAudioConfig.format = getValueFromVector<audio_format_t>(mFdp, kAudioFormats);
+    mAudioConfig.sample_rate = getValueFromVector<uint32_t>(mFdp, kSamplingRates);
+    status_t ret = addPolicyMix(getValueFromVector<int>(mFdp, kMixTypes),
+                                getValueFromVector<int>(mFdp, kMixRouteFlags),
+                                getValueFromVector<audio_devices_t>(mFdp, kAudioDevices),
+                                mMixAddress, mAudioConfig, mUsageRules);
+    if (ret != NO_ERROR) {
+        return false;
+    }
+
+    struct audio_port_v7 extractionPort;
+    findDevicePort(AUDIO_PORT_ROLE_SOURCE, getValueFromVector<audio_devices_t>(mFdp, kAudioDevices),
+                   mMixAddress, &extractionPort);
+
+    audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
+    audio_source_t source = getValueFromVector<audio_source_t>(mFdp, kAudioSources);
+    audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, source,
+                               AUDIO_FLAG_NONE, ""};
+    std::string tags = "addr=" + mMixAddress;
+    strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
+    getInputForAttr(attr, mTracker->getRiid(), &selectedDeviceId, mAudioConfig.format,
+                    mAudioConfig.channel_mask, mAudioConfig.sample_rate, AUDIO_INPUT_FLAG_NONE,
+                    &mPortId);
+
+    ret = mManager->startInput(mPortId);
+    if (ret != NO_ERROR) {
+        return false;
+    }
+    if (!findDevicePort(AUDIO_PORT_ROLE_SINK,
+                        getValueFromVector<audio_devices_t>(mFdp, kAudioDevices), mMixAddress,
+                        &mInjectionPort)) {
+        return false;
+    }
+
+    return true;
+}
+
+void AudioPolicyManagerFuzzerDPPlaybackReRouting::playBackReRouting() {
+    const uint32_t numTestCases = mFdp->ConsumeIntegralInRange<uint32_t>(1, 10);
+    for (int i = 0; i < numTestCases; ++i) {
+        audio_attributes_t attr;
+        attr.content_type = getValueFromVector<audio_content_type_t>(mFdp, kAudioContentTypes);
+        attr.usage = getValueFromVector<audio_usage_t>(mFdp, kAudioUsages);
+        attr.source = getValueFromVector<audio_source_t>(mFdp, kAudioSources);
+        attr.flags = getValueFromVector<audio_flags_mask_t>(mFdp, kAudioFlagMasks);
+        std::string tags(mFdp->ConsumeBool() ? "" : "addr=remote_submix_media");
+        strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
+
+        audio_port_handle_t playbackRoutedPortId = AUDIO_PORT_HANDLE_NONE;
+        getOutputForAttr(&playbackRoutedPortId, mAudioConfig.format, mAudioConfig.channel_mask,
+                         mAudioConfig.sample_rate, AUDIO_OUTPUT_FLAG_NONE, nullptr /*output*/,
+                         nullptr /*portId*/, attr);
+    }
+}
+
+void AudioPolicyManagerFuzzerDPPlaybackReRouting::process() {
+    if (initialize()) {
+        playBackReRouting();
+        registerPolicyMixes();
+        fuzzPatchCreation();
+        unregisterPolicyMixes();
+    }
+}
+
+class AudioPolicyManagerFuzzerDPMixRecordInjection : public AudioPolicyManagerFuzzerDynamicPolicy {
+   public:
+    explicit AudioPolicyManagerFuzzerDPMixRecordInjection(FuzzedDataProvider *fdp);
+    ~AudioPolicyManagerFuzzerDPMixRecordInjection() override;
+    void process() override;
+
+   protected:
+    bool initialize() override;
+    void recordingInjection();
+
+    std::unique_ptr<RecordingActivityTracker> mTracker;
+
+    std::vector<PolicyMixTuple> mSourceRules = {
+        {AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_CAMCORDER, RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET},
+        {AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_MIC, RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET},
+        {AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_VOICE_COMMUNICATION,
+         RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET}};
+
+    struct audio_port_v7 mExtractionPort;
+    audio_port_handle_t mPortId = AUDIO_PORT_HANDLE_NONE;
+    audio_config_t mAudioConfig;
+};
+
+AudioPolicyManagerFuzzerDPMixRecordInjection::AudioPolicyManagerFuzzerDPMixRecordInjection(
+        FuzzedDataProvider *fdp)
+        : AudioPolicyManagerFuzzerDynamicPolicy(fdp) {
+    const uint32_t numRules = mFdp->ConsumeIntegralInRange<uint32_t>(1, 10);
+    for (int i = 0; i < numRules; ++i) {
+        PolicyMixTuple rule = {getValueFromVector<audio_usage_t>(mFdp, kAudioUsages),
+                               getValueFromVector<audio_source_t>(mFdp, kAudioSources),
+                               RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET};
+        mSourceRules.push_back(rule);
+    }
+}
+
+AudioPolicyManagerFuzzerDPMixRecordInjection::~AudioPolicyManagerFuzzerDPMixRecordInjection() {
+    mManager->stopOutput(mPortId);
+}
+
+bool AudioPolicyManagerFuzzerDPMixRecordInjection::initialize() {
+    AudioPolicyManagerFuzzerDynamicPolicy::initialize();
+
+    mTracker.reset(new RecordingActivityTracker());
+
+    mAudioConfig = AUDIO_CONFIG_INITIALIZER;
+    mAudioConfig.channel_mask =
+        getValueFromVector<audio_channel_mask_t>(mFdp, kAudioChannelInMasks);
+    mAudioConfig.format = getValueFromVector<audio_format_t>(mFdp, kAudioFormats);
+    mAudioConfig.sample_rate = getValueFromVector<uint32_t>(mFdp, kSamplingRates);
+    status_t ret = addPolicyMix(getValueFromVector<int>(mFdp, kMixTypes),
+                                getValueFromVector<int>(mFdp, kMixRouteFlags),
+                                getValueFromVector<audio_devices_t>(mFdp, kAudioDevices),
+                                mMixAddress, mAudioConfig, mSourceRules);
+    if (ret != NO_ERROR) {
+        return false;
+    }
+
+    struct audio_port_v7 injectionPort;
+    findDevicePort(AUDIO_PORT_ROLE_SINK, getValueFromVector<audio_devices_t>(mFdp, kAudioDevices),
+                   mMixAddress, &injectionPort);
+
+    audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
+    audio_usage_t usage = getValueFromVector<audio_usage_t>(mFdp, kAudioUsages);
+    audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, usage, AUDIO_SOURCE_DEFAULT,
+                               AUDIO_FLAG_NONE, ""};
+    std::string tags = std::string("addr=") + mMixAddress;
+    strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
+    getOutputForAttr(&selectedDeviceId, mAudioConfig.format, mAudioConfig.channel_mask,
+                     mAudioConfig.sample_rate /*sampleRate*/, AUDIO_OUTPUT_FLAG_NONE,
+                     nullptr /*output*/, &mPortId, attr);
+    ret = mManager->startOutput(mPortId);
+    if (ret != NO_ERROR) {
+        return false;
+    }
+    getDeviceIdFromPatch(mClient->getLastAddedPatch());
+    if (!findDevicePort(AUDIO_PORT_ROLE_SOURCE,
+                        getValueFromVector<audio_devices_t>(mFdp, kAudioDevices), mMixAddress,
+                        &mExtractionPort)) {
+        return false;
+    }
+
+    return true;
+}
+
+void AudioPolicyManagerFuzzerDPMixRecordInjection::recordingInjection() {
+    const uint32_t numTestCases = mFdp->ConsumeIntegralInRange<uint32_t>(1, 10);
+    for (int i = 0; i < numTestCases; ++i) {
+        audio_attributes_t attr;
+        attr.content_type = getValueFromVector<audio_content_type_t>(mFdp, kAudioContentTypes);
+        attr.usage = getValueFromVector<audio_usage_t>(mFdp, kAudioUsages);
+        attr.source = getValueFromVector<audio_source_t>(mFdp, kAudioSources);
+        attr.flags = getValueFromVector<audio_flags_mask_t>(mFdp, kAudioFlagMasks);
+        std::string tags(mFdp->ConsumeBool() ? "" : "addr=remote_submix_media");
+        strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
+
+        audio_port_handle_t captureRoutedPortId = AUDIO_PORT_HANDLE_NONE;
+        audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
+        getInputForAttr(attr, mTracker->getRiid(), &captureRoutedPortId, mAudioConfig.format,
+                        mAudioConfig.channel_mask, mAudioConfig.sample_rate, AUDIO_INPUT_FLAG_NONE,
+                        &portId);
+    }
+}
+
+void AudioPolicyManagerFuzzerDPMixRecordInjection::process() {
+    if (initialize()) {
+        recordingInjection();
+        registerPolicyMixes();
+        fuzzPatchCreation();
+        unregisterPolicyMixes();
+    }
+}
+
+using DeviceConnectionTestParams =
+    std::tuple<audio_devices_t /*type*/, std::string /*name*/, std::string /*address*/>;
+
+class AudioPolicyManagerFuzzerDeviceConnection
+    : public AudioPolicyManagerFuzzerWithConfigurationFile {
+   public:
+    explicit AudioPolicyManagerFuzzerDeviceConnection(FuzzedDataProvider *fdp)
+        : AudioPolicyManagerFuzzerWithConfigurationFile(fdp){};
+    void process() override;
+
+   protected:
+    void setDeviceConnectionState();
+    void explicitlyRoutingAfterConnection();
+};
+
+void AudioPolicyManagerFuzzerDeviceConnection::setDeviceConnectionState() {
+    const uint32_t numTestCases = mFdp->ConsumeIntegralInRange<uint32_t>(1, 10);
+    for (int i = 0; i < numTestCases; ++i) {
+        const audio_devices_t type = getValueFromVector<audio_devices_t>(mFdp, kAudioDevices);
+        const std::string name = mFdp->ConsumeRandomLengthString();
+        const std::string address = mFdp->ConsumeRandomLengthString();
+        mManager->setDeviceConnectionState(
+            type, getValueFromVector<audio_policy_dev_state_t>(mFdp, kAudioPolicyDeviceStates),
+            address.c_str(), name.c_str(), getValueFromVector<audio_format_t>(mFdp, kAudioFormats));
+    }
+}
+
+void AudioPolicyManagerFuzzerDeviceConnection::explicitlyRoutingAfterConnection() {
+    const uint32_t numTestCases = mFdp->ConsumeIntegralInRange<uint32_t>(1, 10);
+    for (int i = 0; i < numTestCases; ++i) {
+        const audio_devices_t type = getValueFromVector<audio_devices_t>(mFdp, kAudioDevices);
+        const std::string name = mFdp->ConsumeRandomLengthString();
+        const std::string address = mFdp->ConsumeRandomLengthString();
+        mManager->setDeviceConnectionState(
+            type, getValueFromVector<audio_policy_dev_state_t>(mFdp, kAudioPolicyDeviceStates),
+            address.c_str(), name.c_str(), getValueFromVector<audio_format_t>(mFdp, kAudioFormats));
+
+        audio_port_v7 devicePort;
+        const audio_port_role_t role =
+            audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
+        findDevicePort(role, type, address, &devicePort);
+
+        audio_port_handle_t routedPortId = devicePort.id;
+        // Try start input or output according to the device type
+        if (audio_is_output_devices(type)) {
+            getOutputForAttr(&routedPortId, getValueFromVector<audio_format_t>(mFdp, kAudioFormats),
+                             getValueFromVector<audio_channel_mask_t>(mFdp, kAudioChannelOutMasks),
+                             getValueFromVector<uint32_t>(mFdp, kSamplingRates),
+                             AUDIO_OUTPUT_FLAG_NONE);
+        } else if (audio_is_input_device(type)) {
+            RecordingActivityTracker tracker;
+            getInputForAttr({}, tracker.getRiid(), &routedPortId,
+                            getValueFromVector<audio_format_t>(mFdp, kAudioFormats),
+                            getValueFromVector<audio_channel_mask_t>(mFdp, kAudioChannelInMasks),
+                            getValueFromVector<uint32_t>(mFdp, kSamplingRates),
+                            AUDIO_INPUT_FLAG_NONE);
+        }
+    }
+}
+
+void AudioPolicyManagerFuzzerDeviceConnection::process() {
+    if (initialize()) {
+        setDeviceConnectionState();
+        explicitlyRoutingAfterConnection();
+        fuzzPatchCreation();
+    }
+}
+
+class AudioPolicyManagerTVFuzzer : public AudioPolicyManagerFuzzerWithConfigurationFile {
+   public:
+    explicit AudioPolicyManagerTVFuzzer(FuzzedDataProvider *fdp)
+        : AudioPolicyManagerFuzzerWithConfigurationFile(fdp){};
+    void process() override;
+
+   protected:
+    std::string getConfigFile();
+    void testHDMIPortSelection(audio_output_flags_t flags);
+
+    static inline const std::string sTvConfig =
+            AudioPolicyManagerTVFuzzer::sExecutableDir + "data/test_tv_apm_configuration.xml";
+};
+
+std::string AudioPolicyManagerTVFuzzer::getConfigFile() { return fuzzXML(sTvConfig); }
+
+void AudioPolicyManagerTVFuzzer::testHDMIPortSelection(audio_output_flags_t flags) {
+    audio_devices_t audioDevice = getValueFromVector<audio_devices_t>(mFdp, kAudioDevices);
+    audio_format_t audioFormat = getValueFromVector<audio_format_t>(mFdp, kAudioFormats);
+    status_t ret = mManager->setDeviceConnectionState(
+        audioDevice, AUDIO_POLICY_DEVICE_STATE_AVAILABLE, "" /*address*/, "" /*name*/, audioFormat);
+    if (ret != NO_ERROR) {
+        return;
+    }
+    audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
+    audio_io_handle_t output;
+    audio_port_handle_t portId;
+    getOutputForAttr(&selectedDeviceId, getValueFromVector<audio_format_t>(mFdp, kAudioFormats),
+                     getValueFromVector<audio_channel_mask_t>(mFdp, kAudioChannelOutMasks),
+                     getValueFromVector<uint32_t>(mFdp, kSamplingRates), flags, &output, &portId);
+    sp<SwAudioOutputDescriptor> outDesc = mManager->getOutputs().valueFor(output);
+    if (outDesc.get() == nullptr) {
+        return;
+    }
+    audio_port_v7 port = {};
+    outDesc->toAudioPort(&port);
+    mManager->releaseOutput(portId);
+    mManager->setDeviceConnectionState(audioDevice, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
+                                       "" /*address*/, "" /*name*/, audioFormat);
+}
+
+void AudioPolicyManagerTVFuzzer::process() {
+    if (initialize()) {
+        testHDMIPortSelection(getValueFromVector<audio_output_flags_t>(mFdp, kAudioOutputFlags));
+        fuzzPatchCreation();
+    }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    if (size < 1) {
+        return 0;
+    }
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+    while (fdp.remaining_bytes() > 0) {
+        AudioPolicyManagerFuzzer audioPolicyManagerFuzzer(&fdp);
+        audioPolicyManagerFuzzer.process();
+
+        AudioPolicyManagerFuzzerMsd audioPolicyManagerFuzzerMsd(&fdp);
+        audioPolicyManagerFuzzerMsd.process();
+
+        AudioPolicyManagerFuzzerWithConfigurationFile audioPolicyManagerFuzzerWithConfigurationFile(
+            &fdp);
+        audioPolicyManagerFuzzerWithConfigurationFile.process();
+
+        AudioPolicyManagerFuzzerDynamicPolicy audioPolicyManagerFuzzerDynamicPolicy(&fdp);
+        audioPolicyManagerFuzzerDynamicPolicy.process();
+
+        AudioPolicyManagerFuzzerDPNoRemoteSubmixModule
+            audioPolicyManagerFuzzerDPNoRemoteSubmixModule(&fdp);
+        audioPolicyManagerFuzzerDPNoRemoteSubmixModule.process();
+
+        AudioPolicyManagerFuzzerDPPlaybackReRouting audioPolicyManagerFuzzerDPPlaybackReRouting(
+            &fdp);
+        audioPolicyManagerFuzzerDPPlaybackReRouting.process();
+
+        AudioPolicyManagerFuzzerDPMixRecordInjection audioPolicyManagerFuzzerDPMixRecordInjection(
+            &fdp);
+        audioPolicyManagerFuzzerDPMixRecordInjection.process();
+
+        AudioPolicyManagerFuzzerDeviceConnection audioPolicyManagerFuzzerDeviceConnection(&fdp);
+        audioPolicyManagerFuzzerDeviceConnection.process();
+
+        AudioPolicyManagerTVFuzzer audioPolicyManagerTVFuzzer(&fdp);
+        audioPolicyManagerTVFuzzer.process();
+    }
+    return 0;
+}
diff --git a/services/audiopolicy/fuzzer/resources/Android.bp b/services/audiopolicy/fuzzer/resources/Android.bp
new file mode 100644
index 0000000..f1e3a51
--- /dev/null
+++ b/services/audiopolicy/fuzzer/resources/Android.bp
@@ -0,0 +1,27 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************************/
+
+filegroup {
+    name: "audiopolicyfuzzer_configuration_files",
+    srcs: [
+        "test_audio_policy_configuration.xml",
+        "test_audio_policy_msd_configuration.xml",
+        "test_audio_policy_primary_only_configuration.xml",
+        "test_tv_apm_configuration.xml",
+    ],
+}
diff --git a/services/audiopolicy/fuzzer/resources/test_audio_policy_configuration.xml b/services/audiopolicy/fuzzer/resources/test_audio_policy_configuration.xml
new file mode 100644
index 0000000..7e26c33
--- /dev/null
+++ b/services/audiopolicy/fuzzer/resources/test_audio_policy_configuration.xml
@@ -0,0 +1,111 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Copyright (C) 2021 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<audioPolicyConfiguration version="1.0" xmlns:xi="http://www.w3.org/2001/XInclude">
+    <globalConfiguration speaker_drc_enabled="true"/>
+
+    <modules>
+        <!-- Primary module -->
+        <module name="primary" halVersion="2.0">
+            <attachedDevices>
+                <item>Speaker</item>
+                <item>Built-In Mic</item>
+            </attachedDevices>
+            <defaultOutputDevice>Speaker</defaultOutputDevice>
+            <mixPorts>
+                <mixPort name="primary output" role="source" flags="AUDIO_OUTPUT_FLAG_PRIMARY">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="primary input" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000"
+                             channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+                </mixPort>
+                <mixPort name="mixport_bt_hfp_output" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="mixport_bt_hfp_input" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000,11025,16000,44100,48000"
+                             channelMasks="AUDIO_CHANNEL_IN_STEREO,AUDIO_CHANNEL_IN_MONO"/>
+                </mixPort>
+            </mixPorts>
+            <devicePorts>
+                <devicePort tagName="Speaker" type="AUDIO_DEVICE_OUT_SPEAKER" role="sink">
+                </devicePort>
+                <devicePort tagName="Built-In Mic" type="AUDIO_DEVICE_IN_BUILTIN_MIC" role="source">
+                </devicePort>
+                <devicePort tagName="Hdmi" type="AUDIO_DEVICE_OUT_HDMI" role="sink">
+                </devicePort>
+                <devicePort tagName="Hdmi-In Mic" type="AUDIO_DEVICE_IN_HDMI" role="source">
+                </devicePort>
+                <devicePort tagName="BT SCO" type="AUDIO_DEVICE_OUT_BLUETOOTH_SCO"
+                            role="sink" address="hfp_client_out">
+                </devicePort>
+                <devicePort tagName="BT SCO Headset Mic" type="AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET"
+                            role="source" address="hfp_client_in">
+                </devicePort>
+            </devicePorts>
+            <routes>
+                <route type="mix" sink="Speaker"
+                       sources="primary output"/>
+                <route type="mix" sink="primary input"
+                       sources="Built-In Mic,Hdmi-In Mic"/>
+                <route type="mix" sink="Hdmi"
+                       sources="primary output"/>
+                <route type="mix" sink="BT SCO"
+                       sources="mixport_bt_hfp_output"/>
+                <route type="mix" sink="mixport_bt_hfp_input"
+                       sources="BT SCO Headset Mic"/>
+            </routes>
+        </module>
+
+        <!-- Remote Submix module -->
+        <module name="r_submix" halVersion="2.0">
+            <attachedDevices>
+                <item>Remote Submix In</item>
+            </attachedDevices>
+            <mixPorts>
+                <mixPort name="r_submix output" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="r_submix input" role="sink">
+                   <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+                </mixPort>
+           </mixPorts>
+           <devicePorts>
+               <devicePort tagName="Remote Submix Out" type="AUDIO_DEVICE_OUT_REMOTE_SUBMIX"  role="sink">
+                   <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+               </devicePort>
+               <devicePort tagName="Remote Submix In" type="AUDIO_DEVICE_IN_REMOTE_SUBMIX"  role="source">
+                   <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+                </devicePort>
+            </devicePorts>
+            <routes>
+                <route type="mix" sink="Remote Submix Out"
+                       sources="r_submix output"/>
+                <route type="mix" sink="r_submix input"
+                       sources="Remote Submix In"/>
+            </routes>
+        </module>
+    </modules>
+</audioPolicyConfiguration>
diff --git a/services/audiopolicy/fuzzer/resources/test_audio_policy_msd_configuration.xml b/services/audiopolicy/fuzzer/resources/test_audio_policy_msd_configuration.xml
new file mode 100644
index 0000000..5248d79
--- /dev/null
+++ b/services/audiopolicy/fuzzer/resources/test_audio_policy_msd_configuration.xml
@@ -0,0 +1,84 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Copyright (C) 2021 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<audioPolicyConfiguration version="1.0" xmlns:xi="http://www.w3.org/2001/XInclude">
+    <globalConfiguration speaker_drc_enabled="true"/>
+
+    <modules>
+        <module name="msd" halVersion="2.0">
+            <attachedDevices>
+                <item>MS12 Input</item>
+                <item>MS12 Output</item>
+            </attachedDevices>
+            <mixPorts>
+                <mixPort name="ms12 input" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="ms12 compressed input" role="source"
+                        flags="AUDIO_OUTPUT_FLAG_DIRECT|AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD|AUDIO_OUTPUT_FLAG_NON_BLOCKING">
+                    <profile name="" format="AUDIO_FORMAT_AC3"
+                             samplingRates="32000,44100,48000"
+                             channelMasks="AUDIO_CHANNEL_OUT_MONO|AUDIO_CHANNEL_OUT_STEREO|AUDIO_CHANNEL_OUT_5POINT1"/>
+                    <profile name="" format="AUDIO_FORMAT_E_AC3"
+                             samplingRates="32000,44100,48000"
+                             channelMasks="AUDIO_CHANNEL_OUT_MONO|AUDIO_CHANNEL_OUT_STEREO|AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"/>
+                    <profile name="" format="AUDIO_FORMAT_E_AC3_JOC"
+                             samplingRates="32000,44100,48000"
+                             channelMasks="AUDIO_CHANNEL_OUT_MONO|AUDIO_CHANNEL_OUT_STEREO|AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"/>
+                    <profile name="" format="AUDIO_FORMAT_AC4"
+                             samplingRates="32000,44100,48000"
+                             channelMasks="AUDIO_CHANNEL_OUT_MONO|AUDIO_CHANNEL_OUT_STEREO|AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"/>
+                </mixPort>
+                <!-- The HW AV Sync flag is not required, but is recommended -->
+                <mixPort name="ms12 output" role="sink" flags="AUDIO_INPUT_FLAG_HW_AV_SYNC|AUDIO_INPUT_FLAG_DIRECT">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+                    <profile name="" format="AUDIO_FORMAT_AC3"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_5POINT1"/>
+                    <profile name="" format="AUDIO_FORMAT_E_AC3"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_5POINT1"/>
+                </mixPort>
+           </mixPorts>
+           <devicePorts>
+               <devicePort tagName="MS12 Input" type="AUDIO_DEVICE_OUT_BUS"  role="sink">
+                   <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                   <profile name="" format="AUDIO_FORMAT_AC3"
+                            samplingRates="32000,44100,48000"
+                            channelMasks="AUDIO_CHANNEL_OUT_MONO|AUDIO_CHANNEL_OUT_STEREO|AUDIO_CHANNEL_OUT_5POINT1"/>
+                   <profile name="" format="AUDIO_FORMAT_E_AC3"
+                            samplingRates="32000,44100,48000"
+                            channelMasks="AUDIO_CHANNEL_OUT_MONO|AUDIO_CHANNEL_OUT_STEREO|AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"/>
+                    <profile name="" format="AUDIO_FORMAT_E_AC3_JOC"
+                             samplingRates="32000,44100,48000"
+                             channelMasks="AUDIO_CHANNEL_OUT_MONO|AUDIO_CHANNEL_OUT_STEREO|AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"/>
+                   <profile name="" format="AUDIO_FORMAT_AC4"
+                            samplingRates="32000,44100,48000"
+                            channelMasks="AUDIO_CHANNEL_OUT_MONO|AUDIO_CHANNEL_OUT_STEREO|AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"/>
+               </devicePort>
+               <devicePort tagName="MS12 Output" type="AUDIO_DEVICE_IN_BUS"  role="source">
+                   <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+                </devicePort>
+            </devicePorts>
+            <routes>
+                <route type="mix" sink="MS12 Input" sources="ms12 input,ms12 compressed input"/>
+                <route type="mix" sink="ms12 output" sources="MS12 Output"/>
+            </routes>
+        </module>
+    </modules>
+</audioPolicyConfiguration>
diff --git a/services/audiopolicy/fuzzer/resources/test_audio_policy_primary_only_configuration.xml b/services/audiopolicy/fuzzer/resources/test_audio_policy_primary_only_configuration.xml
new file mode 100644
index 0000000..15e3773
--- /dev/null
+++ b/services/audiopolicy/fuzzer/resources/test_audio_policy_primary_only_configuration.xml
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Copyright (C) 2021 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<audioPolicyConfiguration version="1.0" xmlns:xi="http://www.w3.org/2001/XInclude">
+    <globalConfiguration speaker_drc_enabled="true"/>
+
+    <modules>
+        <!-- Primary module -->
+        <module name="primary" halVersion="2.0">
+            <attachedDevices>
+                <item>Speaker</item>
+                <item>Built-In Mic</item>
+            </attachedDevices>
+            <defaultOutputDevice>Speaker</defaultOutputDevice>
+            <mixPorts>
+                <mixPort name="primary output" role="source" flags="AUDIO_OUTPUT_FLAG_PRIMARY">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="primary input" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000"
+                             channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+                </mixPort>
+            </mixPorts>
+            <devicePorts>
+                <devicePort tagName="Speaker" type="AUDIO_DEVICE_OUT_SPEAKER" role="sink">
+                </devicePort>
+                <devicePort tagName="Built-In Mic" type="AUDIO_DEVICE_IN_BUILTIN_MIC" role="source">
+                </devicePort>
+            </devicePorts>
+            <routes>
+                <route type="mix" sink="Speaker"
+                       sources="primary output"/>
+                <route type="mix" sink="primary input"
+                       sources="Built-In Mic"/>
+            </routes>
+        </module>
+    </modules>
+</audioPolicyConfiguration>
diff --git a/services/audiopolicy/fuzzer/resources/test_tv_apm_configuration.xml b/services/audiopolicy/fuzzer/resources/test_tv_apm_configuration.xml
new file mode 100644
index 0000000..658d3ce
--- /dev/null
+++ b/services/audiopolicy/fuzzer/resources/test_tv_apm_configuration.xml
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Copyright (C) 2021 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<audioPolicyConfiguration version="1.0" xmlns:xi="http://www.w3.org/2001/XInclude">
+    <globalConfiguration speaker_drc_enabled="false"/>
+    <modules>
+        <module name="primary" halVersion="2.0">
+            <attachedDevices>
+                <item>Speaker</item>
+            </attachedDevices>
+            <defaultOutputDevice>Speaker</defaultOutputDevice>
+            <mixPorts>
+                <!-- Profiles on the HDMI port are explicit for simplicity. In reality they are dynamic -->
+                <!-- Note: ports are intentionally arranged from more specific to less
+                     specific in order to test b/140447125 for HW AV Sync, and similar "explicit matches" -->
+                <mixPort name="tunnel" role="source"
+                         flags="AUDIO_OUTPUT_FLAG_DIRECT|AUDIO_OUTPUT_FLAG_HW_AV_SYNC">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="low latency" role="source"
+                         flags="AUDIO_OUTPUT_FLAG_DIRECT|AUDIO_OUTPUT_FLAG_MMAP_NOIRQ">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="direct" role="source" flags="AUDIO_OUTPUT_FLAG_DIRECT">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="primary output" role="source" flags="AUDIO_OUTPUT_FLAG_PRIMARY">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+           </mixPorts>
+           <devicePorts>
+                <devicePort tagName="Speaker" type="AUDIO_DEVICE_OUT_SPEAKER" role="sink" />
+                <devicePort tagName="Out Aux Digital" type="AUDIO_DEVICE_OUT_AUX_DIGITAL" role="sink" />
+            </devicePorts>
+            <routes>
+                <route type="mix" sink="Speaker" sources="primary output"/>
+                <route type="mix" sink="Out Aux Digital" sources="primary output,tunnel,direct,low latency"/>
+            </routes>
+        </module>
+    </modules>
+</audioPolicyConfiguration>
diff --git a/services/audiopolicy/manager/Android.bp b/services/audiopolicy/manager/Android.bp
deleted file mode 100644
index 5bb432f..0000000
--- a/services/audiopolicy/manager/Android.bp
+++ /dev/null
@@ -1,32 +0,0 @@
-cc_library_shared {
-    name: "libaudiopolicymanager",
-
-    srcs: [
-        "AudioPolicyFactory.cpp",
-    ],
-
-    include_dirs: [
-        "frameworks/av/services/audioflinger"
-    ],
-
-    shared_libs: [
-        "libaudiopolicymanagerdefault",
-    ],
-
-    static_libs: [
-        "libaudiopolicycomponents",
-    ],
-
-    header_libs: [
-        "libaudiopolicycommon",
-        "libaudiopolicyengine_interface_headers",
-        "libaudiopolicymanager_interface_headers",
-        "libaudioutils_headers",
-    ],
-
-    cflags: [
-        "-Werror",
-        "-Wall",
-    ],
-
-}
diff --git a/services/audiopolicy/manager/AudioPolicyFactory.cpp b/services/audiopolicy/manager/AudioPolicyFactory.cpp
deleted file mode 100644
index 476a1ec..0000000
--- a/services/audiopolicy/manager/AudioPolicyFactory.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <AudioPolicyManager.h>
-
-namespace android {
-
-extern "C" AudioPolicyInterface* createAudioPolicyManager(
-        AudioPolicyClientInterface *clientInterface)
-{
-    AudioPolicyManager *apm = new AudioPolicyManager(clientInterface);
-    status_t status = apm->initialize();
-    if (status != NO_ERROR) {
-        delete apm;
-        apm = nullptr;
-    }
-    return apm;
-}
-
-extern "C" void destroyAudioPolicyManager(AudioPolicyInterface *interface)
-{
-    delete interface;
-}
-
-} // namespace android
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index e721a78..340eca4 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -272,7 +272,8 @@
                 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
         for (size_t i = 0; i < mOutputs.size(); i++) {
             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
-            if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
+            if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
+                (desc != mPrimaryOutput))) {
                 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
                 // do not force device change on duplicated output because if device is 0, it will
                 // also force a device 0 for the two outputs it is duplicated to which may override
@@ -3303,6 +3304,11 @@
 
 void AudioPolicyManager::updateInputRouting() {
     for (const auto& activeDesc : mInputs.getActiveInputs()) {
+        // Skip for hotword recording as the input device switch
+        // is handled within sound trigger HAL
+        if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
+            continue;
+        }
         auto newDevice = getNewInputDevice(activeDesc);
         // Force new input selection if the new device can not be reached via current input
         if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
@@ -5720,13 +5726,27 @@
     for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
         StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
         auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
+        auto hasStreamActive = [&](auto stream) {
+            return hasStream(streams, stream) && isStreamActive(stream, 0);
+        };
 
-        if ((hasVoiceStream(streams) &&
-             (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
-             !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
-             ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
-                mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
-                outputDesc->isStrategyActive(productStrategy)) {
+        auto doGetOutputDevicesForVoice = [&]() {
+            return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
+                outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
+                (isInCall() ||
+                 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
+        };
+
+        // With low-latency playing on speaker, music on WFD, when the first low-latency
+        // output is stopped, getNewOutputDevices checks for a product strategy
+        // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
+        // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
+        // devices are returned for STRATEGY_SONIFICATION without checking whether the
+        // stream is associated to the output descriptor.
+        if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
+               ((hasStreamActive(AUDIO_STREAM_ALARM) ||
+                hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
+                mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
             // Retrieval of devices for voice DL is done on primary output profile, cannot
             // check the route (would force modifying configuration file for this profile)
             devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
diff --git a/services/audiopolicy/service/Android.bp b/services/audiopolicy/service/Android.bp
index 8cb1b59..d4f5088 100644
--- a/services/audiopolicy/service/Android.bp
+++ b/services/audiopolicy/service/Android.bp
@@ -18,7 +18,7 @@
         "libaudioclient_aidl_conversion",
         "libaudiofoundation",
         "libaudiopolicy",
-        "libaudiopolicymanager",
+        "libaudiopolicymanagerdefault",
         "libaudioutils",
         "libbinder",
         "libcutils",
@@ -30,11 +30,11 @@
         "libmediautils",
         "libsensorprivacy",
         "libutils",
-        "audioclient-types-aidl-unstable-cpp",
-        "audioflinger-aidl-unstable-cpp",
-        "audiopolicy-aidl-unstable-cpp",
-        "audiopolicy-types-aidl-unstable-cpp",
-        "capture_state_listener-aidl-unstable-cpp",
+        "audioclient-types-aidl-cpp",
+        "audioflinger-aidl-cpp",
+        "audiopolicy-aidl-cpp",
+        "audiopolicy-types-aidl-cpp",
+        "capture_state_listener-aidl-cpp",
     ],
 
     static_libs: [
diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp
index 12335d9..90ad81e 100644
--- a/services/audiopolicy/service/AudioPolicyService.cpp
+++ b/services/audiopolicy/service/AudioPolicyService.cpp
@@ -23,6 +23,7 @@
 #define __STDC_LIMIT_MACROS
 #include <stdint.h>
 #include <sys/time.h>
+#include <dlfcn.h>
 
 #include <audio_utils/clock.h>
 #include <binder/IServiceManager.h>
@@ -44,12 +45,14 @@
 
 #include <system/audio.h>
 #include <system/audio_policy.h>
+#include <AudioPolicyManager.h>
 
 namespace android {
 using binder::Status;
 
 static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
 static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
+static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
 
 static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
 
@@ -59,12 +62,54 @@
 
 // ----------------------------------------------------------------------------
 
+static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
+{
+    AudioPolicyManager *apm = new AudioPolicyManager(clientInterface);
+    status_t status = apm->initialize();
+    if (status != NO_ERROR) {
+        delete apm;
+        apm = nullptr;
+    }
+    return apm;
+}
+
+static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
+{
+    delete interface;
+}
+// ----------------------------------------------------------------------------
+
 AudioPolicyService::AudioPolicyService()
     : BnAudioPolicyService(),
       mAudioPolicyManager(NULL),
       mAudioPolicyClient(NULL),
       mPhoneState(AUDIO_MODE_INVALID),
-      mCaptureStateNotifier(false) {
+      mCaptureStateNotifier(false),
+      mCreateAudioPolicyManager(createAudioPolicyManager),
+      mDestroyAudioPolicyManager(destroyAudioPolicyManager) {
+}
+
+void AudioPolicyService::loadAudioPolicyManager()
+{
+    mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
+    if (mLibraryHandle != nullptr) {
+        ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
+        mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
+                                            (dlsym(mLibraryHandle, "createAudioPolicyManager"));
+        const char *lastError = dlerror();
+        ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
+                    __func__, lastError != nullptr ? lastError : "no error");
+
+        mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
+                                        dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
+        lastError = dlerror();
+        ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
+                    __func__, lastError != nullptr ? lastError : "no error");
+        if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
+            unloadAudioPolicyManager();
+            LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
+        }
+    }
 }
 
 void AudioPolicyService::onFirstRef()
@@ -78,7 +123,9 @@
         mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
 
         mAudioPolicyClient = new AudioPolicyClient(this);
-        mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);
+
+        loadAudioPolicyManager();
+        mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
     }
     // load audio processing modules
     sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
@@ -94,12 +141,25 @@
     sensorPrivacyPolicy->registerSelf();
 }
 
+void AudioPolicyService::unloadAudioPolicyManager()
+{
+    ALOGV("%s ", __func__);
+    if (mLibraryHandle != nullptr) {
+        dlclose(mLibraryHandle);
+    }
+    mLibraryHandle = nullptr;
+    mCreateAudioPolicyManager = nullptr;
+    mDestroyAudioPolicyManager = nullptr;
+}
+
 AudioPolicyService::~AudioPolicyService()
 {
     mAudioCommandThread->exit();
     mOutputCommandThread->exit();
 
-    destroyAudioPolicyManager(mAudioPolicyManager);
+    mDestroyAudioPolicyManager(mAudioPolicyManager);
+    unloadAudioPolicyManager();
+
     delete mAudioPolicyClient;
 
     mNotificationClients.clear();
diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h
index 110beca..149a858 100644
--- a/services/audiopolicy/service/AudioPolicyService.h
+++ b/services/audiopolicy/service/AudioPolicyService.h
@@ -38,7 +38,6 @@
 #include "CaptureStateNotifier.h"
 #include <AudioPolicyInterface.h>
 #include <android/hardware/BnSensorPrivacyListener.h>
-
 #include <unordered_map>
 
 namespace android {
@@ -861,7 +860,8 @@
 
     // Internal dump utilities.
     status_t dumpPermissionDenial(int fd);
-
+    void loadAudioPolicyManager();
+    void unloadAudioPolicyManager();
 
     mutable Mutex mLock;    // prevents concurrent access to AudioPolicy manager functions changing
                             // device connection state  or routing
@@ -896,6 +896,10 @@
 
     CaptureStateNotifier mCaptureStateNotifier;
 
+    void *mLibraryHandle = nullptr;
+    CreateAudioPolicyManagerInstance mCreateAudioPolicyManager;
+    DestroyAudioPolicyManagerInstance mDestroyAudioPolicyManager;
+
     std::map<userid_t, sp<SensorPrivacyPolicy>> mMicrophoneSensorPrivacyPolicies;
 };
 
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index 464e67f..641e463 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -3249,8 +3249,8 @@
     }
 
     mRegistered = true;
-    isIndividual = true;
-    this->userId = userId;
+    mIsIndividual = true;
+    mUserId = userId;
     ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
     return OK;
 }
@@ -3276,8 +3276,8 @@
     // if sensor privacy is enabled then block all clients from accessing the camera
     sp<CameraService> service = mService.promote();
     if (service != nullptr) {
-        if (isIndividual) {
-            service->setMuteForAllClients(userId, enabled);
+        if (mIsIndividual) {
+            service->setMuteForAllClients(mUserId, enabled);
         } else {
             if (enabled) {
                 service->blockAllClients();
diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h
index f455cbb..dbfc6c3 100644
--- a/services/camera/libcameraservice/CameraService.h
+++ b/services/camera/libcameraservice/CameraService.h
@@ -637,7 +637,8 @@
             public virtual IBinder::DeathRecipient {
         public:
             explicit SensorPrivacyPolicy(wp<CameraService> service)
-                    : mService(service), mSensorPrivacyEnabled(false), mRegistered(false) {}
+                    : mService(service), mSensorPrivacyEnabled(false), mRegistered(false),
+                      mIsIndividual(false), mUserId(0) {}
 
             void registerSelf();
             status_t registerSelfForIndividual(int userId);
@@ -656,8 +657,8 @@
             Mutex mSensorPrivacyLock;
             bool mSensorPrivacyEnabled;
             bool mRegistered;
-            bool isIndividual;
-            userid_t userId;
+            bool mIsIndividual;
+            userid_t mUserId;
     };
 
     sp<UidPolicy> mUidPolicy;
diff --git a/services/camera/libcameraservice/api1/Camera2Client.cpp b/services/camera/libcameraservice/api1/Camera2Client.cpp
index 1c9e9cf..31cfed6 100644
--- a/services/camera/libcameraservice/api1/Camera2Client.cpp
+++ b/services/camera/libcameraservice/api1/Camera2Client.cpp
@@ -935,6 +935,7 @@
         return res;
     }
 
+    mCallbackProcessor->unpauseCallback();
     params.state = Parameters::PREVIEW;
     return OK;
 }
@@ -969,6 +970,7 @@
             FALLTHROUGH_INTENDED;
         case Parameters::RECORD:
         case Parameters::PREVIEW:
+            mCallbackProcessor->pauseCallback();
             syncWithDevice();
             // Due to flush a camera device sync is not a sufficient
             // guarantee that the current client parameters are
diff --git a/services/camera/libcameraservice/api1/client2/CallbackProcessor.cpp b/services/camera/libcameraservice/api1/client2/CallbackProcessor.cpp
index 744aaee..4c3ded6 100644
--- a/services/camera/libcameraservice/api1/client2/CallbackProcessor.cpp
+++ b/services/camera/libcameraservice/api1/client2/CallbackProcessor.cpp
@@ -39,6 +39,7 @@
         mDevice(client->getCameraDevice()),
         mId(client->getCameraId()),
         mCallbackAvailable(false),
+        mCallbackPaused(true),
         mCallbackToApp(false),
         mCallbackStreamId(NO_STREAM) {
 }
@@ -216,6 +217,14 @@
     return mCallbackStreamId;
 }
 
+void CallbackProcessor::unpauseCallback() {
+    mCallbackPaused = false;
+}
+
+void CallbackProcessor::pauseCallback() {
+    mCallbackPaused = true;
+}
+
 void CallbackProcessor::dump(int /*fd*/, const Vector<String16>& /*args*/) const {
 }
 
@@ -234,7 +243,7 @@
 
     do {
         sp<Camera2Client> client = mClient.promote();
-        if (client == 0) {
+        if (client == 0 || mCallbackPaused) {
             res = discardNewCallback();
         } else {
             res = processNewCallback(client);
diff --git a/services/camera/libcameraservice/api1/client2/CallbackProcessor.h b/services/camera/libcameraservice/api1/client2/CallbackProcessor.h
index 5231688..a336326 100644
--- a/services/camera/libcameraservice/api1/client2/CallbackProcessor.h
+++ b/services/camera/libcameraservice/api1/client2/CallbackProcessor.h
@@ -17,6 +17,8 @@
 #ifndef ANDROID_SERVERS_CAMERA_CAMERA2_CALLBACKPROCESSOR_H
 #define ANDROID_SERVERS_CAMERA_CAMERA2_CALLBACKPROCESSOR_H
 
+#include <atomic>
+
 #include <utils/Thread.h>
 #include <utils/String16.h>
 #include <utils/Vector.h>
@@ -52,6 +54,9 @@
     status_t deleteStream();
     int getStreamId() const;
 
+    void unpauseCallback();
+    void pauseCallback();
+
     void dump(int fd, const Vector<String16>& args) const;
   private:
     static const nsecs_t kWaitDuration = 10000000; // 10 ms
@@ -67,6 +72,8 @@
         NO_STREAM = -1
     };
 
+    std::atomic<bool> mCallbackPaused;
+
     // True if mCallbackWindow is a remote consumer, false if just the local
     // mCallbackConsumer
     bool mCallbackToApp;
diff --git a/services/mediaresourcemanager/Android.bp b/services/mediaresourcemanager/Android.bp
index 83a139b..cb69aa0 100644
--- a/services/mediaresourcemanager/Android.bp
+++ b/services/mediaresourcemanager/Android.bp
@@ -77,7 +77,7 @@
     ],
 
     static_libs: [
-        "resourceobserver_aidl_interface-ndk_platform",
+        "resourceobserver_aidl_interface-V1-ndk_platform",
     ],
 
     include_dirs: ["frameworks/av/include"],
diff --git a/services/mediaresourcemanager/test/Android.bp b/services/mediaresourcemanager/test/Android.bp
index 308ee91..ad70a35 100644
--- a/services/mediaresourcemanager/test/Android.bp
+++ b/services/mediaresourcemanager/test/Android.bp
@@ -47,7 +47,7 @@
     test_suites: ["device-tests"],
     static_libs: [
         "libresourcemanagerservice",
-        "resourceobserver_aidl_interface-ndk_platform",
+        "resourceobserver_aidl_interface-V1-ndk_platform",
     ],
     shared_libs: [
         "libbinder",
diff --git a/services/tuner/Android.bp b/services/tuner/Android.bp
index 1cb3037..caa3474 100644
--- a/services/tuner/Android.bp
+++ b/services/tuner/Android.bp
@@ -85,7 +85,7 @@
     ],
 
     static_libs: [
-        "android.hardware.common.fmq-unstable-ndk_platform",
+        "android.hardware.common.fmq-V1-ndk_platform",
         "libaidlcommonsupport",
     ],
 
@@ -111,6 +111,7 @@
 
     shared_libs: [
         "android.hardware.tv.tuner@1.0",
+        "android.hardware.tv.tuner@1.1",
         "libbase",
         "libbinder",
         "libfmq",
diff --git a/services/tuner/TunerDemux.cpp b/services/tuner/TunerDemux.cpp
index 1f8b70d..8346992 100644
--- a/services/tuner/TunerDemux.cpp
+++ b/services/tuner/TunerDemux.cpp
@@ -18,6 +18,7 @@
 
 #include "TunerDvr.h"
 #include "TunerDemux.h"
+#include "TunerTimeFilter.h"
 
 using ::android::hardware::tv::tuner::V1_0::DemuxAlpFilterType;
 using ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType;
@@ -97,7 +98,70 @@
         return Status::fromServiceSpecificError(static_cast<int32_t>(status));
     }
 
-    *_aidl_return = ::ndk::SharedRefBase::make<TunerFilter>(filterSp, cbSp);
+    *_aidl_return = ::ndk::SharedRefBase::make<TunerFilter>(filterSp, cbSp, type, subType);
+    return Status::ok();
+}
+
+Status TunerDemux::openTimeFilter(shared_ptr<ITunerTimeFilter>* _aidl_return) {
+    if (mDemux == nullptr) {
+        ALOGE("IDemux is not initialized.");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result status;
+    sp<ITimeFilter> filterSp;
+    mDemux->openTimeFilter([&](Result r, const sp<ITimeFilter>& filter) {
+        filterSp = filter;
+        status = r;
+    });
+    if (status != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(status));
+    }
+
+    *_aidl_return = ::ndk::SharedRefBase::make<TunerTimeFilter>(filterSp);
+    return Status::ok();
+}
+
+Status TunerDemux::getAvSyncHwId(const shared_ptr<ITunerFilter>& tunerFilter, int* _aidl_return) {
+    if (mDemux == nullptr) {
+        ALOGE("IDemux is not initialized.");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    uint32_t avSyncHwId;
+    Result res;
+    sp<IFilter> halFilter = static_cast<TunerFilter*>(tunerFilter.get())->getHalFilter();
+    mDemux->getAvSyncHwId(halFilter,
+            [&](Result r, uint32_t id) {
+                res = r;
+                avSyncHwId = id;
+            });
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+
+    *_aidl_return = (int)avSyncHwId;
+    return Status::ok();
+}
+
+Status TunerDemux::getAvSyncTime(int avSyncHwId, int64_t* _aidl_return) {
+    if (mDemux == nullptr) {
+        ALOGE("IDemux is not initialized.");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    uint64_t time;
+    Result res;
+    mDemux->getAvSyncTime(static_cast<uint32_t>(avSyncHwId),
+            [&](Result r, uint64_t ts) {
+                res = r;
+                time = ts;
+            });
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+
+    *_aidl_return = (int64_t)time;
     return Status::ok();
 }
 
@@ -125,6 +189,32 @@
     return Status::ok();
 }
 
+Status TunerDemux::connectCiCam(int ciCamId) {
+    if (mDemux == nullptr) {
+        ALOGE("IDemux is not initialized.");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res = mDemux->connectCiCam(static_cast<uint32_t>(ciCamId));
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
+Status TunerDemux::disconnectCiCam() {
+    if (mDemux == nullptr) {
+        ALOGE("IDemux is not initialized.");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res = mDemux->disconnectCiCam();
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
 Status TunerDemux::close() {
     if (mDemux == nullptr) {
         ALOGE("IDemux is not initialized.");
diff --git a/services/tuner/TunerDemux.h b/services/tuner/TunerDemux.h
index 594fd66..2a9836b 100644
--- a/services/tuner/TunerDemux.h
+++ b/services/tuner/TunerDemux.h
@@ -27,9 +27,11 @@
 using ::aidl::android::media::tv::tuner::ITunerFilter;
 using ::aidl::android::media::tv::tuner::ITunerFilterCallback;
 using ::aidl::android::media::tv::tuner::ITunerFrontend;
+using ::aidl::android::media::tv::tuner::ITunerTimeFilter;
 using ::android::hardware::tv::tuner::V1_0::IDemux;
 using ::android::hardware::tv::tuner::V1_0::IDvr;
 using ::android::hardware::tv::tuner::V1_0::IDvrCallback;
+using ::android::hardware::tv::tuner::V1_0::ITimeFilter;
 
 using namespace std;
 
@@ -43,12 +45,19 @@
     Status setFrontendDataSource(const shared_ptr<ITunerFrontend>& frontend) override;
     Status openFilter(
         int mainType, int subtype, int bufferSize, const shared_ptr<ITunerFilterCallback>& cb,
-        shared_ptr<ITunerFilter>* _aidl_return);
+        shared_ptr<ITunerFilter>* _aidl_return) override;
+    Status openTimeFilter(shared_ptr<ITunerTimeFilter>* _aidl_return) override;
+    Status getAvSyncHwId(const shared_ptr<ITunerFilter>& tunerFilter, int* _aidl_return) override;
+    Status getAvSyncTime(int avSyncHwId, int64_t* _aidl_return) override;
     Status openDvr(
         int dvbType, int bufferSize, const shared_ptr<ITunerDvrCallback>& cb,
         shared_ptr<ITunerDvr>* _aidl_return) override;
+    Status connectCiCam(int ciCamId) override;
+    Status disconnectCiCam() override;
     Status close() override;
 
+    int getId() { return mDemuxId; }
+
 private:
     sp<IDemux> mDemux;
     int mDemuxId;
diff --git a/services/tuner/TunerDescrambler.cpp b/services/tuner/TunerDescrambler.cpp
new file mode 100644
index 0000000..6b2889d
--- /dev/null
+++ b/services/tuner/TunerDescrambler.cpp
@@ -0,0 +1,120 @@
+/**
+ * Copyright 2021, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "TunerDescrambler"
+
+#include "TunerFilter.h"
+#include "TunerDemux.h"
+#include "TunerDescrambler.h"
+
+using ::android::hardware::tv::tuner::V1_0::Result;
+
+using namespace std;
+
+namespace android {
+
+TunerDescrambler::TunerDescrambler(sp<IDescrambler> descrambler) {
+    mDescrambler = descrambler;
+}
+
+TunerDescrambler::~TunerDescrambler() {
+    mDescrambler = nullptr;
+}
+
+Status TunerDescrambler::setDemuxSource(const std::shared_ptr<ITunerDemux>& demux) {
+    if (mDescrambler == nullptr) {
+        ALOGE("IDescrambler is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res = mDescrambler->setDemuxSource(static_cast<TunerDemux*>(demux.get())->getId());
+    if (res != Result::SUCCESS) {
+        return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
+Status TunerDescrambler::setKeyToken(const vector<uint8_t>& keyToken) {
+    if (mDescrambler == nullptr) {
+        ALOGE("IDescrambler is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res = mDescrambler->setKeyToken(keyToken);
+    if (res != Result::SUCCESS) {
+        return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
+Status TunerDescrambler::addPid(const TunerDemuxPid& pid,
+        const shared_ptr<ITunerFilter>& optionalSourceFilter) {
+    if (mDescrambler == nullptr) {
+        ALOGE("IDescrambler is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res = mDescrambler->addPid(getHidlDemuxPid(pid),
+            static_cast<TunerFilter*>(optionalSourceFilter.get())->getHalFilter());
+    if (res != Result::SUCCESS) {
+        return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
+Status TunerDescrambler::removePid(const TunerDemuxPid& pid,
+        const shared_ptr<ITunerFilter>& optionalSourceFilter) {
+    if (mDescrambler == nullptr) {
+        ALOGE("IDescrambler is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res = mDescrambler->removePid(getHidlDemuxPid(pid),
+            static_cast<TunerFilter*>(optionalSourceFilter.get())->getHalFilter());
+    if (res != Result::SUCCESS) {
+        return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
+Status TunerDescrambler::close() {
+    if (mDescrambler == nullptr) {
+        ALOGE("IDescrambler is not initialized.");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res = mDescrambler->close();
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
+DemuxPid TunerDescrambler::getHidlDemuxPid(const TunerDemuxPid& pid) {
+    DemuxPid hidlPid;
+    switch (pid.getTag()) {
+        case TunerDemuxPid::tPid: {
+            hidlPid.tPid((uint16_t)pid.tPid);
+            break;
+        }
+        case TunerDemuxPid::mmtpPid: {
+            hidlPid.mmtpPid((uint16_t)pid.mmtpPid);
+            break;
+        }
+    }
+    return hidlPid;
+}
+}  // namespace android
diff --git a/services/tuner/TunerDescrambler.h b/services/tuner/TunerDescrambler.h
new file mode 100644
index 0000000..1970fb7
--- /dev/null
+++ b/services/tuner/TunerDescrambler.h
@@ -0,0 +1,54 @@
+/**
+ * Copyright 2021, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_MEDIA_TUNERDESCRAMBLER_H
+#define ANDROID_MEDIA_TUNERDESCRAMBLER_H
+
+#include <aidl/android/media/tv/tuner/BnTunerDescrambler.h>
+#include <android/hardware/tv/tuner/1.0/ITuner.h>
+
+using Status = ::ndk::ScopedAStatus;
+using ::aidl::android::media::tv::tuner::BnTunerDescrambler;
+using ::aidl::android::media::tv::tuner::ITunerDemux;
+using ::aidl::android::media::tv::tuner::ITunerFilter;
+using ::aidl::android::media::tv::tuner::TunerDemuxPid;
+using ::android::hardware::tv::tuner::V1_0::DemuxPid;
+using ::android::hardware::tv::tuner::V1_0::IDescrambler;
+
+namespace android {
+
+class TunerDescrambler : public BnTunerDescrambler {
+
+public:
+    TunerDescrambler(sp<IDescrambler> descrambler);
+    virtual ~TunerDescrambler();
+    Status setDemuxSource(const shared_ptr<ITunerDemux>& demux) override;
+    Status setKeyToken(const vector<uint8_t>& keyToken) override;
+    Status addPid(const TunerDemuxPid& pid,
+            const shared_ptr<ITunerFilter>& optionalSourceFilter) override;
+    Status removePid(const TunerDemuxPid& pid,
+            const shared_ptr<ITunerFilter>& optionalSourceFilter) override;
+    Status close() override;
+
+private:
+    DemuxPid getHidlDemuxPid(const TunerDemuxPid& pid);
+
+    sp<IDescrambler> mDescrambler;
+};
+
+} // namespace android
+
+#endif // ANDROID_MEDIA_TUNERDESCRAMBLER_H
diff --git a/services/tuner/TunerFilter.cpp b/services/tuner/TunerFilter.cpp
index b712348..af5a600 100644
--- a/services/tuner/TunerFilter.cpp
+++ b/services/tuner/TunerFilter.cpp
@@ -30,17 +30,21 @@
 using ::android::hardware::tv::tuner::V1_0::DemuxStreamId;
 using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterType;
 using ::android::hardware::tv::tuner::V1_0::Result;
+using ::android::hardware::tv::tuner::V1_1::AudioStreamType;
 using ::android::hardware::tv::tuner::V1_1::Constant;
+using ::android::hardware::tv::tuner::V1_1::VideoStreamType;
 
 namespace android {
 
 using namespace std;
 
 TunerFilter::TunerFilter(
-        sp<IFilter> filter, sp<IFilterCallback> callback) {
+        sp<IFilter> filter, sp<IFilterCallback> callback, int mainType, int subType) {
     mFilter = filter;
     mFilter_1_1 = ::android::hardware::tv::tuner::V1_1::IFilter::castFrom(filter);
     mFilterCallback = callback;
+    mMainType = mainType;
+    mSubType = subType;
 }
 
 TunerFilter::~TunerFilter() {
@@ -49,6 +53,29 @@
     mFilterCallback = nullptr;
 }
 
+Status TunerFilter::getQueueDesc(AidlMQDesc* _aidl_return) {
+    if (mFilter == NULL) {
+        ALOGE("IFilter is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    MQDesc dvrMQDesc;
+    Result res;
+    mFilter->getQueueDesc([&](Result r, const MQDesc& desc) {
+        dvrMQDesc = desc;
+        res = r;
+    });
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+
+    AidlMQDesc aidlMQDesc;
+    unsafeHidlToAidlMQDescriptor<uint8_t, int8_t, SynchronizedReadWrite>(
+                dvrMQDesc,  &aidlMQDesc);
+    *_aidl_return = move(aidlMQDesc);
+    return Status::ok();
+}
+
 Status TunerFilter::getId(int32_t* _aidl_return) {
     if (mFilter == nullptr) {
         ALOGE("IFilter is not initialized");
@@ -122,6 +149,65 @@
     return Status::ok();
 }
 
+Status TunerFilter::configureMonitorEvent(int monitorEventType) {
+    if (mFilter_1_1 == nullptr) {
+        ALOGE("IFilter_1_1 is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res = mFilter_1_1->configureMonitorEvent(monitorEventType);
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
+Status TunerFilter::configureIpFilterContextId(int cid) {
+    if (mFilter_1_1 == nullptr) {
+        ALOGE("IFilter_1_1 is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res = mFilter_1_1->configureIpCid(cid);
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
+Status TunerFilter::configureAvStreamType(int avStreamType) {
+    if (mFilter_1_1 == nullptr) {
+        ALOGE("IFilter_1_1 is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    AvStreamType type;
+    if (!getHidlAvStreamType(avStreamType, type)) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::INVALID_STATE));
+    }
+
+    Result res = mFilter_1_1->configureAvStreamType(type);
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
+Status TunerFilter::setDataSource(const shared_ptr<ITunerFilter>& filter) {
+    if (mFilter == nullptr) {
+        ALOGE("IFilter is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    ITunerFilter* tunerFilter = filter.get();
+    sp<IFilter> hidlFilter = static_cast<TunerFilter*>(tunerFilter)->getHalFilter();
+    Result res = mFilter->setDataSource(hidlFilter);
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+    return Status::ok();
+}
+
 void TunerFilter::getHidlTsSettings(
         const TunerFilterConfiguration& config, DemuxFilterSettings& settings) {
     auto tsConf = config.get<TunerFilterConfiguration::ts>();
@@ -311,12 +397,9 @@
     switch (s.condition.getTag()) {
         case TunerFilterSectionCondition::sectionBits: {
             auto sectionBits = s.condition.get<TunerFilterSectionCondition::sectionBits>();
-            vector<uint8_t> filter(sectionBits.filter.size());
-            vector<uint8_t> mask(sectionBits.mask.size());
-            vector<uint8_t> mode(sectionBits.mode.size());
-            copy(sectionBits.filter.begin(), sectionBits.filter.end(), filter.begin());
-            copy(sectionBits.mask.begin(), sectionBits.mask.end(), mask.begin());
-            copy(sectionBits.mode.begin(), sectionBits.mode.end(), mode.begin());
+            vector<uint8_t> filter(sectionBits.filter.begin(), sectionBits.filter.end());
+            vector<uint8_t> mask(sectionBits.mask.begin(), sectionBits.mask.end());
+            vector<uint8_t> mode(sectionBits.mode.begin(), sectionBits.mode.end());
             section.condition.sectionBits({
                 .filter = filter,
                 .mask = mask,
@@ -468,6 +551,34 @@
     return mFilter;
 }
 
+bool TunerFilter::isAudioFilter() {
+    return (mMainType == (int)DemuxFilterMainType::TS
+                    && mSubType == (int)DemuxTsFilterType::AUDIO)
+            || (mMainType == (int)DemuxFilterMainType::MMTP
+                    && mSubType == (int)DemuxMmtpFilterType::AUDIO);
+}
+
+bool TunerFilter::isVideoFilter() {
+    return (mMainType == (int)DemuxFilterMainType::TS
+                    && mSubType == (int)DemuxTsFilterType::VIDEO)
+            || (mMainType == (int)DemuxFilterMainType::MMTP
+                    && mSubType == (int)DemuxMmtpFilterType::VIDEO);
+}
+
+bool TunerFilter::getHidlAvStreamType(int avStreamType, AvStreamType& type) {
+    if (isAudioFilter()) {
+        type.audio(static_cast<AudioStreamType>(avStreamType));
+        return true;
+    }
+
+    if (isVideoFilter()) {
+        type.video(static_cast<VideoStreamType>(avStreamType));
+        return true;
+    }
+
+    return false;
+}
+
 /////////////// FilterCallback ///////////////////////
 
 Return<void> TunerFilter::FilterCallback::onFilterStatus(DemuxFilterStatus status) {
diff --git a/services/tuner/TunerFilter.h b/services/tuner/TunerFilter.h
index 0055b53..d12b7ac 100644
--- a/services/tuner/TunerFilter.h
+++ b/services/tuner/TunerFilter.h
@@ -25,8 +25,12 @@
 #include <android/hardware/tv/tuner/1.1/IFilterCallback.h>
 #include <android/hardware/tv/tuner/1.1/types.h>
 #include <media/stagefright/foundation/ADebug.h>
+#include <fmq/ConvertMQDescriptors.h>
+#include <fmq/MessageQueue.h>
 
 using Status = ::ndk::ScopedAStatus;
+using ::aidl::android::hardware::common::fmq::MQDescriptor;
+using ::aidl::android::hardware::common::fmq::SynchronizedReadWrite;
 using ::aidl::android::media::tv::tuner::BnTunerFilter;
 using ::aidl::android::media::tv::tuner::ITunerFilterCallback;
 using ::aidl::android::media::tv::tuner::TunerDemuxIpAddress;
@@ -44,6 +48,7 @@
 using ::aidl::android::media::tv::tuner::TunerFilterSettings;
 using ::aidl::android::media::tv::tuner::TunerFilterTemiEvent;
 using ::aidl::android::media::tv::tuner::TunerFilterTsRecordEvent;
+using ::android::hardware::MQDescriptorSync;
 using ::android::hardware::Return;
 using ::android::hardware::Void;
 using ::android::hardware::hidl_array;
@@ -70,6 +75,7 @@
 using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterSettings;
 using ::android::hardware::tv::tuner::V1_0::DemuxPid;
 using ::android::hardware::tv::tuner::V1_0::IFilter;
+using ::android::hardware::tv::tuner::V1_1::AvStreamType;
 using ::android::hardware::tv::tuner::V1_1::DemuxFilterEventExt;
 using ::android::hardware::tv::tuner::V1_1::DemuxFilterMonitorEvent;
 using ::android::hardware::tv::tuner::V1_1::DemuxFilterTsRecordEventExt;
@@ -77,20 +83,28 @@
 
 namespace android {
 
+using MQDesc = MQDescriptorSync<uint8_t>;
+using AidlMQDesc = MQDescriptor<int8_t, SynchronizedReadWrite>;
+
 const static int IP_V4_LENGTH = 4;
 const static int IP_V6_LENGTH = 16;
 
 class TunerFilter : public BnTunerFilter {
 
 public:
-    TunerFilter(sp<IFilter> filter, sp<IFilterCallback> callback);
+    TunerFilter(sp<IFilter> filter, sp<IFilterCallback> callback, int mainType, int subTyp);
     virtual ~TunerFilter();
     Status getId(int32_t* _aidl_return) override;
     Status getId64Bit(int64_t* _aidl_return) override;
+    Status getQueueDesc(AidlMQDesc* _aidl_return) override;
     Status configure(const TunerFilterConfiguration& config) override;
+    Status configureMonitorEvent(int monitorEventType) override;
+    Status configureIpFilterContextId(int cid) override;
+    Status configureAvStreamType(int avStreamType) override;
     Status getAvSharedHandleInfo(TunerFilterSharedHandleInfo* _aidl_return) override;
     Status releaseAvHandle(const ::aidl::android::hardware::common::NativeHandle& handle,
             int64_t avDataId) override;
+    Status setDataSource(const std::shared_ptr<ITunerFilter>& filter) override;
     Status start() override;
     Status stop() override;
     Status flush() override;
@@ -147,6 +161,10 @@
     DemuxFilterRecordSettings getRecordSettings(const TunerFilterSettings& settings);
     DemuxFilterDownloadSettings getDownloadSettings(const TunerFilterSettings& settings);
 
+    bool isAudioFilter();
+    bool isVideoFilter();
+    bool getHidlAvStreamType(int avStreamType, AvStreamType& type);
+
     void getHidlTsSettings(
         const TunerFilterConfiguration& config, DemuxFilterSettings& settings);
     void getHidlMmtpSettings(
@@ -166,6 +184,8 @@
     sp<IFilterCallback> mFilterCallback;
     int32_t mId;
     int64_t mId64Bit;
+    int mMainType;
+    int mSubType;
 };
 
 } // namespace android
diff --git a/services/tuner/TunerFrontend.cpp b/services/tuner/TunerFrontend.cpp
index bb8b07d..b85e58b 100644
--- a/services/tuner/TunerFrontend.cpp
+++ b/services/tuner/TunerFrontend.cpp
@@ -17,9 +17,12 @@
 #define LOG_TAG "TunerFrontend"
 
 #include "TunerFrontend.h"
+#include "TunerLnb.h"
 
 using ::aidl::android::media::tv::tuner::TunerFrontendAtsc3PlpSettings;
 using ::aidl::android::media::tv::tuner::TunerFrontendScanAtsc3PlpInfo;
+using ::aidl::android::media::tv::tuner::TunerFrontendStatusAtsc3PlpInfo;
+using ::aidl::android::media::tv::tuner::TunerFrontendUnionSettings;
 using ::android::hardware::tv::tuner::V1_0::FrontendAnalogSifStandard;
 using ::android::hardware::tv::tuner::V1_0::FrontendAnalogType;
 using ::android::hardware::tv::tuner::V1_0::FrontendAtscModulation;
@@ -64,10 +67,29 @@
 using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtMode;
 using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtModulation;
 using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtSettings;
+using ::android::hardware::tv::tuner::V1_0::FrontendModulationStatus;
 using ::android::hardware::tv::tuner::V1_0::FrontendScanAtsc3PlpInfo;
 using ::android::hardware::tv::tuner::V1_0::FrontendScanType;
+using ::android::hardware::tv::tuner::V1_0::FrontendStatusType;
 using ::android::hardware::tv::tuner::V1_0::Result;
+using ::android::hardware::tv::tuner::V1_1::FrontendAnalogAftFlag;
+using ::android::hardware::tv::tuner::V1_1::FrontendBandwidth;
+using ::android::hardware::tv::tuner::V1_1::FrontendCableTimeInterleaveMode;
+using ::android::hardware::tv::tuner::V1_1::FrontendDvbcBandwidth;
+using ::android::hardware::tv::tuner::V1_1::FrontendDtmbBandwidth;
+using ::android::hardware::tv::tuner::V1_1::FrontendDtmbCodeRate;
+using ::android::hardware::tv::tuner::V1_1::FrontendDtmbGuardInterval;
+using ::android::hardware::tv::tuner::V1_1::FrontendDtmbModulation;
+using ::android::hardware::tv::tuner::V1_1::FrontendDtmbTimeInterleaveMode;
+using ::android::hardware::tv::tuner::V1_1::FrontendDtmbTransmissionMode;
+using ::android::hardware::tv::tuner::V1_1::FrontendDvbsScanType;
+using ::android::hardware::tv::tuner::V1_1::FrontendGuardInterval;
+using ::android::hardware::tv::tuner::V1_1::FrontendInterleaveMode;
 using ::android::hardware::tv::tuner::V1_1::FrontendModulation;
+using ::android::hardware::tv::tuner::V1_1::FrontendRollOff;
+using ::android::hardware::tv::tuner::V1_1::FrontendTransmissionMode;
+using ::android::hardware::tv::tuner::V1_1::FrontendSpectralInversion;
+using ::android::hardware::tv::tuner::V1_1::FrontendStatusTypeExt1_1;
 
 namespace android {
 
@@ -105,12 +127,23 @@
 
 Status TunerFrontend::tune(const TunerFrontendSettings& settings) {
     if (mFrontend == NULL) {
-        ALOGD("IFrontend is not initialized");
+        ALOGE("IFrontend is not initialized");
         return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
     }
 
+    Result status;
     FrontendSettings frontendSettings = getHidlFrontendSettings(settings);
-    Result status = mFrontend->tune(frontendSettings);
+    if (settings.isExtended) {
+        if (mFrontend_1_1 == NULL) {
+            ALOGE("IFrontend_1_1 is not initialized");
+            return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+        }
+        FrontendSettingsExt1_1 frontendSettingsExt = getHidlFrontendSettingsExt(settings);
+        status = mFrontend_1_1->tune_1_1(frontendSettings, frontendSettingsExt);
+    } else {
+        status = mFrontend->tune(frontendSettings);
+    }
+
     if (status == Result::SUCCESS) {
         return Status::ok();
     }
@@ -138,9 +171,21 @@
         return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
     }
 
+    Result status;
     FrontendSettings frontendSettings = getHidlFrontendSettings(settings);
-    Result status = mFrontend->scan(
-            frontendSettings, static_cast<FrontendScanType>(frontendScanType));
+    if (settings.isExtended) {
+        if (mFrontend_1_1 == NULL) {
+            ALOGE("IFrontend_1_1 is not initialized");
+            return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+        }
+        FrontendSettingsExt1_1 frontendSettingsExt = getHidlFrontendSettingsExt(settings);
+        status = mFrontend_1_1->scan_1_1(frontendSettings,
+                static_cast<FrontendScanType>(frontendScanType), frontendSettingsExt);
+    } else {
+        status = mFrontend->scan(
+                frontendSettings, static_cast<FrontendScanType>(frontendScanType));
+    }
+
     if (status == Result::SUCCESS) {
         return Status::ok();
     }
@@ -162,12 +207,68 @@
     return Status::fromServiceSpecificError(static_cast<int32_t>(status));
 }
 
-Status TunerFrontend::setLnb(int /*lnbHandle*/) {
-    return Status::ok();
+Status TunerFrontend::setLnb(const shared_ptr<ITunerLnb>& lnb) {
+    if (mFrontend == NULL) {
+        ALOGD("IFrontend is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result status = mFrontend->setLnb(static_cast<TunerLnb*>(lnb.get())->getId());
+    if (status == Result::SUCCESS) {
+        return Status::ok();
+    }
+
+    return Status::fromServiceSpecificError(static_cast<int32_t>(status));
 }
 
-Status TunerFrontend::setLna(bool /*bEnable*/) {
-    return Status::ok();
+Status TunerFrontend::setLna(bool bEnable) {
+    if (mFrontend == NULL) {
+        ALOGD("IFrontend is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result status = mFrontend->setLna(bEnable);
+    if (status == Result::SUCCESS) {
+        return Status::ok();
+    }
+
+    return Status::fromServiceSpecificError(static_cast<int32_t>(status));
+}
+
+Status TunerFrontend::linkCiCamToFrontend(int ciCamId, int32_t* _aidl_return) {
+    if (mFrontend_1_1 == NULL) {
+        ALOGD("IFrontend_1_1 is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    int ltsId;
+    Result status;
+    mFrontend_1_1->linkCiCam(static_cast<uint32_t>(ciCamId),
+            [&](Result r, uint32_t id) {
+                status = r;
+                ltsId = id;
+            });
+
+    if (status == Result::SUCCESS) {
+        *_aidl_return = ltsId;
+        return Status::ok();
+    }
+
+    return Status::fromServiceSpecificError(static_cast<int32_t>(status));
+}
+
+Status TunerFrontend::unlinkCiCamToFrontend(int ciCamId) {
+    if (mFrontend_1_1 == NULL) {
+        ALOGD("IFrontend_1_1 is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result status = mFrontend_1_1->unlinkCiCam(ciCamId);
+    if (status == Result::SUCCESS) {
+        return Status::ok();
+    }
+
+    return Status::fromServiceSpecificError(static_cast<int32_t>(status));
 }
 
 Status TunerFrontend::close() {
@@ -184,8 +285,55 @@
     return Status::fromServiceSpecificError(static_cast<int32_t>(status));
 }
 
-Status TunerFrontend::getStatus(const vector<int32_t>& /*statusTypes*/,
-        vector<TunerFrontendStatus>* /*_aidl_return*/) {
+Status TunerFrontend::getStatus(const vector<int32_t>& statusTypes,
+        vector<TunerFrontendStatus>* _aidl_return) {
+    if (mFrontend == NULL) {
+        ALOGD("IFrontend is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res;
+    vector<FrontendStatus> status;
+    vector<FrontendStatusType> types;
+    for (auto s : statusTypes) {
+        types.push_back(static_cast<FrontendStatusType>(s));
+    }
+
+    mFrontend->getStatus(types, [&](Result r, const hidl_vec<FrontendStatus>& s) {
+        res = r;
+        status = s;
+    });
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+
+    getAidlFrontendStatus(status, *_aidl_return);
+    return Status::ok();
+}
+
+Status TunerFrontend::getStatusExtended_1_1(const vector<int32_t>& statusTypes,
+        vector<TunerFrontendStatus>* _aidl_return) {
+    if (mFrontend_1_1 == NULL) {
+        ALOGD("IFrontend_1_1 is not initialized");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res;
+    vector<FrontendStatusExt1_1> status;
+    vector<FrontendStatusTypeExt1_1> types;
+    for (auto s : statusTypes) {
+        types.push_back(static_cast<FrontendStatusTypeExt1_1>(s));
+    }
+
+    mFrontend_1_1->getStatusExt1_1(types, [&](Result r, const hidl_vec<FrontendStatusExt1_1>& s) {
+        res = r;
+        status = s;
+    });
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+
+    getAidlFrontendStatusExt(status, *_aidl_return);
     return Status::ok();
 }
 
@@ -277,7 +425,7 @@
             vector<TunerFrontendScanAtsc3PlpInfo> tunerPlpInfos;
             for (int i = 0; i < plpInfos.size(); i++) {
                 auto info = plpInfos[i];
-                int plpId = (int) info.plpId;
+                int8_t plpId = (int8_t) info.plpId;
                 bool lls = (bool) info.bLlsFlag;
                 TunerFrontendScanAtsc3PlpInfo plpInfo{
                     .plpId = plpId,
@@ -303,24 +451,34 @@
         case FrontendScanMessageTypeExt1_1::MODULATION: {
             FrontendModulation m = message.modulation();
             int modulation;
-            if (m.getDiscriminator() == FrontendModulation::hidl_discriminator::dvbc) {
-                modulation = (int) m.dvbc();
-            } else if (m.getDiscriminator() == FrontendModulation::hidl_discriminator::dvbt) {
-                modulation = (int) m.dvbt();
-            } else if (m.getDiscriminator() == FrontendModulation::hidl_discriminator::dvbs) {
-                modulation = (int) m.dvbs();
-            } else if (m.getDiscriminator() == FrontendModulation::hidl_discriminator::isdbs) {
-                modulation = (int) m.isdbs();
-            } else if (m.getDiscriminator() == FrontendModulation::hidl_discriminator::isdbs3) {
-                modulation = (int) m.isdbs3();
-            } else if (m.getDiscriminator() == FrontendModulation::hidl_discriminator::isdbt) {
-                modulation = (int) m.isdbt();
-            } else if (m.getDiscriminator() == FrontendModulation::hidl_discriminator::atsc) {
-                modulation = (int) m.atsc();
-            } else if (m.getDiscriminator() == FrontendModulation::hidl_discriminator::atsc3) {
-                modulation = (int) m.atsc3();
-            } else if (m.getDiscriminator() == FrontendModulation::hidl_discriminator::dtmb) {
-                modulation = (int) m.dtmb();
+            switch (m.getDiscriminator()) {
+                case FrontendModulation::hidl_discriminator::dvbc:
+                    modulation = (int) m.dvbc();
+                    break;
+                case FrontendModulation::hidl_discriminator::dvbt:
+                    modulation = (int) m.dvbt();
+                    break;
+                case FrontendModulation::hidl_discriminator::dvbs:
+                    modulation = (int) m.dvbs();
+                    break;
+                case FrontendModulation::hidl_discriminator::isdbs:
+                    modulation = (int) m.isdbs();
+                    break;
+                case FrontendModulation::hidl_discriminator::isdbs3:
+                    modulation = (int) m.isdbs3();
+                    break;
+                case FrontendModulation::hidl_discriminator::isdbt:
+                    modulation = (int) m.isdbt();
+                    break;
+                case FrontendModulation::hidl_discriminator::atsc:
+                    modulation = (int) m.atsc();
+                    break;
+                case FrontendModulation::hidl_discriminator::atsc3:
+                    modulation = (int) m.atsc3();
+                    break;
+                case FrontendModulation::hidl_discriminator::dtmb:
+                    modulation = (int) m.dtmb();
+                    break;
             }
             scanMessage.set<TunerFrontendScanMessage::modulation>(modulation);
             break;
@@ -342,6 +500,341 @@
 
 /////////////// TunerFrontend Helper Methods ///////////////////////
 
+void TunerFrontend::getAidlFrontendStatus(
+        vector<FrontendStatus>& hidlStatus, vector<TunerFrontendStatus>& aidlStatus) {
+    for (FrontendStatus s : hidlStatus) {
+        TunerFrontendStatus status;
+        switch (s.getDiscriminator()) {
+            case FrontendStatus::hidl_discriminator::isDemodLocked: {
+                status.set<TunerFrontendStatus::isDemodLocked>(s.isDemodLocked());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::snr: {
+                status.set<TunerFrontendStatus::snr>((int)s.snr());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::ber: {
+                status.set<TunerFrontendStatus::ber>((int)s.ber());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::per: {
+                status.set<TunerFrontendStatus::per>((int)s.per());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::preBer: {
+                status.set<TunerFrontendStatus::preBer>((int)s.preBer());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::signalQuality: {
+                status.set<TunerFrontendStatus::signalQuality>((int)s.signalQuality());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::signalStrength: {
+                status.set<TunerFrontendStatus::signalStrength>((int)s.signalStrength());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::symbolRate: {
+                status.set<TunerFrontendStatus::symbolRate>((int)s.symbolRate());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::innerFec: {
+                status.set<TunerFrontendStatus::innerFec>((long)s.innerFec());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::modulation: {
+                switch (s.modulation().getDiscriminator()) {
+                    case FrontendModulationStatus::hidl_discriminator::dvbc:
+                        status.set<TunerFrontendStatus::modulation>((int)s.modulation().dvbc());
+                        aidlStatus.push_back(status);
+                        break;
+                    case FrontendModulationStatus::hidl_discriminator::dvbs:
+                        status.set<TunerFrontendStatus::modulation>((int)s.modulation().dvbs());
+                        aidlStatus.push_back(status);
+                        break;
+                    case FrontendModulationStatus::hidl_discriminator::isdbs:
+                        status.set<TunerFrontendStatus::modulation>((int)s.modulation().isdbs());
+                        aidlStatus.push_back(status);
+                        break;
+                    case FrontendModulationStatus::hidl_discriminator::isdbs3:
+                        status.set<TunerFrontendStatus::modulation>((int)s.modulation().isdbs3());
+                        aidlStatus.push_back(status);
+                        break;
+                    case FrontendModulationStatus::hidl_discriminator::isdbt:
+                        status.set<TunerFrontendStatus::modulation>((int)s.modulation().isdbt());
+                        aidlStatus.push_back(status);
+                        break;
+                }
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::inversion: {
+                status.set<TunerFrontendStatus::inversion>((int)s.inversion());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::lnbVoltage: {
+                status.set<TunerFrontendStatus::lnbVoltage>((int)s.lnbVoltage());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::plpId: {
+                status.set<TunerFrontendStatus::plpId>((int8_t)s.plpId());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::isEWBS: {
+                status.set<TunerFrontendStatus::isEWBS>(s.isEWBS());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::agc: {
+                status.set<TunerFrontendStatus::agc>((int8_t)s.agc());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::isLnaOn: {
+                status.set<TunerFrontendStatus::isLnaOn>(s.isLnaOn());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::isLayerError: {
+                vector<bool> e(s.isLayerError().begin(), s.isLayerError().end());
+                status.set<TunerFrontendStatus::isLayerError>(e);
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::mer: {
+                status.set<TunerFrontendStatus::mer>((int)s.mer());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::freqOffset: {
+                status.set<TunerFrontendStatus::freqOffset>((int)s.freqOffset());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::hierarchy: {
+                status.set<TunerFrontendStatus::hierarchy>((int)s.hierarchy());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::isRfLocked: {
+                status.set<TunerFrontendStatus::isRfLocked>(s.isRfLocked());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatus::hidl_discriminator::plpInfo: {
+                vector<TunerFrontendStatusAtsc3PlpInfo> info;
+                for (auto i : s.plpInfo()) {
+                    info.push_back({
+                        .plpId = (int8_t)i.plpId,
+                        .isLocked = i.isLocked,
+                        .uec = (int)i.uec,
+                    });
+                }
+                status.set<TunerFrontendStatus::plpInfo>(info);
+                aidlStatus.push_back(status);
+                break;
+            }
+        }
+    }
+}
+
+void TunerFrontend::getAidlFrontendStatusExt(
+        vector<FrontendStatusExt1_1>& hidlStatus, vector<TunerFrontendStatus>& aidlStatus) {
+    for (FrontendStatusExt1_1 s : hidlStatus) {
+        TunerFrontendStatus status;
+        switch (s.getDiscriminator()) {
+            case FrontendStatusExt1_1::hidl_discriminator::modulations: {
+                vector<int> aidlMod;
+                for (auto m : s.modulations()) {
+                    switch (m.getDiscriminator()) {
+                        case FrontendModulation::hidl_discriminator::dvbc:
+                            aidlMod.push_back((int)m.dvbc());
+                            break;
+                        case FrontendModulation::hidl_discriminator::dvbs:
+                            aidlMod.push_back((int)m.dvbs());
+                            break;
+                        case FrontendModulation::hidl_discriminator::dvbt:
+                            aidlMod.push_back((int)m.dvbt());
+                            break;
+                        case FrontendModulation::hidl_discriminator::isdbs:
+                            aidlMod.push_back((int)m.isdbs());
+                            break;
+                        case FrontendModulation::hidl_discriminator::isdbs3:
+                            aidlMod.push_back((int)m.isdbs3());
+                            break;
+                        case FrontendModulation::hidl_discriminator::isdbt:
+                            aidlMod.push_back((int)m.isdbt());
+                            break;
+                        case FrontendModulation::hidl_discriminator::atsc:
+                            aidlMod.push_back((int)m.atsc());
+                            break;
+                        case FrontendModulation::hidl_discriminator::atsc3:
+                            aidlMod.push_back((int)m.atsc3());
+                            break;
+                        case FrontendModulation::hidl_discriminator::dtmb:
+                            aidlMod.push_back((int)m.dtmb());
+                            break;
+                    }
+                }
+                status.set<TunerFrontendStatus::modulations>(aidlMod);
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::bers: {
+                vector<int> b(s.bers().begin(), s.bers().end());
+                status.set<TunerFrontendStatus::bers>(b);
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::codeRates: {
+                vector<int64_t> codeRates;
+                for (auto c : s.codeRates()) {
+                    codeRates.push_back((long)c);
+                }
+                status.set<TunerFrontendStatus::codeRates>(codeRates);
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::bandwidth: {
+                switch (s.bandwidth().getDiscriminator()) {
+                    case FrontendBandwidth::hidl_discriminator::atsc3:
+                        status.set<TunerFrontendStatus::bandwidth>((int)s.bandwidth().atsc3());
+                        break;
+                    case FrontendBandwidth::hidl_discriminator::dvbc:
+                        status.set<TunerFrontendStatus::bandwidth>((int)s.bandwidth().dvbc());
+                        break;
+                    case FrontendBandwidth::hidl_discriminator::dvbt:
+                        status.set<TunerFrontendStatus::bandwidth>((int)s.bandwidth().dvbt());
+                        break;
+                    case FrontendBandwidth::hidl_discriminator::isdbt:
+                        status.set<TunerFrontendStatus::bandwidth>((int)s.bandwidth().isdbt());
+                        break;
+                    case FrontendBandwidth::hidl_discriminator::dtmb:
+                        status.set<TunerFrontendStatus::bandwidth>((int)s.bandwidth().dtmb());
+                        break;
+                }
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::interval: {
+                switch (s.interval().getDiscriminator()) {
+                    case FrontendGuardInterval::hidl_discriminator::dvbt:
+                        status.set<TunerFrontendStatus::interval>((int)s.interval().dvbt());
+                        break;
+                    case FrontendGuardInterval::hidl_discriminator::isdbt:
+                        status.set<TunerFrontendStatus::interval>((int)s.interval().isdbt());
+                        break;
+                    case FrontendGuardInterval::hidl_discriminator::dtmb:
+                        status.set<TunerFrontendStatus::interval>((int)s.interval().dtmb());
+                        break;
+                }
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::transmissionMode: {
+                switch (s.transmissionMode().getDiscriminator()) {
+                    case FrontendTransmissionMode::hidl_discriminator::dvbt:
+                        status.set<TunerFrontendStatus::transmissionMode>(
+                                (int)s.transmissionMode().dvbt());
+                        break;
+                    case FrontendTransmissionMode::hidl_discriminator::isdbt:
+                        status.set<TunerFrontendStatus::transmissionMode>(
+                                (int)s.transmissionMode().isdbt());
+                        break;
+                    case FrontendTransmissionMode::hidl_discriminator::dtmb:
+                        status.set<TunerFrontendStatus::transmissionMode>(
+                                (int)s.transmissionMode().dtmb());
+                        break;
+                }
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::uec: {
+                status.set<TunerFrontendStatus::uec>((int)s.uec());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::systemId: {
+                status.set<TunerFrontendStatus::systemId>((char16_t)s.systemId());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::interleaving: {
+                vector<int> aidlInter;
+                for (auto i : s.interleaving()) {
+                    switch (i.getDiscriminator()) {
+                        case FrontendInterleaveMode::hidl_discriminator::atsc3:
+                            aidlInter.push_back((int)i.atsc3());
+                            break;
+                        case FrontendInterleaveMode::hidl_discriminator::dvbc:
+                            aidlInter.push_back((int)i.dvbc());
+                            break;
+                        case FrontendInterleaveMode::hidl_discriminator::dtmb:
+                            aidlInter.push_back((int)i.dtmb());
+                            break;
+                    }
+                }
+                status.set<TunerFrontendStatus::interleaving>(aidlInter);
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::isdbtSegment: {
+                auto seg = s.isdbtSegment();
+                vector<uint8_t> i(seg.begin(), seg.end());
+                status.set<TunerFrontendStatus::isdbtSegment>(i);
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::tsDataRate: {
+                vector<int> ts(s.tsDataRate().begin(), s.tsDataRate().end());
+                status.set<TunerFrontendStatus::tsDataRate>(ts);
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::rollOff: {
+                switch (s.rollOff().getDiscriminator()) {
+                    case FrontendRollOff::hidl_discriminator::dvbs:
+                        status.set<TunerFrontendStatus::interleaving>((int)s.rollOff().dvbs());
+                        break;
+                    case FrontendRollOff::hidl_discriminator::isdbs:
+                        status.set<TunerFrontendStatus::interleaving>((int)s.rollOff().isdbs());
+                        break;
+                    case FrontendRollOff::hidl_discriminator::isdbs3:
+                        status.set<TunerFrontendStatus::interleaving>((int)s.rollOff().isdbs3());
+                        break;
+                }
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::isMiso: {
+                status.set<TunerFrontendStatus::isMiso>(s.isMiso());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::isLinear: {
+                status.set<TunerFrontendStatus::isLinear>(s.isLinear());
+                aidlStatus.push_back(status);
+                break;
+            }
+            case FrontendStatusExt1_1::hidl_discriminator::isShortFrames: {
+                status.set<TunerFrontendStatus::isShortFrames>(s.isShortFrames());
+                aidlStatus.push_back(status);
+                break;
+            }
+        }
+    }
+}
+
 hidl_vec<FrontendAtsc3PlpSettings> TunerFrontend::getAtsc3PlpSettings(
         const TunerFrontendAtsc3Settings& settings) {
     int len = settings.plpSettings.size();
@@ -384,166 +877,216 @@
     return coderate;
 }
 
-FrontendSettings TunerFrontend::getHidlFrontendSettings(const TunerFrontendSettings& settings) {
-    // TODO: extend TunerFrontendSettings to use 1.1 types
+FrontendSettings TunerFrontend::getHidlFrontendSettings(const TunerFrontendSettings& aidlSettings) {
+    auto settings = aidlSettings.settings;
     FrontendSettings frontendSettings;
+
     switch (settings.getTag()) {
-        case TunerFrontendSettings::analog:
+        case TunerFrontendUnionSettings::analog: {
+            auto analog = settings.get<TunerFrontendUnionSettings::analog>();
             frontendSettings.analog({
-                .frequency = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::analog>().frequency),
-                .type = static_cast<FrontendAnalogType>(
-                        settings.get<TunerFrontendSettings::analog>().signalType),
-                .sifStandard = static_cast<FrontendAnalogSifStandard>(
-                        settings.get<TunerFrontendSettings::analog>().sifStandard),
+                .frequency = static_cast<uint32_t>(analog.frequency),
+                .type = static_cast<FrontendAnalogType>(analog.signalType),
+                .sifStandard = static_cast<FrontendAnalogSifStandard>(analog.sifStandard),
             });
             break;
-        case TunerFrontendSettings::atsc:
+        }
+        case TunerFrontendUnionSettings::atsc: {
+            auto atsc = settings.get<TunerFrontendUnionSettings::atsc>();
             frontendSettings.atsc({
-                .frequency = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::atsc>().frequency),
-                .modulation = static_cast<FrontendAtscModulation>(
-                        settings.get<TunerFrontendSettings::atsc>().modulation),
+                .frequency = static_cast<uint32_t>(atsc.frequency),
+                .modulation = static_cast<FrontendAtscModulation>(atsc.modulation),
             });
             break;
-        case TunerFrontendSettings::atsc3:
+        }
+        case TunerFrontendUnionSettings::atsc3: {
+            auto atsc3 = settings.get<TunerFrontendUnionSettings::atsc3>();
             frontendSettings.atsc3({
-                .frequency = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::atsc3>().frequency),
-                .bandwidth = static_cast<FrontendAtsc3Bandwidth>(
-                        settings.get<TunerFrontendSettings::atsc3>().bandwidth),
+                .frequency = static_cast<uint32_t>(atsc3.frequency),
+                .bandwidth = static_cast<FrontendAtsc3Bandwidth>(atsc3.bandwidth),
                 .demodOutputFormat = static_cast<FrontendAtsc3DemodOutputFormat>(
-                        settings.get<TunerFrontendSettings::atsc3>().demodOutputFormat),
-                .plpSettings = getAtsc3PlpSettings(settings.get<TunerFrontendSettings::atsc3>()),
+                        atsc3.demodOutputFormat),
+                .plpSettings = getAtsc3PlpSettings(atsc3),
             });
             break;
-        case TunerFrontendSettings::cable:
+        }
+        case TunerFrontendUnionSettings::cable: {
+            auto dvbc = settings.get<TunerFrontendUnionSettings::cable>();
             frontendSettings.dvbc({
-                .frequency = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::cable>().frequency),
-                .modulation = static_cast<FrontendDvbcModulation>(
-                        settings.get<TunerFrontendSettings::cable>().modulation),
-                .fec = static_cast<FrontendInnerFec>(
-                        settings.get<TunerFrontendSettings::cable>().innerFec),
-                .symbolRate = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::cable>().symbolRate),
-                .outerFec = static_cast<FrontendDvbcOuterFec>(
-                        settings.get<TunerFrontendSettings::cable>().outerFec),
-                .annex = static_cast<FrontendDvbcAnnex>(
-                        settings.get<TunerFrontendSettings::cable>().annex),
+                .frequency = static_cast<uint32_t>(dvbc.frequency),
+                .modulation = static_cast<FrontendDvbcModulation>(dvbc.modulation),
+                .fec = static_cast<FrontendInnerFec>(dvbc.innerFec),
+                .symbolRate = static_cast<uint32_t>(dvbc.symbolRate),
+                .outerFec = static_cast<FrontendDvbcOuterFec>(dvbc.outerFec),
+                .annex = static_cast<FrontendDvbcAnnex>(dvbc.annex),
                 .spectralInversion = static_cast<FrontendDvbcSpectralInversion>(
-                        settings.get<TunerFrontendSettings::cable>().spectralInversion),
+                        dvbc.spectralInversion),
             });
             break;
-        case TunerFrontendSettings::dvbs:
+        }
+        case TunerFrontendUnionSettings::dvbs: {
+            auto dvbs = settings.get<TunerFrontendUnionSettings::dvbs>();
             frontendSettings.dvbs({
-                .frequency = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::dvbs>().frequency),
-                .modulation = static_cast<FrontendDvbsModulation>(
-                        settings.get<TunerFrontendSettings::dvbs>().modulation),
-                .coderate = getDvbsCodeRate(
-                        settings.get<TunerFrontendSettings::dvbs>().codeRate),
-                .symbolRate = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::dvbs>().symbolRate),
-                .rolloff = static_cast<FrontendDvbsRolloff>(
-                        settings.get<TunerFrontendSettings::dvbs>().rolloff),
-                .pilot = static_cast<FrontendDvbsPilot>(
-                        settings.get<TunerFrontendSettings::dvbs>().pilot),
-                .inputStreamId = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::dvbs>().inputStreamId),
-                .standard = static_cast<FrontendDvbsStandard>(
-                        settings.get<TunerFrontendSettings::dvbs>().standard),
-                .vcmMode = static_cast<FrontendDvbsVcmMode>(
-                        settings.get<TunerFrontendSettings::dvbs>().vcm),
+                .frequency = static_cast<uint32_t>(dvbs.frequency),
+                .modulation = static_cast<FrontendDvbsModulation>(dvbs.modulation),
+                .coderate = getDvbsCodeRate(dvbs.codeRate),
+                .symbolRate = static_cast<uint32_t>(dvbs.symbolRate),
+                .rolloff = static_cast<FrontendDvbsRolloff>(dvbs.rolloff),
+                .pilot = static_cast<FrontendDvbsPilot>(dvbs.pilot),
+                .inputStreamId = static_cast<uint32_t>(dvbs.inputStreamId),
+                .standard = static_cast<FrontendDvbsStandard>(dvbs.standard),
+                .vcmMode = static_cast<FrontendDvbsVcmMode>(dvbs.vcm),
             });
             break;
-        case TunerFrontendSettings::dvbt:
+        }
+        case TunerFrontendUnionSettings::dvbt: {
+            auto dvbt = settings.get<TunerFrontendUnionSettings::dvbt>();
             frontendSettings.dvbt({
-                .frequency = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::dvbt>().frequency),
+                .frequency = static_cast<uint32_t>(dvbt.frequency),
                 .transmissionMode = static_cast<FrontendDvbtTransmissionMode>(
-                        settings.get<TunerFrontendSettings::dvbt>().transmissionMode),
-                .bandwidth = static_cast<FrontendDvbtBandwidth>(
-                        settings.get<TunerFrontendSettings::dvbt>().bandwidth),
-                .constellation = static_cast<FrontendDvbtConstellation>(
-                        settings.get<TunerFrontendSettings::dvbt>().constellation),
-                .hierarchy = static_cast<FrontendDvbtHierarchy>(
-                        settings.get<TunerFrontendSettings::dvbt>().hierarchy),
-                .hpCoderate = static_cast<FrontendDvbtCoderate>(
-                        settings.get<TunerFrontendSettings::dvbt>().hpCodeRate),
-                .lpCoderate = static_cast<FrontendDvbtCoderate>(
-                        settings.get<TunerFrontendSettings::dvbt>().lpCodeRate),
-                .guardInterval = static_cast<FrontendDvbtGuardInterval>(
-                        settings.get<TunerFrontendSettings::dvbt>().guardInterval),
-                .isHighPriority = settings.get<TunerFrontendSettings::dvbt>().isHighPriority,
-                .standard = static_cast<FrontendDvbtStandard>(
-                        settings.get<TunerFrontendSettings::dvbt>().standard),
-                .isMiso = settings.get<TunerFrontendSettings::dvbt>().isMiso,
-                .plpMode = static_cast<FrontendDvbtPlpMode>(
-                        settings.get<TunerFrontendSettings::dvbt>().plpMode),
-                .plpId = static_cast<uint8_t>(
-                        settings.get<TunerFrontendSettings::dvbt>().plpId),
-                .plpGroupId = static_cast<uint8_t>(
-                        settings.get<TunerFrontendSettings::dvbt>().plpGroupId),
+                        dvbt.transmissionMode),
+                .bandwidth = static_cast<FrontendDvbtBandwidth>(dvbt.bandwidth),
+                .constellation = static_cast<FrontendDvbtConstellation>(dvbt.constellation),
+                .hierarchy = static_cast<FrontendDvbtHierarchy>(dvbt.hierarchy),
+                .hpCoderate = static_cast<FrontendDvbtCoderate>(dvbt.hpCodeRate),
+                .lpCoderate = static_cast<FrontendDvbtCoderate>(dvbt.lpCodeRate),
+                .guardInterval = static_cast<FrontendDvbtGuardInterval>(dvbt.guardInterval),
+                .isHighPriority = dvbt.isHighPriority,
+                .standard = static_cast<FrontendDvbtStandard>(dvbt.standard),
+                .isMiso = dvbt.isMiso,
+                .plpMode = static_cast<FrontendDvbtPlpMode>(dvbt.plpMode),
+                .plpId = static_cast<uint8_t>(dvbt.plpId),
+                .plpGroupId = static_cast<uint8_t>(dvbt.plpGroupId),
             });
             break;
-        case TunerFrontendSettings::isdbs:
+        }
+        case TunerFrontendUnionSettings::isdbs: {
+            auto isdbs = settings.get<TunerFrontendUnionSettings::isdbs>();
             frontendSettings.isdbs({
-                .frequency = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::isdbs>().frequency),
-                .streamId = static_cast<uint16_t>(
-                        settings.get<TunerFrontendSettings::isdbs>().streamId),
-                .streamIdType = static_cast<FrontendIsdbsStreamIdType>(
-                        settings.get<TunerFrontendSettings::isdbs>().streamIdType),
-                .modulation = static_cast<FrontendIsdbsModulation>(
-                        settings.get<TunerFrontendSettings::isdbs>().modulation),
-                .coderate = static_cast<FrontendIsdbsCoderate>(
-                        settings.get<TunerFrontendSettings::isdbs>().codeRate),
-                .symbolRate = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::isdbs>().symbolRate),
-                .rolloff = static_cast<FrontendIsdbsRolloff>(
-                        settings.get<TunerFrontendSettings::isdbs>().rolloff),
+                .frequency = static_cast<uint32_t>(isdbs.frequency),
+                .streamId = static_cast<uint16_t>(isdbs.streamId),
+                .streamIdType = static_cast<FrontendIsdbsStreamIdType>(isdbs.streamIdType),
+                .modulation = static_cast<FrontendIsdbsModulation>(isdbs.modulation),
+                .coderate = static_cast<FrontendIsdbsCoderate>(isdbs.codeRate),
+                .symbolRate = static_cast<uint32_t>(isdbs.symbolRate),
+                .rolloff = static_cast<FrontendIsdbsRolloff>(isdbs.rolloff),
             });
             break;
-        case TunerFrontendSettings::isdbs3:
+        }
+        case TunerFrontendUnionSettings::isdbs3: {
+            auto isdbs3 = settings.get<TunerFrontendUnionSettings::isdbs3>();
             frontendSettings.isdbs3({
-                .frequency = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::isdbs3>().frequency),
-                .streamId = static_cast<uint16_t>(
-                        settings.get<TunerFrontendSettings::isdbs3>().streamId),
-                .streamIdType = static_cast<FrontendIsdbsStreamIdType>(
-                        settings.get<TunerFrontendSettings::isdbs3>().streamIdType),
-                .modulation = static_cast<FrontendIsdbs3Modulation>(
-                        settings.get<TunerFrontendSettings::isdbs3>().modulation),
-                .coderate = static_cast<FrontendIsdbs3Coderate>(
-                        settings.get<TunerFrontendSettings::isdbs3>().codeRate),
-                .symbolRate = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::isdbs3>().symbolRate),
-                .rolloff = static_cast<FrontendIsdbs3Rolloff>(
-                        settings.get<TunerFrontendSettings::isdbs3>().rolloff),
+                .frequency = static_cast<uint32_t>(isdbs3.frequency),
+                .streamId = static_cast<uint16_t>(isdbs3.streamId),
+                .streamIdType = static_cast<FrontendIsdbsStreamIdType>(isdbs3.streamIdType),
+                .modulation = static_cast<FrontendIsdbs3Modulation>(isdbs3.modulation),
+                .coderate = static_cast<FrontendIsdbs3Coderate>(isdbs3.codeRate),
+                .symbolRate = static_cast<uint32_t>(isdbs3.symbolRate),
+                .rolloff = static_cast<FrontendIsdbs3Rolloff>(isdbs3.rolloff),
             });
             break;
-        case TunerFrontendSettings::isdbt:
+        }
+        case TunerFrontendUnionSettings::isdbt: {
+            auto isdbt = settings.get<TunerFrontendUnionSettings::isdbt>();
             frontendSettings.isdbt({
-                .frequency = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::isdbt>().frequency),
-                .modulation = static_cast<FrontendIsdbtModulation>(
-                        settings.get<TunerFrontendSettings::isdbt>().modulation),
-                .bandwidth = static_cast<FrontendIsdbtBandwidth>(
-                        settings.get<TunerFrontendSettings::isdbt>().bandwidth),
-                .mode = static_cast<FrontendIsdbtMode>(
-                        settings.get<TunerFrontendSettings::isdbt>().mode),
-                .coderate = static_cast<FrontendIsdbtCoderate>(
-                        settings.get<TunerFrontendSettings::isdbt>().codeRate),
-                .guardInterval = static_cast<FrontendIsdbtGuardInterval>(
-                        settings.get<TunerFrontendSettings::isdbt>().guardInterval),
-                .serviceAreaId = static_cast<uint32_t>(
-                        settings.get<TunerFrontendSettings::isdbt>().serviceAreaId),
+                .frequency = static_cast<uint32_t>(isdbt.frequency),
+                .modulation = static_cast<FrontendIsdbtModulation>(isdbt.modulation),
+                .bandwidth = static_cast<FrontendIsdbtBandwidth>(isdbt.bandwidth),
+                .mode = static_cast<FrontendIsdbtMode>(isdbt.mode),
+                .coderate = static_cast<FrontendIsdbtCoderate>(isdbt.codeRate),
+                .guardInterval = static_cast<FrontendIsdbtGuardInterval>(isdbt.guardInterval),
+                .serviceAreaId = static_cast<uint32_t>(isdbt.serviceAreaId),
             });
             break;
+        }
         default:
             break;
     }
+
     return frontendSettings;
 }
+
+FrontendSettingsExt1_1 TunerFrontend::getHidlFrontendSettingsExt(
+        const TunerFrontendSettings& aidlSettings) {
+    FrontendSettingsExt1_1 frontendSettingsExt{
+        .endFrequency = static_cast<uint32_t>(aidlSettings.endFrequency),
+        .inversion = static_cast<FrontendSpectralInversion>(aidlSettings.inversion),
+    };
+
+    auto settings = aidlSettings.settings;
+    switch (settings.getTag()) {
+        case TunerFrontendUnionSettings::analog: {
+            auto analog = settings.get<TunerFrontendUnionSettings::analog>();
+            if (analog.isExtended) {
+                frontendSettingsExt.settingExt.analog({
+                    .aftFlag = static_cast<FrontendAnalogAftFlag>(analog.aftFlag),
+                });
+            } else {
+                frontendSettingsExt.settingExt.noinit();
+            }
+            break;
+        }
+        case TunerFrontendUnionSettings::cable: {
+            auto dvbc = settings.get<TunerFrontendUnionSettings::cable>();
+            if (dvbc.isExtended) {
+                frontendSettingsExt.settingExt.dvbc({
+                    .interleaveMode = static_cast<FrontendCableTimeInterleaveMode>(
+                            dvbc.interleaveMode),
+                    .bandwidth = static_cast<FrontendDvbcBandwidth>(
+                            dvbc.bandwidth),
+                });
+            } else {
+                frontendSettingsExt.settingExt.noinit();
+            }
+            break;
+        }
+        case TunerFrontendUnionSettings::dvbs: {
+            auto dvbs = settings.get<TunerFrontendUnionSettings::dvbs>();
+            if (dvbs.isExtended) {
+                frontendSettingsExt.settingExt.dvbs({
+                    .scanType = static_cast<FrontendDvbsScanType>(dvbs.scanType),
+                    .isDiseqcRxMessage = dvbs.isDiseqcRxMessage,
+                });
+            } else {
+                frontendSettingsExt.settingExt.noinit();
+            }
+            break;
+        }
+        case TunerFrontendUnionSettings::dvbt: {
+            auto dvbt = settings.get<TunerFrontendUnionSettings::dvbt>();
+            if (dvbt.isExtended) {
+                frontendSettingsExt.settingExt.dvbt({
+                    .constellation =
+                            static_cast<hardware::tv::tuner::V1_1::FrontendDvbtConstellation>(
+                                    dvbt.constellation),
+                    .transmissionMode =
+                            static_cast<hardware::tv::tuner::V1_1::FrontendDvbtTransmissionMode>(
+                                    dvbt.transmissionMode),
+                });
+            } else {
+                frontendSettingsExt.settingExt.noinit();
+            }
+            break;
+        }
+        case TunerFrontendUnionSettings::dtmb: {
+            auto dtmb = settings.get<TunerFrontendUnionSettings::dtmb>();
+            frontendSettingsExt.settingExt.dtmb({
+                .frequency = static_cast<uint32_t>(dtmb.frequency),
+                .transmissionMode = static_cast<FrontendDtmbTransmissionMode>(
+                        dtmb.transmissionMode),
+                .bandwidth = static_cast<FrontendDtmbBandwidth>(dtmb.bandwidth),
+                .modulation = static_cast<FrontendDtmbModulation>(dtmb.modulation),
+                .codeRate = static_cast<FrontendDtmbCodeRate>(dtmb.codeRate),
+                .guardInterval = static_cast<FrontendDtmbGuardInterval>(dtmb.guardInterval),
+                .interleaveMode = static_cast<FrontendDtmbTimeInterleaveMode>(dtmb.interleaveMode),
+            });
+            break;
+        }
+        default:
+            frontendSettingsExt.settingExt.noinit();
+            break;
+    }
+
+    return frontendSettingsExt;
+}
 }  // namespace android
diff --git a/services/tuner/TunerFrontend.h b/services/tuner/TunerFrontend.h
index 431022d..22fd509 100644
--- a/services/tuner/TunerFrontend.h
+++ b/services/tuner/TunerFrontend.h
@@ -27,6 +27,7 @@
 using Status = ::ndk::ScopedAStatus;
 using ::aidl::android::media::tv::tuner::BnTunerFrontend;
 using ::aidl::android::media::tv::tuner::ITunerFrontendCallback;
+using ::aidl::android::media::tv::tuner::ITunerLnb;
 using ::aidl::android::media::tv::tuner::TunerFrontendAtsc3Settings;
 using ::aidl::android::media::tv::tuner::TunerFrontendDvbsCodeRate;
 using ::aidl::android::media::tv::tuner::TunerFrontendScanMessage;
@@ -41,11 +42,14 @@
 using ::android::hardware::tv::tuner::V1_0::FrontendId;
 using ::android::hardware::tv::tuner::V1_0::FrontendScanMessage;
 using ::android::hardware::tv::tuner::V1_0::FrontendScanMessageType;
-using ::android::hardware::tv::tuner::V1_0::FrontendSettings;;
+using ::android::hardware::tv::tuner::V1_0::FrontendSettings;
+using ::android::hardware::tv::tuner::V1_0::FrontendStatus;
 using ::android::hardware::tv::tuner::V1_0::IFrontend;
 using ::android::hardware::tv::tuner::V1_1::IFrontendCallback;
 using ::android::hardware::tv::tuner::V1_1::FrontendScanMessageExt1_1;
 using ::android::hardware::tv::tuner::V1_1::FrontendScanMessageTypeExt1_1;
+using ::android::hardware::tv::tuner::V1_1::FrontendSettingsExt1_1;
+using ::android::hardware::tv::tuner::V1_1::FrontendStatusExt1_1;
 
 using namespace std;
 
@@ -62,11 +66,15 @@
     Status stopTune() override;
     Status scan(const TunerFrontendSettings& settings, int frontendScanType) override;
     Status stopScan() override;
-    Status setLnb(int lnbHandle) override;
+    Status setLnb(const shared_ptr<ITunerLnb>& lnb) override;
     Status setLna(bool bEnable) override;
+    Status linkCiCamToFrontend(int ciCamId, int32_t* _aidl_return) override;
+    Status unlinkCiCamToFrontend(int ciCamId) override;
     Status close() override;
     Status getStatus(const vector<int32_t>& statusTypes,
             vector<TunerFrontendStatus>* _aidl_return) override;
+    Status getStatusExtended_1_1(const vector<int32_t>& statusTypes,
+            vector<TunerFrontendStatus>* _aidl_return) override;
     Status getFrontendId(int* _aidl_return) override;
 
     struct FrontendCallback : public IFrontendCallback {
@@ -86,7 +94,12 @@
     hidl_vec<FrontendAtsc3PlpSettings> getAtsc3PlpSettings(
             const TunerFrontendAtsc3Settings& settings);
     FrontendDvbsCodeRate getDvbsCodeRate(const TunerFrontendDvbsCodeRate& codeRate);
-    FrontendSettings getHidlFrontendSettings(const TunerFrontendSettings& settings);
+    FrontendSettings getHidlFrontendSettings(const TunerFrontendSettings& aidlSettings);
+    FrontendSettingsExt1_1 getHidlFrontendSettingsExt(const TunerFrontendSettings& aidlSettings);
+    void getAidlFrontendStatus(
+            vector<FrontendStatus>& hidlStatus, vector<TunerFrontendStatus>& aidlStatus);
+    void getAidlFrontendStatusExt(
+            vector<FrontendStatusExt1_1>& hidlStatus, vector<TunerFrontendStatus>& aidlStatus);
 
     int mId;
     sp<IFrontend> mFrontend;
diff --git a/services/tuner/TunerLnb.h b/services/tuner/TunerLnb.h
index e80b97e..500d072 100644
--- a/services/tuner/TunerLnb.h
+++ b/services/tuner/TunerLnb.h
@@ -49,6 +49,8 @@
     Status sendDiseqcMessage(const vector<uint8_t>& diseqcMessage) override;
     Status close() override;
 
+    int getId() { return mId; }
+
     struct LnbCallback : public ILnbCallback {
         LnbCallback(const shared_ptr<ITunerLnbCallback> tunerLnbCallback)
                 : mTunerLnbCallback(tunerLnbCallback) {};
diff --git a/services/tuner/TunerService.cpp b/services/tuner/TunerService.cpp
index da9f541..4f6f16c 100644
--- a/services/tuner/TunerService.cpp
+++ b/services/tuner/TunerService.cpp
@@ -17,12 +17,12 @@
 #define LOG_TAG "TunerService"
 
 #include <android/binder_manager.h>
-#include <fmq/ConvertMQDescriptors.h>
 #include <utils/Log.h>
 #include "TunerService.h"
 #include "TunerFrontend.h"
 #include "TunerLnb.h"
 #include "TunerDemux.h"
+#include "TunerDescrambler.h"
 
 using ::aidl::android::media::tv::tuner::TunerFrontendAnalogCapabilities;
 using ::aidl::android::media::tv::tuner::TunerFrontendAtsc3Capabilities;
@@ -45,6 +45,7 @@
 using ::android::hardware::tv::tuner::V1_0::ILnb;
 using ::android::hardware::tv::tuner::V1_0::LnbId;
 using ::android::hardware::tv::tuner::V1_0::Result;
+using ::android::hardware::tv::tuner::V1_1::FrontendDtmbCapabilities;
 
 namespace android {
 
@@ -57,8 +58,8 @@
     AServiceManager_addService(service->asBinder().get(), getServiceName());
 }
 
-bool TunerService::getITuner() {
-    ALOGD("getITuner");
+bool TunerService::hasITuner() {
+    ALOGD("hasITuner");
     if (mTuner != nullptr) {
         return true;
     }
@@ -70,10 +71,26 @@
     return true;
 }
 
+bool TunerService::hasITuner_1_1() {
+    ALOGD("hasITuner_1_1");
+    if (mTuner_1_1 != nullptr) {
+        return true;
+    }
+    if (!hasITuner()) {
+        return false;
+    }
+    mTuner_1_1 = ::android::hardware::tv::tuner::V1_1::ITuner::castFrom(mTuner);
+    if (mTuner_1_1 == nullptr) {
+        ALOGE("Failed to get ITuner_1_1 service");
+        return false;
+    }
+    return true;
+}
+
 Status TunerService::openDemux(
         int /* demuxHandle */, std::shared_ptr<ITunerDemux>* _aidl_return) {
     ALOGD("openDemux");
-    if (!getITuner()) {
+    if (!hasITuner()) {
         return Status::fromServiceSpecificError(static_cast<int32_t>(Result::NOT_INITIALIZED));
     }
     Result res;
@@ -92,52 +109,32 @@
         return Status::ok();
     }
 
-    ALOGD("open demux failed, res = %d", res);
+    ALOGW("open demux failed, res = %d", res);
     return Status::fromServiceSpecificError(static_cast<int32_t>(res));
 }
 
-Result TunerService::configFilter() {
-    ALOGD("configFilter");
-    if (mFilter == NULL) {
-        ALOGD("Failed to configure filter: filter not found");
-        return Result::NOT_INITIALIZED;
+Status TunerService::getDemuxCaps(TunerDemuxCapabilities* _aidl_return) {
+    ALOGD("getDemuxCaps");
+    if (!hasITuner()) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::NOT_INITIALIZED));
     }
-    DemuxFilterSettings filterSettings;
-    DemuxTsFilterSettings tsFilterSettings {
-        .tpid = 256,
-    };
-    DemuxFilterAvSettings filterAvSettings {
-        .isPassthrough = false,
-    };
-    tsFilterSettings.filterSettings.av(filterAvSettings);
-    filterSettings.ts(tsFilterSettings);
-    Result res = mFilter->configure(filterSettings);
-
-    if (res != Result::SUCCESS) {
-        ALOGD("config filter failed, res = %d", res);
-        return res;
+    Result res;
+    DemuxCapabilities caps;
+    mTuner->getDemuxCaps([&](Result r, const DemuxCapabilities& demuxCaps) {
+        caps = demuxCaps;
+        res = r;
+    });
+    if (res == Result::SUCCESS) {
+        *_aidl_return = getAidlDemuxCaps(caps);
+        return Status::ok();
     }
 
-    Result getQueueDescResult = Result::UNKNOWN_ERROR;
-    mFilter->getQueueDesc(
-            [&](Result r, const MQDescriptorSync<uint8_t>& desc) {
-                mFilterMQDesc = desc;
-                getQueueDescResult = r;
-                ALOGD("getFilterQueueDesc");
-            });
-    if (getQueueDescResult == Result::SUCCESS) {
-        unsafeHidlToAidlMQDescriptor<uint8_t, int8_t, SynchronizedReadWrite>(
-                mFilterMQDesc,  &mAidlMQDesc);
-        mAidlMq = new (nothrow) AidlMessageQueue(mAidlMQDesc);
-        EventFlag::createEventFlag(mAidlMq->getEventFlagWord(), &mEventFlag);
-    } else {
-        ALOGD("get MQDesc failed, res = %d", getQueueDescResult);
-    }
-    return getQueueDescResult;
+    ALOGW("Get demux caps failed, res = %d", res);
+    return Status::fromServiceSpecificError(static_cast<int32_t>(res));
 }
 
 Status TunerService::getFrontendIds(vector<int32_t>* ids) {
-    if (!getITuner()) {
+    if (!hasITuner()) {
         return Status::fromServiceSpecificError(
                 static_cast<int32_t>(Result::NOT_INITIALIZED));
     }
@@ -152,17 +149,15 @@
     return Status::ok();
 }
 
-Status TunerService::getFrontendInfo(
-        int32_t frontendHandle, TunerFrontendInfo* _aidl_return) {
-    if (mTuner == nullptr) {
+Status TunerService::getFrontendInfo(int32_t id, TunerFrontendInfo* _aidl_return) {
+    if (!hasITuner()) {
         ALOGE("ITuner service is not init.");
         return ::ndk::ScopedAStatus::fromServiceSpecificError(
                 static_cast<int32_t>(Result::UNAVAILABLE));
     }
 
     FrontendInfo info;
-    int feId = getResourceIdFromHandle(frontendHandle, FRONTEND);
-    Result res = getHidlFrontendInfo(feId, info);
+    Result res = getHidlFrontendInfo(id, info);
     if (res != Result::SUCCESS) {
         return Status::fromServiceSpecificError(static_cast<int32_t>(res));
     }
@@ -172,9 +167,41 @@
     return Status::ok();
 }
 
+Status TunerService::getFrontendDtmbCapabilities(
+        int32_t id, TunerFrontendDtmbCapabilities* _aidl_return) {
+    if (!hasITuner_1_1()) {
+        ALOGE("ITuner_1_1 service is not init.");
+        return ::ndk::ScopedAStatus::fromServiceSpecificError(
+                static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result res;
+    FrontendDtmbCapabilities dtmbCaps;
+    mTuner_1_1->getFrontendDtmbCapabilities(id,
+            [&](Result r, const FrontendDtmbCapabilities& caps) {
+        dtmbCaps = caps;
+        res = r;
+    });
+    if (res != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(res));
+    }
+
+    TunerFrontendDtmbCapabilities aidlDtmbCaps{
+        .transmissionModeCap = (int)dtmbCaps.transmissionModeCap,
+        .bandwidthCap = (int)dtmbCaps.bandwidthCap,
+        .modulationCap = (int)dtmbCaps.modulationCap,
+        .codeRateCap = (int)dtmbCaps.codeRateCap,
+        .guardIntervalCap = (int)dtmbCaps.guardIntervalCap,
+        .interleaveModeCap = (int)dtmbCaps.interleaveModeCap,
+    };
+
+    *_aidl_return = aidlDtmbCaps;
+    return Status::ok();
+}
+
 Status TunerService::openFrontend(
         int32_t frontendHandle, shared_ptr<ITunerFrontend>* _aidl_return) {
-    if (mTuner == nullptr) {
+    if (!hasITuner()) {
         ALOGE("ITuner service is not init.");
         return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
     }
@@ -193,25 +220,8 @@
     return Status::ok();
 }
 
-Status TunerService::getFmqSyncReadWrite(
-        MQDescriptor<int8_t, SynchronizedReadWrite>* mqDesc, bool* _aidl_return) {
-    ALOGD("getFmqSyncReadWrite");
-    // TODO: put the following methods AIDL, and should be called from clients.
-    configFilter();
-    mFilter->start();
-    if (mqDesc == nullptr) {
-        ALOGD("getFmqSyncReadWrite null MQDescriptor.");
-        *_aidl_return = false;
-    } else {
-        ALOGD("getFmqSyncReadWrite true");
-        *_aidl_return = true;
-        *mqDesc = move(mAidlMQDesc);
-    }
-    return ndk::ScopedAStatus::ok();
-}
-
 Status TunerService::openLnb(int lnbHandle, shared_ptr<ITunerLnb>* _aidl_return) {
-    if (!getITuner()) {
+    if (!hasITuner()) {
         ALOGD("get ITuner failed");
         return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
     }
@@ -232,7 +242,7 @@
 }
 
 Status TunerService::openLnbByName(const string& lnbName, shared_ptr<ITunerLnb>* _aidl_return) {
-    if (!getITuner()) {
+    if (!hasITuner()) {
         ALOGE("get ITuner failed");
         return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
     }
@@ -253,8 +263,30 @@
     return Status::ok();
 }
 
+Status TunerService::openDescrambler(int32_t /*descramblerHandle*/,
+            std::shared_ptr<ITunerDescrambler>* _aidl_return) {
+    if (!hasITuner()) {
+        ALOGD("get ITuner failed");
+        return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
+    }
+
+    Result status;
+    sp<IDescrambler> descrambler;
+    //int id = getResourceIdFromHandle(descramblerHandle, DESCRAMBLER);
+    mTuner->openDescrambler([&](Result r, const sp<IDescrambler>& descramblerSp) {
+        status = r;
+        descrambler = descramblerSp;
+    });
+    if (status != Result::SUCCESS) {
+        return Status::fromServiceSpecificError(static_cast<int32_t>(status));
+    }
+
+    *_aidl_return = ::ndk::SharedRefBase::make<TunerDescrambler>(descrambler);
+    return Status::ok();
+}
+
 Status TunerService::updateTunerResources() {
-    if (!getITuner()) {
+    if (!hasITuner()) {
         return Status::fromServiceSpecificError(static_cast<int32_t>(Result::UNAVAILABLE));
     }
 
@@ -343,6 +375,26 @@
     return res;
 }
 
+TunerDemuxCapabilities TunerService::getAidlDemuxCaps(DemuxCapabilities caps) {
+    TunerDemuxCapabilities aidlCaps{
+        .numDemux = (int)caps.numDemux,
+        .numRecord = (int)caps.numRecord,
+        .numPlayback = (int)caps.numPlayback,
+        .numTsFilter = (int)caps.numTsFilter,
+        .numSectionFilter = (int)caps.numSectionFilter,
+        .numAudioFilter = (int)caps.numAudioFilter,
+        .numVideoFilter = (int)caps.numVideoFilter,
+        .numPesFilter = (int)caps.numPesFilter,
+        .numPcrFilter = (int)caps.numPcrFilter,
+        .numBytesInSectionFilter = (int)caps.numBytesInSectionFilter,
+        .filterCaps = (int)caps.filterCaps,
+        .bTimeFilter = caps.bTimeFilter,
+    };
+    aidlCaps.linkCaps.resize(caps.linkCaps.size());
+    copy(caps.linkCaps.begin(), caps.linkCaps.end(), aidlCaps.linkCaps.begin());
+    return aidlCaps;
+}
+
 TunerFrontendInfo TunerService::convertToAidlFrontendInfo(FrontendInfo halInfo) {
     TunerFrontendInfo info{
         .type = (int)halInfo.type,
@@ -390,7 +442,7 @@
         case FrontendType::DVBC: {
             TunerFrontendCableCapabilities cableCaps{
                 .modulationCap = (int)halInfo.frontendCaps.dvbcCaps().modulationCap,
-                .codeRateCap = (int)halInfo.frontendCaps.dvbcCaps().fecCap,
+                .codeRateCap = (int64_t)halInfo.frontendCaps.dvbcCaps().fecCap,
                 .annexCap = (int)halInfo.frontendCaps.dvbcCaps().annexCap,
             };
             caps.set<TunerFrontendCapabilities::cableCaps>(cableCaps);
diff --git a/services/tuner/TunerService.h b/services/tuner/TunerService.h
index 942d409..ce085cb 100644
--- a/services/tuner/TunerService.h
+++ b/services/tuner/TunerService.h
@@ -19,7 +19,7 @@
 
 #include <aidl/android/media/tv/tunerresourcemanager/ITunerResourceManager.h>
 #include <aidl/android/media/tv/tuner/BnTunerService.h>
-#include <android/hardware/tv/tuner/1.0/ITuner.h>
+#include <android/hardware/tv/tuner/1.1/ITuner.h>
 #include <fmq/AidlMessageQueue.h>
 #include <fmq/EventFlag.h>
 #include <fmq/MessageQueue.h>
@@ -29,8 +29,11 @@
 using ::aidl::android::hardware::common::fmq::SynchronizedReadWrite;
 using ::aidl::android::media::tv::tuner::BnTunerService;
 using ::aidl::android::media::tv::tuner::ITunerDemux;
+using ::aidl::android::media::tv::tuner::ITunerDescrambler;
 using ::aidl::android::media::tv::tuner::ITunerFrontend;
 using ::aidl::android::media::tv::tuner::ITunerLnb;
+using ::aidl::android::media::tv::tuner::TunerDemuxCapabilities;
+using ::aidl::android::media::tv::tuner::TunerFrontendDtmbCapabilities;
 using ::aidl::android::media::tv::tuner::TunerFrontendInfo;
 using ::aidl::android::media::tv::tunerresourcemanager::ITunerResourceManager;
 
@@ -42,6 +45,7 @@
 using ::android::hardware::MQDescriptorSync;
 using ::android::hardware::Return;
 using ::android::hardware::Void;
+using ::android::hardware::tv::tuner::V1_0::DemuxCapabilities;
 using ::android::hardware::tv::tuner::V1_0::DemuxFilterAvSettings;
 using ::android::hardware::tv::tuner::V1_0::DemuxFilterEvent;
 using ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType;
@@ -53,6 +57,7 @@
 using ::android::hardware::tv::tuner::V1_0::FrontendId;
 using ::android::hardware::tv::tuner::V1_0::FrontendInfo;
 using ::android::hardware::tv::tuner::V1_0::IDemux;
+using ::android::hardware::tv::tuner::V1_0::IDescrambler;
 using ::android::hardware::tv::tuner::V1_0::IFilter;
 using ::android::hardware::tv::tuner::V1_0::IFilterCallback;
 using ::android::hardware::tv::tuner::V1_0::ITuner;
@@ -92,6 +97,20 @@
     TunerService();
     virtual ~TunerService();
 
+    Status getFrontendIds(vector<int32_t>* ids) override;
+    Status getFrontendInfo(int32_t id, TunerFrontendInfo* _aidl_return) override;
+    Status getFrontendDtmbCapabilities(
+            int32_t id, TunerFrontendDtmbCapabilities* _aidl_return) override;
+    Status openFrontend(
+            int32_t frontendHandle, shared_ptr<ITunerFrontend>* _aidl_return) override;
+    Status openLnb(int lnbHandle, shared_ptr<ITunerLnb>* _aidl_return) override;
+    Status openLnbByName(const string& lnbName, shared_ptr<ITunerLnb>* _aidl_return) override;
+    Status openDemux(int32_t demuxHandle, std::shared_ptr<ITunerDemux>* _aidl_return) override;
+    Status getDemuxCaps(TunerDemuxCapabilities* _aidl_return) override;
+    Status openDescrambler(int32_t descramblerHandle,
+            std::shared_ptr<ITunerDescrambler>* _aidl_return) override;
+    Status updateTunerResources() override;
+
     // TODO: create a map between resource id and handles.
     static int getResourceIdFromHandle(int resourceHandle, int /*type*/) {
         return (resourceHandle & 0x00ff0000) >> 16;
@@ -104,20 +123,9 @@
                 | (mResourceRequestCount++ & 0xffff);
     }
 
-    Status getFrontendIds(vector<int32_t>* ids) override;
-    Status getFrontendInfo(int32_t frontendHandle, TunerFrontendInfo* _aidl_return) override;
-    Status openFrontend(
-            int32_t frontendHandle, shared_ptr<ITunerFrontend>* _aidl_return) override;
-    Status getFmqSyncReadWrite(
-            MQDescriptor<int8_t, SynchronizedReadWrite>* mqDesc, bool* _aidl_return) override;
-    Status openLnb(int lnbHandle, shared_ptr<ITunerLnb>* _aidl_return) override;
-    Status openLnbByName(const string& lnbName, shared_ptr<ITunerLnb>* _aidl_return) override;
-    Status openDemux(int32_t demuxHandle, std::shared_ptr<ITunerDemux>* _aidl_return) override;
-    Status updateTunerResources() override;
-
 private:
-    bool getITuner();
-    Result configFilter();
+    bool hasITuner();
+    bool hasITuner_1_1();
 
     void updateFrontendResources();
     void updateLnbResources();
@@ -125,18 +133,14 @@
     Result getHidlFrontendInfo(int id, FrontendInfo& info);
     vector<int> getLnbHandles();
 
+    TunerDemuxCapabilities getAidlDemuxCaps(DemuxCapabilities caps);
     TunerFrontendInfo convertToAidlFrontendInfo(FrontendInfo halInfo);
 
     sp<ITuner> mTuner;
-    sp<IFilter> mFilter;
+    sp<::android::hardware::tv::tuner::V1_1::ITuner> mTuner_1_1;
 
     shared_ptr<ITunerResourceManager> mTunerResourceManager;
     int mResourceRequestCount = 0;
-
-    AidlMessageQueue* mAidlMq;
-    MQDescriptorSync<uint8_t> mFilterMQDesc;
-    AidlMQDesc mAidlMQDesc;
-    EventFlag* mEventFlag;
 };
 
 } // namespace android
diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl
index fa2c1ff..73b00ae 100644
--- a/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl
@@ -21,6 +21,7 @@
 import android.media.tv.tuner.ITunerFilter;
 import android.media.tv.tuner.ITunerFilterCallback;
 import android.media.tv.tuner.ITunerFrontend;
+import android.media.tv.tuner.ITunerTimeFilter;
 
 /**
  * Tuner Demux interface handles tuner related operations.
@@ -41,11 +42,36 @@
         in int mainType, in int subtype, in int bufferSize, in ITunerFilterCallback cb);
 
     /**
+     * Open time filter of the demux.
+     */
+    ITunerTimeFilter openTimeFilter();
+
+    /**
+     * Get hardware sync ID for audio and video.
+     */
+    int getAvSyncHwId(ITunerFilter tunerFilter);
+
+    /**
+     * Get current time stamp to use for A/V sync.
+     */
+    long getAvSyncTime(in int avSyncHwId);
+
+    /**
      * Open a DVR (Digital Video Record) instance in the demux.
      */
     ITunerDvr openDvr(in int dvbType, in int bufferSize, in ITunerDvrCallback cb);
 
     /**
+     * Connect Conditional Access Modules (CAM) through Common Interface (CI).
+     */
+    void connectCiCam(in int ciCamId);
+
+    /**
+     * Disconnect Conditional Access Modules (CAM).
+     */
+    void disconnectCiCam();
+
+    /**
      * Releases the ITunerDemux instance.
      */
     void close();
diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerDescrambler.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerDescrambler.aidl
new file mode 100644
index 0000000..7370eee
--- /dev/null
+++ b/services/tuner/aidl/android/media/tv/tuner/ITunerDescrambler.aidl
@@ -0,0 +1,53 @@
+/**
+ * Copyright 2021, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.tv.tuner;
+
+import android.media.tv.tuner.ITunerDemux;
+import android.media.tv.tuner.ITunerFilter;
+import android.media.tv.tuner.TunerDemuxPid;
+
+/**
+ * Tuner Demux interface handles tuner related operations.
+ *
+ * {@hide}
+ */
+interface ITunerDescrambler {
+    /**
+     * Set a demux as source of the descrambler.
+     */
+    void setDemuxSource(in ITunerDemux tunerDemux);
+
+    /**
+     * Set a key token to link descrambler to a key slot.
+     */
+    void setKeyToken(in byte[] keyToken);
+
+    /**
+     * Add packets' PID to the descrambler for descrambling.
+     */
+    void addPid(in TunerDemuxPid pid, in ITunerFilter optionalSourceFilter);
+
+    /**
+     * Remove packets' PID from the descrambler.
+     */
+    void removePid(in TunerDemuxPid pid, in ITunerFilter optionalSourceFilter);
+
+    /**
+     * Close a new interface of ITunerDescrambler.
+     */
+    void close();
+}
diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl
index 1d5544f..10d4c3b 100644
--- a/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl
@@ -16,6 +16,8 @@
 
 package android.media.tv.tuner;
 
+import android.hardware.common.fmq.MQDescriptor;
+import android.hardware.common.fmq.SynchronizedReadWrite;
 import android.hardware.common.NativeHandle;
 import android.media.tv.tuner.TunerFilterConfiguration;
 import android.media.tv.tuner.TunerFilterSharedHandleInfo;
@@ -37,11 +39,31 @@
     long getId64Bit();
 
     /**
+     * Get the descriptor of the Filter's FMQ.
+     */
+    MQDescriptor<byte, SynchronizedReadWrite> getQueueDesc();
+
+    /**
      * Configure the filter.
      */
     void configure(in TunerFilterConfiguration config);
 
     /**
+     * Configure the monitor event of the Filter.
+     */
+    void configureMonitorEvent(in int monitorEventType);
+
+    /**
+     * Configure the context id of the IP Filter.
+     */
+    void configureIpFilterContextId(in int cid);
+
+    /**
+     * Configure the stream type of the media Filter.
+     */
+    void configureAvStreamType(in int avStreamType);
+
+    /**
      * Get the a/v shared memory handle
      */
     TunerFilterSharedHandleInfo getAvSharedHandleInfo();
@@ -52,6 +74,11 @@
     void releaseAvHandle(in NativeHandle handle, in long avDataId);
 
     /**
+     * Set the filter's data source.
+     */
+    void setDataSource(ITunerFilter filter);
+
+    /**
      * Start the filter.
      */
     void start();
diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerFrontend.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerFrontend.aidl
index bfc3e30..ef0255a 100644
--- a/services/tuner/aidl/android/media/tv/tuner/ITunerFrontend.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/ITunerFrontend.aidl
@@ -17,6 +17,7 @@
 package android.media.tv.tuner;
 
 import android.media.tv.tuner.ITunerFrontendCallback;
+import android.media.tv.tuner.ITunerLnb;
 import android.media.tv.tuner.TunerFrontendSettings;
 import android.media.tv.tuner.TunerFrontendStatus;
 
@@ -61,9 +62,9 @@
     /**
      * Sets Low-Noise Block downconverter (LNB) for satellite frontend.
      *
-     * @param lnbHandle lnb handle in use.
+     * @param tuner lnb interface.
      */
-    void setLnb(in int lnbHandle);
+    void setLnb(in ITunerLnb lnb);
 
     /**
      * Enable or Disable Low Noise Amplifier (LNA).
@@ -73,6 +74,18 @@
     void setLna(in boolean bEnable);
 
     /**
+     * Link Frontend to the cicam with given id.
+     *
+     * @return lts id
+     */
+    int linkCiCamToFrontend(in int ciCamId);
+
+    /**
+     * Unink Frontend to the cicam with given id.
+     */
+    void unlinkCiCamToFrontend(in int ciCamId);
+
+    /**
      * Releases the ITunerFrontend instance.
      */
     void close();
@@ -83,6 +96,11 @@
     TunerFrontendStatus[] getStatus(in int[] statusTypes);
 
     /**
+     * Gets the 1.1 extended statuses of the frontend.
+     */
+    TunerFrontendStatus[] getStatusExtended_1_1(in int[] statusTypes);
+
+    /**
      * Gets the id of the frontend.
      */
     int getFrontendId();
diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl
index 2fabbe5..bea8811 100644
--- a/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl
@@ -20,8 +20,11 @@
 import android.hardware.common.fmq.SynchronizedReadWrite;
 import android.hardware.common.fmq.UnsynchronizedWrite;
 import android.media.tv.tuner.ITunerDemux;
+import android.media.tv.tuner.ITunerDescrambler;
 import android.media.tv.tuner.ITunerFrontend;
 import android.media.tv.tuner.ITunerLnb;
+import android.media.tv.tuner.TunerDemuxCapabilities;
+import android.media.tv.tuner.TunerFrontendDtmbCapabilities;
 import android.media.tv.tuner.TunerFrontendInfo;
 
 /**
@@ -46,6 +49,11 @@
     TunerFrontendInfo getFrontendInfo(in int frontendHandle);
 
     /**
+     * Get Dtmb Frontend Capabilities.
+     */
+    TunerFrontendDtmbCapabilities getFrontendDtmbCapabilities(in int id);
+
+    /**
      * Open a Tuner Frontend interface.
      *
      * @param frontendHandle the handle of the frontend granted by TRM.
@@ -53,13 +61,6 @@
      */
     ITunerFrontend openFrontend(in int frontendHandle);
 
-    /*
-     * Gets synchronized fast message queue.
-     *
-     * @return true if succeeds, false otherwise.
-     */
-    boolean getFmqSyncReadWrite(out MQDescriptor<byte, SynchronizedReadWrite> mqDesc);
-
     /**
      * Open a new interface of ITunerLnb given a lnbHandle.
      *
@@ -82,6 +83,20 @@
     ITunerDemux openDemux(in int demuxHandle);
 
     /**
+     * Retrieve the Tuner Demux capabilities.
+     *
+     * @return the demux’s capabilities.
+     */
+    TunerDemuxCapabilities getDemuxCaps();
+
+    /* Open a new interface of ITunerDescrambler given a descramblerHandle.
+     *
+     * @param descramblerHandle the handle of the descrambler granted by TRM.
+     * @return a newly created ITunerDescrambler interface.
+     */
+    ITunerDescrambler openDescrambler(in int descramblerHandle);
+
+    /**
      * Update Tuner Resources in TunerResourceManager.
      */
     // TODO: b/178124017 update TRM in TunerService independently.
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerDemuxCapabilities.aidl
new file mode 100644
index 0000000..71ab151
--- /dev/null
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerDemuxCapabilities.aidl
@@ -0,0 +1,50 @@
+/**
+ * Copyright 2021, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.tv.tuner;
+
+/**
+ * Tuner Demux capabilities interface.
+ *
+ * {@hide}
+ */
+parcelable TunerDemuxCapabilities {
+    int numDemux;
+
+    int numRecord;
+
+    int numPlayback;
+
+    int numTsFilter;
+
+    int numSectionFilter;
+
+    int numAudioFilter;
+
+    int numVideoFilter;
+
+    int numPesFilter;
+
+    int numPcrFilter;
+
+    int numBytesInSectionFilter;
+
+    int filterCaps;
+
+    int[] linkCaps;
+
+    boolean bTimeFilter;
+}
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxPid.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerDemuxPid.aidl
new file mode 100644
index 0000000..51c6378
--- /dev/null
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerDemuxPid.aidl
@@ -0,0 +1,28 @@
+/**
+ * Copyright 2021, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.tv.tuner;
+
+/**
+ * Demux PID interface.
+ *
+ * {@hide}
+ */
+union TunerDemuxPid {
+    int tPid;
+
+    int mmtpPid;
+}
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogSettings.aidl
index b6d07c3..40cd8c9 100644
--- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogSettings.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogSettings.aidl
@@ -33,4 +33,11 @@
      * Standard Interchange Format (SIF) setting
      */
     int sifStandard;
+
+    /**
+     * Fields after isExtended are only valid when isExtended is true
+     */
+    boolean isExtended;
+
+    int aftFlag;
 }
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableCapabilities.aidl
index 7df452a..b880c60 100644
--- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableCapabilities.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableCapabilities.aidl
@@ -30,7 +30,7 @@
     /**
      * Code Rate capability
      */
-    int codeRateCap; // inner FEC will converge to codeRate
+    long codeRateCap; // inner FEC will converge to codeRate
 
     /**
      * Annex capability
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableSettings.aidl
index 3984f2c..b9bcf29 100644
--- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableSettings.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableSettings.aidl
@@ -51,4 +51,13 @@
      * Spectral Inversion Type.
      */
     int spectralInversion;
+
+    /**
+     * Fields after isExtended are only valid when isExtended is true
+     */
+    boolean isExtended;
+
+    int interleaveMode;
+
+    int bandwidth;
 }
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbCapabilities.aidl
new file mode 100644
index 0000000..e8e4933
--- /dev/null
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbCapabilities.aidl
@@ -0,0 +1,36 @@
+/**
+ * Copyright 2021, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.tv.tuner;
+
+/**
+ * DTMB Frontend Capabilities interface.
+ *
+ * {@hide}
+ */
+parcelable TunerFrontendDtmbCapabilities {
+    int transmissionModeCap;
+
+    int bandwidthCap;
+
+    int modulationCap;
+
+    int codeRateCap;
+
+    int guardIntervalCap;
+
+    int interleaveModeCap;
+}
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbSettings.aidl
new file mode 100644
index 0000000..45e7ff9
--- /dev/null
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbSettings.aidl
@@ -0,0 +1,38 @@
+/**
+ * Copyright 2021, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.tv.tuner;
+
+/**
+ * DTMB Frontend Settings interface.
+ *
+ * {@hide}
+ */
+parcelable TunerFrontendDtmbSettings {
+    int frequency;
+
+    int transmissionMode;
+
+    int bandwidth;
+
+    int modulation;
+
+    int codeRate;
+
+    int guardInterval;
+
+    int interleaveMode;
+}
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsSettings.aidl
index 554a502..ec3e4b9 100644
--- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsSettings.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsSettings.aidl
@@ -53,4 +53,13 @@
      * Vcm mode.
      */
     int vcm;
+
+    /**
+     * Fields after isExtended are only valid when isExtended is true
+     */
+    boolean isExtended;
+
+    int scanType;
+
+    boolean isDiseqcRxMessage;
 }
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtSettings.aidl
index c72396b..14c942a 100644
--- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtSettings.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtSettings.aidl
@@ -67,4 +67,9 @@
      * Physical Layer Pipe (PLP) Group Id
      */
     int plpGroupId;
+
+    /**
+     * Fields after isExtended are only valid when isExtended is true
+     */
+    boolean isExtended;
 }
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanAtsc3PlpInfo.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanAtsc3PlpInfo.aidl
index ca4a9af..1b8fcbb 100644
--- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanAtsc3PlpInfo.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanAtsc3PlpInfo.aidl
@@ -22,7 +22,7 @@
  * {@hide}
  */
 parcelable TunerFrontendScanAtsc3PlpInfo {
-    int plpId;
+    byte plpId;
 
     boolean llsFlag;
 }
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendSettings.aidl
index a382941..70a5f3e 100644
--- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendSettings.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendSettings.aidl
@@ -1,5 +1,5 @@
 /**
- * Copyright 2020, The Android Open Source Project
+ * Copyright 2021, The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,37 +16,19 @@
 
 package android.media.tv.tuner;
 
-import android.media.tv.tuner.TunerFrontendAnalogSettings;
-import android.media.tv.tuner.TunerFrontendAtscSettings;
-import android.media.tv.tuner.TunerFrontendAtsc3Settings;
-import android.media.tv.tuner.TunerFrontendCableSettings;
-import android.media.tv.tuner.TunerFrontendDvbsSettings;
-import android.media.tv.tuner.TunerFrontendDvbtSettings;
-import android.media.tv.tuner.TunerFrontendIsdbsSettings;
-import android.media.tv.tuner.TunerFrontendIsdbs3Settings;
-import android.media.tv.tuner.TunerFrontendIsdbtSettings;
+import android.media.tv.tuner.TunerFrontendUnionSettings;
 
 /**
- * Analog Frontend Settings interface.
+ * Frontend Settings interface.
  *
  * {@hide}
  */
-union TunerFrontendSettings {
-    TunerFrontendAnalogSettings analog;
+parcelable TunerFrontendSettings {
+    TunerFrontendUnionSettings settings;
 
-    TunerFrontendAtscSettings atsc;
+    boolean isExtended;
 
-    TunerFrontendAtsc3Settings atsc3;
+    int endFrequency;
 
-    TunerFrontendCableSettings cable;
-
-    TunerFrontendDvbsSettings dvbs;
-
-    TunerFrontendDvbtSettings dvbt;
-
-    TunerFrontendIsdbsSettings isdbs;
-
-    TunerFrontendIsdbs3Settings isdbs3;
-
-    TunerFrontendIsdbtSettings isdbt;
+    int inversion;
 }
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatus.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatus.aidl
index 41f9f0e..2b3c01b 100644
--- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatus.aidl
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatus.aidl
@@ -16,9 +16,172 @@
 
 package android.media.tv.tuner;
 
+import android.media.tv.tuner.TunerFrontendStatusAtsc3PlpInfo;
+
 /**
  * Tuner Frontend Status interface.
  *
  * {@hide}
  */
-parcelable TunerFrontendStatus {}
+union TunerFrontendStatus {
+    /**
+     * Lock status for Demod in True/False.
+     */
+    boolean isDemodLocked;
+
+    /**
+     * SNR value measured by 0.001 dB.
+     */
+    int snr;
+
+    /**
+     * The number of error bits per 1 billion bits.
+     */
+    int ber;
+
+    /**
+     * The number of error packages per 1 billion packages.
+     */
+    int per;
+
+    /**
+     * The number of error bits per 1 billion bits before FEC.
+     */
+    int preBer;
+
+    /**
+     * Signal Quality in percent.
+     */
+    int signalQuality;
+
+    /**
+     * Signal Strength measured by 0.001 dBm.
+     */
+    int signalStrength;
+
+    /**
+     * Symbols per second
+     */
+    int symbolRate;
+
+    long innerFec;
+
+    /**
+     * Check frontend type to decide the hidl type value
+     */
+    int modulation;
+
+    int inversion;
+
+    int lnbVoltage;
+
+    byte plpId;
+
+    boolean isEWBS;
+
+    /**
+     * AGC value is normalized from 0 to 255.
+     */
+    byte agc;
+
+    boolean isLnaOn;
+
+    boolean[] isLayerError;
+
+    /**
+     * MER value measured by 0.001 dB
+     */
+    int mer;
+
+    /**
+     * Frequency difference in Hertz.
+     */
+    int freqOffset;
+
+    int hierarchy;
+
+    boolean isRfLocked;
+
+    /**
+     * A list of PLP status for tuned PLPs for ATSC3 frontend.
+     */
+    TunerFrontendStatusAtsc3PlpInfo[] plpInfo;
+
+    // 1.1 Extension Starting
+
+    /**
+     * Extended modulation status. Check frontend type to decide the hidl type value.
+     */
+    int[] modulations;
+
+    /**
+     * Extended bit error ratio status.
+     */
+    int[] bers;
+
+    /**
+     * Extended code rate status.
+     */
+    long[] codeRates;
+
+    /**
+     * Extended bandwidth status. Check frontend type to decide the hidl type value.
+     */
+    int bandwidth;
+
+    /**
+     * Extended guard interval status. Check frontend type to decide the hidl type value.
+     */
+    int interval;
+
+    /**
+     * Extended transmission mode status. Check frontend type to decide the hidl type value.
+     */
+    int transmissionMode;
+
+    /**
+     * Uncorrectable Error Counts of the frontend's Physical Layer Pipe (PLP)
+     * since the last tune operation.
+     */
+    int uec;
+
+    /**
+     * The current DVB-T2 system id status.
+     */
+    char systemId;
+
+    /**
+     * Frontend Interleaving Modes. Check frontend type to decide the hidl type value.
+     */
+    int[] interleaving;
+
+    /**
+     * Segments in ISDB-T Specification of all the channels.
+     */
+    byte[] isdbtSegment;
+
+    /**
+     * Transport Stream Data Rate in BPS of the current channel.
+     */
+    int[] tsDataRate;
+
+    /**
+     * Roll Off Type status of the frontend. Check frontend type to decide the hidl type value.
+     */
+    int rollOff;
+
+    /**
+     * If the frontend currently supports MISO or not.
+     */
+    boolean isMiso;
+
+    /**
+     * If the frontend code rate is linear or not.
+     */
+    boolean isLinear;
+
+    /**
+     * If short frames are enabled or not.
+     */
+    boolean isShortFrames;
+}
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatusAtsc3PlpInfo.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatusAtsc3PlpInfo.aidl
new file mode 100644
index 0000000..4116c34
--- /dev/null
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatusAtsc3PlpInfo.aidl
@@ -0,0 +1,39 @@
+/**
+ * Copyright 2021, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.tv.tuner;
+
+/**
+ * Atsc3 Frontend Physical Layer Pipe Info in Frontend status.
+ *
+ * {@hide}
+ */
+parcelable TunerFrontendStatusAtsc3PlpInfo {
+    /**
+     * PLP Id value.
+     */
+    byte plpId;
+
+    /**
+     * Demod Lock/Unlock status of this particular PLP.
+     */
+    boolean isLocked;
+
+    /**
+     * Uncorrectable Error Counts (UEC) of this particular PLP since last tune operation.
+     */
+    int uec;
+}
diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendUnionSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendUnionSettings.aidl
new file mode 100644
index 0000000..c362c2a
--- /dev/null
+++ b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendUnionSettings.aidl
@@ -0,0 +1,55 @@
+/**
+ * Copyright 2020, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.tv.tuner;
+
+import android.media.tv.tuner.TunerFrontendAnalogSettings;
+import android.media.tv.tuner.TunerFrontendAtscSettings;
+import android.media.tv.tuner.TunerFrontendAtsc3Settings;
+import android.media.tv.tuner.TunerFrontendCableSettings;
+import android.media.tv.tuner.TunerFrontendDtmbSettings;
+import android.media.tv.tuner.TunerFrontendDvbsSettings;
+import android.media.tv.tuner.TunerFrontendDvbtSettings;
+import android.media.tv.tuner.TunerFrontendIsdbsSettings;
+import android.media.tv.tuner.TunerFrontendIsdbs3Settings;
+import android.media.tv.tuner.TunerFrontendIsdbtSettings;
+
+/**
+ * Frontend Settings Union interface.
+ *
+ * {@hide}
+ */
+union TunerFrontendUnionSettings {
+    TunerFrontendAnalogSettings analog;
+
+    TunerFrontendAtscSettings atsc;
+
+    TunerFrontendAtsc3Settings atsc3;
+
+    TunerFrontendCableSettings cable;
+
+    TunerFrontendDvbsSettings dvbs;
+
+    TunerFrontendDvbtSettings dvbt;
+
+    TunerFrontendIsdbsSettings isdbs;
+
+    TunerFrontendIsdbs3Settings isdbs3;
+
+    TunerFrontendIsdbtSettings isdbt;
+
+    TunerFrontendDtmbSettings dtmb;
+}