Merge "hal: Make LL as primary output"
diff --git a/hal/Makefile.am b/hal/Makefile.am
index 6f6b36c..aafc3e9 100644
--- a/hal/Makefile.am
+++ b/hal/Makefile.am
@@ -187,6 +187,7 @@
 
 if AUDIO_HW_LOOPBACK
 AM_CFLAGS += -DAUDIO_HW_LOOPBACK_ENABLED
+AM_CFLAGS += -DCOMPRESS_METADATA_NEEDED
 c_sources += audio_extn/hw_loopback.c
 endif
 
diff --git a/hal/audio_extn/a2dp.c b/hal/audio_extn/a2dp.c
index 3b4acd8..5f8a7f4 100644
--- a/hal/audio_extn/a2dp.c
+++ b/hal/audio_extn/a2dp.c
@@ -50,14 +50,17 @@
 
 #ifdef SPLIT_A2DP_ENABLED
 #define AUDIO_PARAMETER_A2DP_STARTED "A2dpStarted"
-#define BT_IPC_LIB_NAME  "libbthost_if.so"
-#define ENC_MEDIA_FMT_NONE                                     0
-#define ENC_MEDIA_FMT_AAC                                  0x00010DA6
-#define ENC_MEDIA_FMT_APTX                                 0x000131ff
-#define ENC_MEDIA_FMT_APTX_HD                              0x00013200
-#define ENC_MEDIA_FMT_SBC                                  0x00010BF2
-#define ENC_MEDIA_FMT_CELT                                 0x00013221
-#define ENC_MEDIA_FMT_LDAC                                 0x00013224
+#define BT_IPC_SOURCE_LIB_NAME  "libbthost_if.so"
+#define BT_IPC_SINK_LIB_NAME    "libbthost_if_sink.so"
+#define MEDIA_FMT_NONE                                     0
+#define MEDIA_FMT_AAC                                      0x00010DA6
+#define MEDIA_FMT_APTX                                     0x000131ff
+#define MEDIA_FMT_APTX_HD                                  0x00013200
+#define MEDIA_FMT_SBC                                      0x00010BF2
+#define MEDIA_FMT_CELT                                     0x00013221
+#define MEDIA_FMT_LDAC                                     0x00013224
+#define MEDIA_FMT_MP3                                      0x00010BE9
+#define MEDIA_FMT_APTX_ADAPTIVE                            0x00013204
 #define MEDIA_FMT_AAC_AOT_LC                               2
 #define MEDIA_FMT_AAC_AOT_SBR                              5
 #define MEDIA_FMT_AAC_AOT_PS                               29
@@ -71,10 +74,14 @@
 #define MEDIA_FMT_SBC_ALLOCATION_METHOD_LOUDNESS           0
 #define MEDIA_FMT_SBC_ALLOCATION_METHOD_SNR                1
 #define MIXER_ENC_CONFIG_BLOCK     "SLIM_7_RX Encoder Config"
+#define MIXER_DEC_CONFIG_BLOCK     "SLIM_9_TX Decoder Config"
 #define MIXER_ENC_BIT_FORMAT       "AFE Input Bit Format"
+#define MIXER_DEC_BIT_FORMAT       "AFE Output Bit Format"
 #define MIXER_SCRAMBLER_MODE       "AFE Scrambler Mode"
-#define MIXER_SAMPLE_RATE          "BT SampleRate"
+#define MIXER_SAMPLE_RATE_SINK     "BT_TX SampleRate"
+#define MIXER_SAMPLE_RATE_SOURCE   "BT SampleRate"
 #define MIXER_AFE_IN_CHANNELS      "AFE Input Channels"
+#define MIXER_AFE_SINK_CHANNELS    "AFE Output Channels"
 #define MIXER_ENC_FMT_SBC          "SBC"
 #define MIXER_ENC_FMT_AAC          "AAC"
 #define MIXER_ENC_FMT_APTX         "APTX"
@@ -95,37 +102,45 @@
 #define DEFAULT_SINK_LATENCY_CELT      180
 #define DEFAULT_SINK_LATENCY_LDAC      180
 
+#define SOURCE 0
+#define SINK   1
+
 /*
  * Below enum values are extended from audio_base.h to
- * to keep encoder codec type local to bthost_ipc
+ * to keep encoder and decoder type local to bthost_ipc
  * and audio_hal as these are intended only for handshake
  * between IPC lib and Audio HAL.
  */
 typedef enum {
-    ENC_CODEC_TYPE_INVALID = AUDIO_FORMAT_INVALID, // 0xFFFFFFFFUL
-    ENC_CODEC_TYPE_AAC = AUDIO_FORMAT_AAC, // 0x04000000UL
-    ENC_CODEC_TYPE_SBC = AUDIO_FORMAT_SBC, // 0x1F000000UL
-    ENC_CODEC_TYPE_APTX = AUDIO_FORMAT_APTX, // 0x20000000UL
-    ENC_CODEC_TYPE_APTX_HD = AUDIO_FORMAT_APTX_HD, // 0x21000000UL
+    CODEC_TYPE_INVALID = AUDIO_FORMAT_INVALID, // 0xFFFFFFFFUL
+    CODEC_TYPE_AAC = AUDIO_FORMAT_AAC, // 0x04000000UL
+    CODEC_TYPE_SBC = AUDIO_FORMAT_SBC, // 0x1F000000UL
+    CODEC_TYPE_APTX = AUDIO_FORMAT_APTX, // 0x20000000UL
+    CODEC_TYPE_APTX_HD = AUDIO_FORMAT_APTX_HD, // 0x21000000UL
 #ifndef LINUX_ENABLED
-    ENC_CODEC_TYPE_APTX_DUAL_MONO = 570425344u, // 0x22000000UL
+    CODEC_TYPE_APTX_DUAL_MONO = 570425344u, // 0x22000000UL
 #endif
-    ENC_CODEC_TYPE_LDAC = AUDIO_FORMAT_LDAC, // 0x23000000UL
-    ENC_CODEC_TYPE_CELT = 603979776u, // 0x24000000UL
-}enc_codec_t;
+    CODEC_TYPE_LDAC = AUDIO_FORMAT_LDAC, // 0x23000000UL
+    CODEC_TYPE_CELT = 603979776u, // 0x24000000UL
+}codec_t;
 
-typedef int (*audio_stream_open_t)(void);
-typedef int (*audio_stream_close_t)(void);
-typedef int (*audio_start_stream_t)(void);
-typedef int (*audio_stop_stream_t)(void);
-typedef int (*audio_suspend_stream_t)(void);
-typedef void (*audio_handoff_triggered_t)(void);
-typedef void (*clear_a2dpsuspend_flag_t)(void);
-typedef void * (*audio_get_codec_config_t)(uint8_t *multicast_status,uint8_t *num_dev,
-                               enc_codec_t *codec_type);
-typedef int (*audio_check_a2dp_ready_t)(void);
-typedef uint16_t (*audio_get_a2dp_sink_latency_t)(void);
-typedef int (*audio_is_scrambling_enabled_t)(void);
+typedef int (*audio_source_open_t)(void);
+typedef int (*audio_source_close_t)(void);
+typedef int (*audio_source_start_t)(void);
+typedef int (*audio_source_stop_t)(void);
+typedef int (*audio_source_suspend_t)(void);
+typedef void (*audio_source_handoff_triggered_t)(void);
+typedef void (*clear_source_a2dpsuspend_flag_t)(void);
+typedef void * (*audio_get_enc_config_t)(uint8_t *multicast_status,
+                                uint8_t *num_dev, codec_t *codec_type);
+typedef int (*audio_source_check_a2dp_ready_t)(void);
+typedef int (*audio_is_source_scrambling_enabled_t)(void);
+typedef int (*audio_sink_start_t)(void);
+typedef int (*audio_sink_stop_t)(void);
+typedef void * (*audio_get_dec_config_t)(codec_t *codec_type);
+typedef void * (*audio_sink_session_setup_complete_t)(uint64_t system_latency);
+typedef int (*audio_sink_check_a2dp_ready_t)(void);
+typedef uint16_t (*audio_sink_get_a2dp_latency_t)(void);
 
 enum A2DP_STATE {
     A2DP_STATE_CONNECTED,
@@ -140,28 +155,41 @@
  */
 struct a2dp_data {
     struct audio_device *adev;
-    void *bt_lib_handle;
-    audio_stream_open_t audio_stream_open;
-    audio_stream_close_t audio_stream_close;
-    audio_start_stream_t audio_start_stream;
-    audio_stop_stream_t audio_stop_stream;
-    audio_suspend_stream_t audio_suspend_stream;
-    audio_handoff_triggered_t audio_handoff_triggered;
-    clear_a2dpsuspend_flag_t clear_a2dpsuspend_flag;
-    audio_get_codec_config_t audio_get_codec_config;
-    audio_check_a2dp_ready_t audio_check_a2dp_ready;
-    audio_get_a2dp_sink_latency_t audio_get_a2dp_sink_latency;
-    audio_is_scrambling_enabled_t audio_is_scrambling_enabled;
-    enum A2DP_STATE bt_state;
-    enc_codec_t bt_encoder_format;
+    void *bt_lib_source_handle;
+    audio_source_open_t audio_source_open;
+    audio_source_close_t audio_source_close;
+    audio_source_start_t audio_source_start;
+    audio_source_stop_t audio_source_stop;
+    audio_source_suspend_t audio_source_suspend;
+    audio_source_handoff_triggered_t audio_source_handoff_triggered;
+    clear_source_a2dpsuspend_flag_t clear_source_a2dpsuspend_flag;
+    audio_get_enc_config_t audio_get_enc_config;
+    audio_source_check_a2dp_ready_t audio_source_check_a2dp_ready;
+    audio_is_source_scrambling_enabled_t audio_is_source_scrambling_enabled;
+    enum A2DP_STATE bt_state_source;
+    codec_t bt_encoder_format;
     uint32_t enc_sampling_rate;
     uint32_t enc_channels;
-    bool a2dp_started;
-    bool a2dp_suspended;
-    int  a2dp_total_active_session_request;
+    bool a2dp_source_started;
+    bool a2dp_source_suspended;
+    int  a2dp_source_total_active_session_requests;
     bool is_a2dp_offload_supported;
     bool is_handoff_in_progress;
     bool is_aptx_dual_mono_supported;
+
+    void *bt_lib_sink_handle;
+    audio_sink_start_t audio_sink_start;
+    audio_sink_stop_t audio_sink_stop;
+    audio_get_dec_config_t audio_get_dec_config;
+    audio_sink_session_setup_complete_t audio_sink_session_setup_complete;
+    audio_sink_check_a2dp_ready_t audio_sink_check_a2dp_ready;
+    audio_sink_get_a2dp_latency_t audio_sink_get_a2dp_latency;
+    enum A2DP_STATE bt_state_sink;
+    codec_t bt_decoder_format;
+    uint32_t dec_sampling_rate;
+    uint32_t dec_channels;
+    bool a2dp_sink_started;
+    int  a2dp_sink_total_active_session_requests;
 };
 
 struct a2dp_data a2dp;
@@ -186,6 +214,43 @@
     uint32_t      sample_rate;
 } __attribute__ ((packed));
 
+/* Information about BT AAC decoder configuration
+ * This data is used between audio HAL module and
+ * BT IPC library to configure DSP decoder
+ */
+typedef struct {
+    uint16_t      aac_fmt_flag; /* LATM*/
+    uint16_t      audio_object_type; /* LC */
+    uint16_t      channels; /* Stereo */
+    uint16_t      total_size_of_pce_bits; /* 0 - only for channel conf PCE */
+    uint32_t      sampling_rate; /* 8k, 11.025k, 12k, 16k, 22.05k, 24k, 32k,
+                                  44.1k, 48k, 64k, 88.2k, 96k */
+} audio_aac_decoder_config_t;
+
+/* Information about BT SBC decoder configuration
+ * This data is used between audio HAL module and
+ * BT IPC library to configure DSP decoder
+ */
+typedef struct {
+    uint16_t      channels; /* Mono, Stereo */
+    uint32_t      sampling_rate; /* 8k, 11.025k, 12k, 16k, 22.05k, 24k, 32k,
+                                  44.1k, 48k, 64k, 88.2k, 96k */
+} audio_sbc_decoder_config_t;
+
+/* AAC decoder configuration structure. */
+typedef struct aac_dec_cfg_t aac_dec_cfg_t;
+struct aac_dec_cfg_t {
+    uint32_t dec_format;
+    audio_aac_decoder_config_t data;
+} __attribute__ ((packed));
+
+/* SBC decoder configuration structure. */
+typedef struct sbc_dec_cfg_t sbc_dec_cfg_t;
+struct sbc_dec_cfg_t {
+    uint32_t dec_format;
+    audio_sbc_decoder_config_t data;
+} __attribute__ ((packed));
+
 /* SBC encoder configuration structure. */
 typedef struct sbc_enc_cfg_t sbc_enc_cfg_t;
 
@@ -405,90 +470,141 @@
     ALOGD("%s: codec cap = %s",__func__,value);
 }
 
-/* API to open BT IPC library to start IPC communication */
-static void open_a2dp_output()
+/* API to open BT IPC library to start IPC communication for BT Source*/
+static void open_a2dp_source()
 {
     int ret = 0;
 
-    ALOGD(" Open A2DP output start ");
-    if (a2dp.bt_lib_handle == NULL){
+    ALOGD(" Open A2DP source start ");
+    if (a2dp.bt_lib_source_handle == NULL){
         ALOGD(" Requesting for BT lib handle");
-        a2dp.bt_lib_handle = dlopen(BT_IPC_LIB_NAME, RTLD_NOW);
+        a2dp.bt_lib_source_handle = dlopen(BT_IPC_SOURCE_LIB_NAME, RTLD_NOW);
 
-        if (a2dp.bt_lib_handle == NULL) {
-            ALOGE("%s: DLOPEN failed for %s", __func__, BT_IPC_LIB_NAME);
+        if (a2dp.bt_lib_source_handle == NULL) {
+            ALOGE("%s: DLOPEN failed for %s", __func__, BT_IPC_SOURCE_LIB_NAME);
             ret = -ENOSYS;
             goto init_fail;
         } else {
-            a2dp.audio_stream_open = (audio_stream_open_t)
-                          dlsym(a2dp.bt_lib_handle, "audio_stream_open");
-            a2dp.audio_start_stream = (audio_start_stream_t)
-                          dlsym(a2dp.bt_lib_handle, "audio_start_stream");
-            a2dp.audio_get_codec_config = (audio_get_codec_config_t)
-                          dlsym(a2dp.bt_lib_handle, "audio_get_codec_config");
-            a2dp.audio_suspend_stream = (audio_suspend_stream_t)
-                          dlsym(a2dp.bt_lib_handle, "audio_suspend_stream");
-            a2dp.audio_handoff_triggered = (audio_handoff_triggered_t)
-                          dlsym(a2dp.bt_lib_handle, "audio_handoff_triggered");
-            a2dp.clear_a2dpsuspend_flag = (clear_a2dpsuspend_flag_t)
-                          dlsym(a2dp.bt_lib_handle, "clear_a2dpsuspend_flag");
-            a2dp.audio_stop_stream = (audio_stop_stream_t)
-                          dlsym(a2dp.bt_lib_handle, "audio_stop_stream");
-            a2dp.audio_stream_close = (audio_stream_close_t)
-                          dlsym(a2dp.bt_lib_handle, "audio_stream_close");
-            a2dp.audio_check_a2dp_ready = (audio_check_a2dp_ready_t)
-                        dlsym(a2dp.bt_lib_handle,"audio_check_a2dp_ready");
-            a2dp.audio_get_a2dp_sink_latency = (audio_get_a2dp_sink_latency_t)
-                        dlsym(a2dp.bt_lib_handle,"audio_get_a2dp_sink_latency");
-            a2dp.audio_is_scrambling_enabled = (audio_is_scrambling_enabled_t)
-                        dlsym(a2dp.bt_lib_handle,"audio_is_scrambling_enabled");
+            a2dp.audio_source_open = (audio_source_open_t)
+                          dlsym(a2dp.bt_lib_source_handle, "audio_stream_open");
+            a2dp.audio_source_start = (audio_source_start_t)
+                          dlsym(a2dp.bt_lib_source_handle, "audio_start_stream");
+            a2dp.audio_get_enc_config = (audio_get_enc_config_t)
+                          dlsym(a2dp.bt_lib_source_handle, "audio_get_codec_config");
+            a2dp.audio_source_suspend = (audio_source_suspend_t)
+                          dlsym(a2dp.bt_lib_source_handle, "audio_suspend_stream");
+            a2dp.audio_source_handoff_triggered = (audio_source_handoff_triggered_t)
+                          dlsym(a2dp.bt_lib_source_handle, "audio_handoff_triggered");
+            a2dp.clear_source_a2dpsuspend_flag = (clear_source_a2dpsuspend_flag_t)
+                          dlsym(a2dp.bt_lib_source_handle, "clear_a2dpsuspend_flag");
+            a2dp.audio_source_stop = (audio_source_stop_t)
+                          dlsym(a2dp.bt_lib_source_handle, "audio_stop_stream");
+            a2dp.audio_source_close = (audio_source_close_t)
+                          dlsym(a2dp.bt_lib_source_handle, "audio_stream_close");
+            a2dp.audio_source_check_a2dp_ready = (audio_source_check_a2dp_ready_t)
+                        dlsym(a2dp.bt_lib_source_handle,"audio_check_a2dp_ready");
+            a2dp.audio_sink_get_a2dp_latency = (audio_sink_get_a2dp_latency_t)
+                        dlsym(a2dp.bt_lib_source_handle,"audio_sink_get_a2dp_latency");
+            a2dp.audio_is_source_scrambling_enabled = (audio_is_source_scrambling_enabled_t)
+                        dlsym(a2dp.bt_lib_source_handle,"audio_is_scrambling_enabled");
         }
     }
 
-    if (a2dp.bt_lib_handle && a2dp.audio_stream_open) {
-        if (a2dp.bt_state == A2DP_STATE_DISCONNECTED) {
+    if (a2dp.bt_lib_source_handle && a2dp.audio_source_open) {
+        if (a2dp.bt_state_source == A2DP_STATE_DISCONNECTED) {
             ALOGD("calling BT stream open");
-            ret = a2dp.audio_stream_open();
+            ret = a2dp.audio_source_open();
             if(ret != 0) {
-                ALOGE("Failed to open output stream for a2dp: status %d", ret);
+                ALOGE("Failed to open source stream for a2dp: status %d", ret);
                 goto init_fail;
             }
-            a2dp.bt_state = A2DP_STATE_CONNECTED;
+            a2dp.bt_state_source = A2DP_STATE_CONNECTED;
         } else {
-            ALOGD("Called a2dp open with improper state, Ignoring request state %d", a2dp.bt_state);
+            ALOGD("Called a2dp open with improper state, Ignoring request state %d", a2dp.bt_state_source);
         }
     } else {
         ALOGE("a2dp handle is not identified, Ignoring open request");
-        a2dp.bt_state = A2DP_STATE_DISCONNECTED;
+        a2dp.bt_state_source = A2DP_STATE_DISCONNECTED;
         goto init_fail;
     }
 
 init_fail:
-    if(ret != 0 && (a2dp.bt_lib_handle != NULL)) {
-        dlclose(a2dp.bt_lib_handle);
-        a2dp.bt_lib_handle = NULL;
+    if(ret != 0 && (a2dp.bt_lib_source_handle != NULL)) {
+        dlclose(a2dp.bt_lib_source_handle);
+        a2dp.bt_lib_source_handle = NULL;
+    }
+}
+
+/* API to open BT IPC library to start IPC communication for BT Sink*/
+static void open_a2dp_sink()
+{
+    ALOGD(" Open A2DP input start ");
+    if (a2dp.bt_lib_sink_handle == NULL){
+        ALOGD(" Requesting for BT lib handle");
+        a2dp.bt_lib_sink_handle = dlopen(BT_IPC_SINK_LIB_NAME, RTLD_NOW);
+
+        if (a2dp.bt_lib_sink_handle == NULL) {
+            ALOGE("%s: DLOPEN failed for %s", __func__, BT_IPC_SINK_LIB_NAME);
+        } else {
+            a2dp.audio_sink_start = (audio_sink_start_t)
+                          dlsym(a2dp.bt_lib_sink_handle, "audio_sink_start_capture");
+            a2dp.audio_get_dec_config = (audio_get_dec_config_t)
+                          dlsym(a2dp.bt_lib_sink_handle, "audio_get_decoder_config");
+            a2dp.audio_sink_stop = (audio_sink_stop_t)
+                          dlsym(a2dp.bt_lib_sink_handle, "audio_sink_stop_capture");
+            a2dp.audio_sink_check_a2dp_ready = (audio_sink_check_a2dp_ready_t)
+                        dlsym(a2dp.bt_lib_sink_handle,"audio_sink_check_a2dp_ready");
+            a2dp.audio_sink_session_setup_complete = (audio_sink_session_setup_complete_t)
+                          dlsym(a2dp.bt_lib_sink_handle, "audio_sink_session_setup_complete");
+        }
     }
 }
 
 static int close_a2dp_output()
 {
     ALOGV("%s\n",__func__);
-    if (!(a2dp.bt_lib_handle && a2dp.audio_stream_close)) {
-        ALOGE("a2dp handle is not identified, Ignoring close request");
+
+    if (!(a2dp.bt_lib_source_handle && a2dp.audio_source_close)) {
+        ALOGE("a2dp source handle is not identified, Ignoring close request");
         return -ENOSYS;
     }
-    if (a2dp.bt_state != A2DP_STATE_DISCONNECTED) {
-        ALOGD("calling BT stream close");
-        if(a2dp.audio_stream_close() == false)
-            ALOGE("failed close a2dp control path from BT library");
+
+    if (a2dp.bt_state_source != A2DP_STATE_DISCONNECTED) {
+        ALOGD("calling BT source stream close");
+        if(a2dp.audio_source_close() == false)
+            ALOGE("failed close a2dp source control path from BT library");
     }
-    a2dp.a2dp_started = false;
-    a2dp.a2dp_total_active_session_request = 0;
-    a2dp.a2dp_suspended = false;
-    a2dp.bt_encoder_format = ENC_CODEC_TYPE_INVALID;
+    a2dp.a2dp_source_started = false;
+    a2dp.a2dp_source_total_active_session_requests = 0;
+    a2dp.a2dp_source_suspended = false;
+    a2dp.bt_encoder_format = CODEC_TYPE_INVALID;
     a2dp.enc_sampling_rate = 48000;
     a2dp.enc_channels = 2;
-    a2dp.bt_state = A2DP_STATE_DISCONNECTED;
+    a2dp.bt_state_source = A2DP_STATE_DISCONNECTED;
+
+    return 0;
+}
+
+static int close_a2dp_input()
+{
+    ALOGV("%s\n",__func__);
+
+    if (!(a2dp.bt_lib_sink_handle && a2dp.audio_source_close)) {
+        ALOGE("a2dp sink handle is not identified, Ignoring close request");
+        return -ENOSYS;
+    }
+
+    if (a2dp.bt_state_sink != A2DP_STATE_DISCONNECTED) {
+        ALOGD("calling BT sink stream close");
+        if(a2dp.audio_source_close() == false)
+            ALOGE("failed close a2dp sink control path from BT library");
+    }
+    a2dp.a2dp_sink_started = false;
+    a2dp.a2dp_sink_total_active_session_requests = 0;
+    a2dp.bt_decoder_format = CODEC_TYPE_INVALID;
+    a2dp.dec_sampling_rate = 48000;
+    a2dp.dec_channels = 2;
+    a2dp.bt_state_sink = A2DP_STATE_DISCONNECTED;
 
     return 0;
 }
@@ -497,15 +613,15 @@
 {
     bool scrambler_mode = false;
     struct mixer_ctl *ctrl_scrambler_mode = NULL;
-    if (a2dp.audio_is_scrambling_enabled && (a2dp.bt_state != A2DP_STATE_DISCONNECTED))
-        scrambler_mode = a2dp.audio_is_scrambling_enabled();
+    if (a2dp.audio_is_source_scrambling_enabled && (a2dp.bt_state_source != A2DP_STATE_DISCONNECTED))
+        scrambler_mode = a2dp.audio_is_source_scrambling_enabled();
 
     if (scrambler_mode) {
         //enable scrambler in dsp
         ctrl_scrambler_mode = mixer_get_ctl_by_name(a2dp.adev->mixer,
                                             MIXER_SCRAMBLER_MODE);
         if (!ctrl_scrambler_mode) {
-            ALOGE(" ERROR scrambler mode mixer control not identifed");
+            ALOGE(" ERROR scrambler mode mixer control not identified");
             return;
         } else {
             if (mixer_ctl_set_value(ctrl_scrambler_mode, 0, true) != 0) {
@@ -516,18 +632,26 @@
     }
 }
 
-static void a2dp_set_backend_cfg()
+static bool a2dp_set_backend_cfg(uint8_t direction)
 {
-    char *rate_str = NULL, *in_channels = NULL;
-    uint32_t sampling_rate = a2dp.enc_sampling_rate;
-    struct mixer_ctl *ctl_sample_rate = NULL, *ctrl_in_channels = NULL;
+    char *rate_str = NULL, *channels = NULL;
+    uint32_t sampling_rate;
+    struct mixer_ctl *ctl_sample_rate = NULL, *ctrl_channels = NULL;
+    bool is_configured = false;
 
-    //For LDAC encoder open slimbus port at 96Khz for 48Khz input
-    //and 88.2Khz for 44.1Khz input.
-    if ((a2dp.bt_encoder_format == ENC_CODEC_TYPE_LDAC) &&
+    if (direction == SINK) {
+        sampling_rate = a2dp.dec_sampling_rate;
+    } else {
+        sampling_rate = a2dp.enc_sampling_rate;
+    }
+    //For LDAC encoder and AAC decoder open slimbus port at
+    //96Khz for 48Khz input and 88.2Khz for 44.1Khz input.
+    if (((a2dp.bt_encoder_format == CODEC_TYPE_LDAC) ||
+         (a2dp.bt_decoder_format == AUDIO_FORMAT_AAC)) &&
         (sampling_rate == 48000 || sampling_rate == 44100 )) {
         sampling_rate = sampling_rate *2;
     }
+
     //Configure backend sampling rate
     switch (sampling_rate) {
     case 44100:
@@ -547,76 +671,271 @@
         break;
     }
 
-    ALOGD("%s: set backend sample rate =%s", __func__, rate_str);
-    ctl_sample_rate = mixer_get_ctl_by_name(a2dp.adev->mixer,
-                                        MIXER_SAMPLE_RATE);
+    if (direction == SINK) {
+        ALOGD("%s: set sink backend sample rate =%s", __func__, rate_str);
+        ctl_sample_rate = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                            MIXER_SAMPLE_RATE_SINK);
+    } else {
+        ALOGD("%s: set source backend sample rate =%s", __func__, rate_str);
+        ctl_sample_rate = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                            MIXER_SAMPLE_RATE_SOURCE);
+    }
     if (!ctl_sample_rate) {
-        ALOGE(" ERROR backend sample rate mixer control not identifed");
-        return;
+        ALOGE(" ERROR: backend sample rate mixer control not identified");
     } else {
         if (mixer_ctl_set_enum_by_string(ctl_sample_rate, rate_str) != 0) {
             ALOGE("%s: Failed to set backend sample rate =%s", __func__, rate_str);
-            return;
+            is_configured = false;
+            goto fail;
         }
     }
 
-    //Configure AFE input channels
-    switch (a2dp.enc_channels) {
-    case 1:
-        in_channels = "One";
-        break;
-    case 2:
-    default:
-        in_channels = "Two";
-        break;
+    if (direction == SINK) {
+        switch (a2dp.dec_channels) {
+        case 1:
+            channels = "One";
+            break;
+        case 2:
+        default:
+            channels = "Two";
+            break;
+        }
+
+        ALOGD("%s: set afe dec channels =%d", __func__, channels);
+        ctrl_channels = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                            MIXER_AFE_SINK_CHANNELS);
+    } else {
+        //Configure AFE enc channels
+        switch (a2dp.enc_channels) {
+        case 1:
+            channels = "One";
+            break;
+        case 2:
+        default:
+            channels = "Two";
+            break;
+        }
+
+        ALOGD("%s: set afe enc channels =%d", __func__, channels);
+        ctrl_channels = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                            MIXER_AFE_IN_CHANNELS);
     }
 
-    ALOGD("%s: set afe input channels =%d", __func__, a2dp.enc_channels);
-    ctrl_in_channels = mixer_get_ctl_by_name(a2dp.adev->mixer,
-                                        MIXER_AFE_IN_CHANNELS);
-    if (!ctrl_in_channels) {
-        ALOGE(" ERROR AFE input channels mixer control not identifed");
+    if (!ctrl_channels) {
+        ALOGE(" ERROR AFE channels mixer control not identified");
+    } else {
+        if (mixer_ctl_set_enum_by_string(ctrl_channels, channels) != 0) {
+            ALOGE("%s: Failed to set AFE channels =%d", __func__, channels);
+            is_configured = false;
+            goto fail;
+        }
+    }
+    is_configured = true;
+fail:
+    return is_configured;
+}
+
+bool configure_aac_dec_format(audio_aac_decoder_config_t *aac_bt_cfg)
+{
+    struct mixer_ctl *ctl_dec_data = NULL, *ctrl_bit_format = NULL;
+    struct aac_dec_cfg_t aac_dsp_cfg;
+    bool is_configured = false;
+    int ret = 0;
+
+    if(aac_bt_cfg == NULL)
+        return false;
+
+    ctl_dec_data = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_DEC_CONFIG_BLOCK);
+    if (!ctl_dec_data) {
+        ALOGE(" ERROR  a2dp decoder CONFIG data mixer control not identified");
+        is_configured = false;
+        goto fail;
+    }
+
+    memset(&aac_dsp_cfg, 0x0, sizeof(struct aac_dec_cfg_t));
+    aac_dsp_cfg.dec_format = MEDIA_FMT_AAC;
+    aac_dsp_cfg.data.aac_fmt_flag = aac_bt_cfg->aac_fmt_flag;
+    aac_dsp_cfg.data.channels = aac_bt_cfg->channels;
+    switch(aac_bt_cfg->audio_object_type) {
+    case 0:
+        aac_dsp_cfg.data.audio_object_type = MEDIA_FMT_AAC_AOT_LC;
+        break;
+    case 2:
+        aac_dsp_cfg.data.audio_object_type = MEDIA_FMT_AAC_AOT_PS;
+        break;
+    case 1:
+    default:
+        aac_dsp_cfg.data.audio_object_type = MEDIA_FMT_AAC_AOT_SBR;
+        break;
+    }
+    aac_dsp_cfg.data.total_size_of_pce_bits = aac_bt_cfg->total_size_of_pce_bits;
+    aac_dsp_cfg.data.sampling_rate = aac_bt_cfg->sampling_rate;
+    ret = mixer_ctl_set_array(ctl_dec_data, (void *)&aac_dsp_cfg,
+                              sizeof(struct aac_dec_cfg_t));
+    if (ret != 0) {
+        ALOGE("%s: failed to set AAC decoder config", __func__);
+        is_configured = false;
+        goto fail;
+    }
+
+    ctrl_bit_format = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                            MIXER_DEC_BIT_FORMAT);
+    if (!ctrl_bit_format) {
+        ALOGE(" ERROR Dec bit format mixer control not identified");
+        is_configured = false;
+        goto fail;
+    }
+    ret = mixer_ctl_set_enum_by_string(ctrl_bit_format, "S16_LE");
+    if (ret != 0) {
+        ALOGE("%s: Failed to set bit format to decoder", __func__);
+        is_configured = false;
+        goto fail;
+    }
+
+    is_configured = true;
+    a2dp.bt_decoder_format = CODEC_TYPE_AAC;
+    a2dp.dec_channels = aac_dsp_cfg.data.channels;
+    a2dp.dec_sampling_rate = aac_dsp_cfg.data.sampling_rate;
+    ALOGV("Successfully updated AAC dec format with sampling_rate: %d channels:%d",
+           aac_dsp_cfg.data.sampling_rate, aac_dsp_cfg.data.channels);
+fail:
+    return is_configured;
+}
+
+bool configure_sbc_dec_format(audio_sbc_decoder_config_t *sbc_bt_cfg)
+{
+    struct mixer_ctl *ctl_dec_data = NULL, *ctrl_bit_format = NULL;
+    struct sbc_dec_cfg_t sbc_dsp_cfg;
+    bool is_configured = false;
+    int ret = 0;
+
+    if(sbc_bt_cfg == NULL)
+        goto fail;
+
+    ctl_dec_data = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_DEC_CONFIG_BLOCK);
+    if (!ctl_dec_data) {
+        ALOGE(" ERROR  a2dp decoder CONFIG data mixer control not identified");
+        is_configured = false;
+        goto fail;
+    }
+
+    memset(&sbc_dsp_cfg, 0x0, sizeof(struct sbc_dec_cfg_t));
+    sbc_dsp_cfg.dec_format = MEDIA_FMT_SBC;
+    sbc_dsp_cfg.data.channels = sbc_bt_cfg->channels;
+    sbc_dsp_cfg.data.sampling_rate = sbc_bt_cfg->sampling_rate;
+    ret = mixer_ctl_set_array(ctl_dec_data, (void *)&sbc_dsp_cfg,
+                              sizeof(struct sbc_dec_cfg_t));
+    if (ret != 0) {
+        ALOGE("%s: failed to set SBC decoder config", __func__);
+        is_configured = false;
+        goto fail;
+    }
+
+    ctrl_bit_format = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                            MIXER_DEC_BIT_FORMAT);
+    if (!ctrl_bit_format) {
+        ALOGE(" ERROR Dec bit format mixer control not identified");
+        is_configured = false;
+        goto fail;
+    }
+    ret = mixer_ctl_set_enum_by_string(ctrl_bit_format, "S16_LE");
+    if (ret != 0) {
+        ALOGE("%s: Failed to set bit format to decoder", __func__);
+        is_configured = false;
+        goto fail;
+    }
+
+    is_configured = true;
+    a2dp.bt_decoder_format = CODEC_TYPE_SBC;
+    if (sbc_dsp_cfg.data.channels == MEDIA_FMT_SBC_CHANNEL_MODE_MONO)
+        a2dp.dec_channels = 1;
+    else
+        a2dp.dec_channels = 2;
+    a2dp.dec_sampling_rate = sbc_dsp_cfg.data.sampling_rate;
+    ALOGV("Successfully updated SBC dec format");
+fail:
+    return is_configured;
+}
+
+static void a2dp_reset_backend_cfg(uint8_t direction)
+{
+    char *rate_str = "KHZ_8", *channels = "Zero";
+    struct mixer_ctl *ctl_sample_rate = NULL, *ctrl_channels = NULL;
+
+    if (direction == SINK) {
+        ALOGD("%s: reset sink backend sample rate =%s", __func__, rate_str);
+        ctl_sample_rate = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                              MIXER_SAMPLE_RATE_SINK);
+    } else {
+        ALOGD("%s: reset source backend sample rate =%s", __func__, rate_str);
+        ctl_sample_rate = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                              MIXER_SAMPLE_RATE_SOURCE);
+    }
+    if (!ctl_sample_rate) {
+        ALOGE(" ERROR: backend sample rate mixer control not identified");
+    } else {
+        if (mixer_ctl_set_enum_by_string(ctl_sample_rate, rate_str) != 0) {
+            ALOGE("%s: Failed to reset backend sample rate = %s", __func__, rate_str);
+        }
+    }
+
+    if (direction == SINK) {
+        ALOGD("%s: reset afe sink channels =%s", __func__, channels);
+        ctrl_channels = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                            MIXER_AFE_SINK_CHANNELS);
+    } else {
+        ALOGD("%s: reset afe source channels =%s", __func__, channels);
+        ctrl_channels = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                            MIXER_AFE_IN_CHANNELS);
+    }
+    if (!ctrl_channels) {
+        ALOGE(" ERROR AFE channel mixer control not identified");
         return;
     } else {
-        if (mixer_ctl_set_enum_by_string(ctrl_in_channels, in_channels) != 0) {
-            ALOGE("%s: Failed to set AFE in channels =%d", __func__, a2dp.enc_channels);
+        if (mixer_ctl_set_enum_by_string(ctrl_channels, channels) != 0) {
+            ALOGE("%s: Failed to reset AFE channels", __func__);
             return;
         }
     }
 }
 
-static void a2dp_reset_backend_cfg()
+/* API to configure AFE decoder in DSP */
+static bool configure_a2dp_dsp_decoder_format()
 {
-    char *rate_str = "KHZ_8", *in_channels = "Zero";
-    struct mixer_ctl *ctl_sample_rate = NULL, *ctrl_in_channels = NULL;
+    void *codec_info = NULL;
+    codec_t codec_type = CODEC_TYPE_INVALID;
+    bool is_configured = false;
+    struct mixer_ctl *ctl_dec_data = NULL;
+    int ret = 0;
 
-    //reset backend sampling rate
-    ALOGD("%s: reset backend sample rate =%s", __func__, rate_str);
-    ctl_sample_rate = mixer_get_ctl_by_name(a2dp.adev->mixer,
-                                        MIXER_SAMPLE_RATE);
-    if (!ctl_sample_rate) {
-        ALOGE(" ERROR backend sample rate mixer control not identifed");
-        return;
-    } else {
-        if (mixer_ctl_set_enum_by_string(ctl_sample_rate, rate_str) != 0) {
-            ALOGE("%s: Failed to reset backend sample rate =%s", __func__, rate_str);
-            return;
-        }
+    if (!a2dp.audio_get_dec_config) {
+        ALOGE(" a2dp handle is not identified, ignoring a2dp decoder config");
+        return false;
     }
 
-    //reset AFE input channels
-    ALOGD("%s: reset afe input channels =%s", __func__, in_channels);
-    ctrl_in_channels = mixer_get_ctl_by_name(a2dp.adev->mixer,
-                                        MIXER_AFE_IN_CHANNELS);
-    if (!ctrl_in_channels) {
-        ALOGE(" ERROR AFE input channels mixer control not identifed");
-        return;
-    } else {
-        if (mixer_ctl_set_enum_by_string(ctrl_in_channels, in_channels) != 0) {
-            ALOGE("%s: Failed to reset AFE in channels =%d", __func__, a2dp.enc_channels);
-            return;
-        }
+    ctl_dec_data = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_DEC_CONFIG_BLOCK);
+    if (!ctl_dec_data) {
+        ALOGE(" ERROR  a2dp decoder CONFIG data mixer control not identified");
+        is_configured = false;
+        return false;
     }
+    codec_info = a2dp.audio_get_dec_config(&codec_type);
+    switch(codec_type) {
+        case CODEC_TYPE_SBC:
+            ALOGD(" SBC decoder supported BT device");
+            is_configured = configure_sbc_dec_format((audio_sbc_decoder_config_t *)codec_info);
+            break;
+        case CODEC_TYPE_AAC:
+            ALOGD(" AAC decoder supported BT device");
+            is_configured =
+              configure_aac_dec_format((audio_aac_decoder_config_t *)codec_info);
+            break;
+        default:
+            ALOGD(" Received Unsupported decoder format");
+            is_configured = false;
+            break;
+    }
+    return is_configured;
 }
 
 /* API to configure SBC DSP encoder */
@@ -632,12 +951,12 @@
 
    ctl_enc_data = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_ENC_CONFIG_BLOCK);
     if (!ctl_enc_data) {
-        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
     memset(&sbc_dsp_cfg, 0x0, sizeof(struct sbc_enc_cfg_t));
-    sbc_dsp_cfg.enc_format = ENC_MEDIA_FMT_SBC;
+    sbc_dsp_cfg.enc_format = MEDIA_FMT_SBC;
     sbc_dsp_cfg.num_subbands = sbc_bt_cfg->subband;
     sbc_dsp_cfg.blk_len = sbc_bt_cfg->blk_len;
     switch(sbc_bt_cfg->channels) {
@@ -671,7 +990,7 @@
     ctrl_bit_format = mixer_get_ctl_by_name(a2dp.adev->mixer,
                                             MIXER_ENC_BIT_FORMAT);
     if (!ctrl_bit_format) {
-        ALOGE(" ERROR bit format CONFIG data mixer control not identifed");
+        ALOGE(" ERROR bit format CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
@@ -682,7 +1001,7 @@
         goto fail;
     }
     is_configured = true;
-    a2dp.bt_encoder_format = ENC_CODEC_TYPE_SBC;
+    a2dp.bt_encoder_format = CODEC_TYPE_SBC;
     a2dp.enc_sampling_rate = sbc_bt_cfg->sampling_rate;
 
     if (sbc_dsp_cfg.channel_mode == MEDIA_FMT_SBC_CHANNEL_MODE_MONO)
@@ -709,7 +1028,7 @@
     }
 
     memset(aptx_dsp_cfg, 0x0, sizeof(struct aptx_enc_cfg_t));
-    aptx_dsp_cfg->custom_cfg.enc_format = ENC_MEDIA_FMT_APTX;
+    aptx_dsp_cfg->custom_cfg.enc_format = MEDIA_FMT_APTX;
 
     if (!a2dp.is_aptx_dual_mono_supported) {
         aptx_dsp_cfg->custom_cfg.sample_rate = aptx_bt_cfg->default_cfg->sampling_rate;
@@ -759,7 +1078,7 @@
     }
 
     memset(&aptx_dsp_cfg, 0x0, sizeof(struct custom_enc_cfg_t));
-    aptx_dsp_cfg->enc_format = ENC_MEDIA_FMT_APTX;
+    aptx_dsp_cfg->enc_format = MEDIA_FMT_APTX;
     aptx_dsp_cfg->sample_rate = aptx_bt_cfg->sampling_rate;
     aptx_dsp_cfg->num_channels = aptx_bt_cfg->channels;
     switch(aptx_dsp_cfg->num_channels) {
@@ -804,7 +1123,7 @@
 
     ctl_enc_data = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_ENC_CONFIG_BLOCK);
     if (!ctl_enc_data) {
-        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
@@ -829,7 +1148,7 @@
     ctrl_bit_format = mixer_get_ctl_by_name(a2dp.adev->mixer,
                                             MIXER_ENC_BIT_FORMAT);
     if (!ctrl_bit_format) {
-        ALOGE("ERROR bit format CONFIG data mixer control not identifed");
+        ALOGE("ERROR bit format CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     } else {
@@ -841,7 +1160,7 @@
         }
     }
     is_configured = true;
-    a2dp.bt_encoder_format = ENC_CODEC_TYPE_APTX;
+    a2dp.bt_encoder_format = CODEC_TYPE_APTX;
 fail:
     /*restore sample rate */
     if(!is_configured)
@@ -867,13 +1186,13 @@
 
     ctl_enc_data = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_ENC_CONFIG_BLOCK);
     if (!ctl_enc_data) {
-        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
 
     memset(&aptx_dsp_cfg, 0x0, sizeof(struct custom_enc_cfg_t));
-    aptx_dsp_cfg.enc_format = ENC_MEDIA_FMT_APTX_HD;
+    aptx_dsp_cfg.enc_format = MEDIA_FMT_APTX_HD;
     aptx_dsp_cfg.sample_rate = aptx_bt_cfg->sampling_rate;
     aptx_dsp_cfg.num_channels = aptx_bt_cfg->channels;
     switch(aptx_dsp_cfg.num_channels) {
@@ -895,7 +1214,7 @@
     }
     ctrl_bit_format = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_ENC_BIT_FORMAT);
     if (!ctrl_bit_format) {
-        ALOGE(" ERROR  bit format CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  bit format CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
@@ -906,7 +1225,7 @@
         goto fail;
     }
     is_configured = true;
-    a2dp.bt_encoder_format = ENC_CODEC_TYPE_APTX_HD;
+    a2dp.bt_encoder_format = CODEC_TYPE_APTX_HD;
     a2dp.enc_sampling_rate = aptx_bt_cfg->sampling_rate;
     a2dp.enc_channels = aptx_bt_cfg->channels;
     ALOGV("Successfully updated APTX HD encformat with samplingrate: %d channels:%d",
@@ -928,12 +1247,12 @@
 
     ctl_enc_data = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_ENC_CONFIG_BLOCK);
     if (!ctl_enc_data) {
-        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
     memset(&aac_dsp_cfg, 0x0, sizeof(struct aac_enc_cfg_t));
-    aac_dsp_cfg.enc_format = ENC_MEDIA_FMT_AAC;
+    aac_dsp_cfg.enc_format = MEDIA_FMT_AAC;
     aac_dsp_cfg.bit_rate = aac_bt_cfg->bitrate;
     aac_dsp_cfg.sample_rate = aac_bt_cfg->sampling_rate;
     switch(aac_bt_cfg->enc_mode) {
@@ -961,7 +1280,7 @@
                                             MIXER_ENC_BIT_FORMAT);
     if (!ctrl_bit_format) {
         is_configured = false;
-        ALOGE(" ERROR  bit format CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  bit format CONFIG data mixer control not identified");
         goto fail;
     }
     ret = mixer_ctl_set_enum_by_string(ctrl_bit_format, "S16_LE");
@@ -971,9 +1290,9 @@
         goto fail;
     }
     is_configured = true;
-    a2dp.bt_encoder_format = ENC_CODEC_TYPE_AAC;
+    a2dp.bt_encoder_format = CODEC_TYPE_AAC;
     a2dp.enc_sampling_rate = aac_bt_cfg->sampling_rate;
-    a2dp.enc_channels = aac_bt_cfg->channels;;
+    a2dp.enc_channels = aac_bt_cfg->channels;
     ALOGV("Successfully updated AAC enc format with samplingrate: %d channels:%d",
            aac_dsp_cfg.sample_rate, aac_dsp_cfg.channel_cfg);
 fail:
@@ -991,13 +1310,13 @@
 
     ctl_enc_data = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_ENC_CONFIG_BLOCK);
     if (!ctl_enc_data) {
-        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
     memset(&celt_dsp_cfg, 0x0, sizeof(struct celt_enc_cfg_t));
 
-    celt_dsp_cfg.custom_cfg.enc_format = ENC_MEDIA_FMT_CELT;
+    celt_dsp_cfg.custom_cfg.enc_format = MEDIA_FMT_CELT;
     celt_dsp_cfg.custom_cfg.sample_rate = celt_bt_cfg->sampling_rate;
     celt_dsp_cfg.custom_cfg.num_channels = celt_bt_cfg->channels;
     switch(celt_dsp_cfg.custom_cfg.num_channels) {
@@ -1028,7 +1347,7 @@
     }
     ctrl_bit_format = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_ENC_BIT_FORMAT);
     if (!ctrl_bit_format) {
-        ALOGE(" ERROR  bit format CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  bit format CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
@@ -1039,7 +1358,7 @@
         goto fail;
     }
     is_configured = true;
-    a2dp.bt_encoder_format = ENC_CODEC_TYPE_CELT;
+    a2dp.bt_encoder_format = CODEC_TYPE_CELT;
     a2dp.enc_sampling_rate = celt_bt_cfg->sampling_rate;
     a2dp.enc_channels = celt_bt_cfg->channels;
     ALOGV("Successfully updated CELT encformat with samplingrate: %d channels:%d",
@@ -1059,13 +1378,13 @@
 
     ldac_enc_data = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_ENC_CONFIG_BLOCK);
     if (!ldac_enc_data) {
-        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  a2dp encoder CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
     memset(&ldac_dsp_cfg, 0x0, sizeof(struct ldac_enc_cfg_t));
 
-    ldac_dsp_cfg.custom_cfg.enc_format = ENC_MEDIA_FMT_LDAC;
+    ldac_dsp_cfg.custom_cfg.enc_format = MEDIA_FMT_LDAC;
     ldac_dsp_cfg.custom_cfg.sample_rate = ldac_bt_cfg->sampling_rate;
     ldac_dsp_cfg.ldac_cfg.channel_mode = ldac_bt_cfg->channel_mode;
     switch(ldac_dsp_cfg.ldac_cfg.channel_mode) {
@@ -1094,7 +1413,7 @@
     }
     ctrl_bit_format = mixer_get_ctl_by_name(a2dp.adev->mixer, MIXER_ENC_BIT_FORMAT);
     if (!ctrl_bit_format) {
-        ALOGE(" ERROR  bit format CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  bit format CONFIG data mixer control not identified");
         is_configured = false;
         goto fail;
     }
@@ -1105,7 +1424,7 @@
         goto fail;
     }
     is_configured = true;
-    a2dp.bt_encoder_format = ENC_CODEC_TYPE_LDAC;
+    a2dp.bt_encoder_format = CODEC_TYPE_LDAC;
     a2dp.enc_sampling_rate = ldac_bt_cfg->sampling_rate;
     a2dp.enc_channels = ldac_dsp_cfg.custom_cfg.num_channels;
     ALOGV("Successfully updated LDAC encformat with samplingrate: %d channels:%d",
@@ -1118,25 +1437,25 @@
 {
     void *codec_info = NULL;
     uint8_t multi_cast = 0, num_dev = 1;
-    enc_codec_t codec_type = ENC_CODEC_TYPE_INVALID;
+    codec_t codec_type = CODEC_TYPE_INVALID;
     bool is_configured = false;
     audio_aptx_encoder_config aptx_encoder_cfg;
 
-    if (!a2dp.audio_get_codec_config) {
+    if (!a2dp.audio_get_enc_config) {
         ALOGE(" a2dp handle is not identified, ignoring a2dp encoder config");
         return false;
     }
     ALOGD("configure_a2dp_encoder_format start");
-    codec_info = a2dp.audio_get_codec_config(&multi_cast, &num_dev,
+    codec_info = a2dp.audio_get_enc_config(&multi_cast, &num_dev,
                                &codec_type);
 
     switch(codec_type) {
-        case ENC_CODEC_TYPE_SBC:
+        case CODEC_TYPE_SBC:
             ALOGD(" Received SBC encoder supported BT device");
             is_configured =
               configure_sbc_enc_format((audio_sbc_encoder_config *)codec_info);
             break;
-        case ENC_CODEC_TYPE_APTX:
+        case CODEC_TYPE_APTX:
             ALOGD(" Received APTX encoder supported BT device");
 #ifndef LINUX_ENABLED
             a2dp.is_aptx_dual_mono_supported = false;
@@ -1145,7 +1464,7 @@
             is_configured =
               configure_aptx_enc_format(&aptx_encoder_cfg);
             break;
-        case ENC_CODEC_TYPE_APTX_HD:
+        case CODEC_TYPE_APTX_HD:
             ALOGD(" Received APTX HD encoder supported BT device");
 #ifndef LINUX_ENABLED
             is_configured =
@@ -1156,7 +1475,7 @@
 #endif
             break;
 #ifndef LINUX_ENABLED
-        case ENC_CODEC_TYPE_APTX_DUAL_MONO:
+        case CODEC_TYPE_APTX_DUAL_MONO:
             ALOGD(" Received APTX dual mono encoder supported BT device");
             a2dp.is_aptx_dual_mono_supported = true;
             aptx_encoder_cfg.dual_mono_cfg = (audio_aptx_dual_mono_config *)codec_info;
@@ -1164,17 +1483,17 @@
               configure_aptx_enc_format(&aptx_encoder_cfg);
             break;
 #endif
-        case ENC_CODEC_TYPE_AAC:
+        case CODEC_TYPE_AAC:
             ALOGD(" Received AAC encoder supported BT device");
             is_configured =
               configure_aac_enc_format((audio_aac_encoder_config *)codec_info);
             break;
-        case ENC_CODEC_TYPE_CELT:
+        case CODEC_TYPE_CELT:
             ALOGD(" Received CELT encoder supported BT device");
             is_configured =
               configure_celt_enc_format((audio_celt_encoder_config *)codec_info);
             break;
-        case ENC_CODEC_TYPE_LDAC:
+        case CODEC_TYPE_LDAC:
             ALOGD(" Received LDAC encoder supported BT device");
             is_configured =
               configure_ldac_enc_format((audio_ldac_encoder_config *)codec_info);
@@ -1193,47 +1512,133 @@
 
     ALOGD("audio_extn_a2dp_start_playback start");
 
-    if(!(a2dp.bt_lib_handle && a2dp.audio_start_stream
-       && a2dp.audio_get_codec_config)) {
-        ALOGE("a2dp handle is not identified, Ignoring start request");
+    if(!(a2dp.bt_lib_source_handle && a2dp.audio_source_start
+       && a2dp.audio_get_enc_config)) {
+        ALOGE("a2dp handle is not identified, Ignoring start playback request");
         return -ENOSYS;
     }
 
-    if(a2dp.a2dp_suspended == true) {
+    if(a2dp.a2dp_source_suspended == true) {
         //session will be restarted after suspend completion
         ALOGD("a2dp start requested during suspend state");
         return -ENOSYS;
     }
 
-    if (!a2dp.a2dp_started && !a2dp.a2dp_total_active_session_request) {
+    if (!a2dp.a2dp_source_started && !a2dp.a2dp_source_total_active_session_requests) {
         ALOGD("calling BT module stream start");
         /* This call indicates BT IPC lib to start playback */
-        ret =  a2dp.audio_start_stream();
+        ret =  a2dp.audio_source_start();
         ALOGE("BT controller start return = %d",ret);
         if (ret != 0 ) {
            ALOGE("BT controller start failed");
-           a2dp.a2dp_started = false;
+           a2dp.a2dp_source_started = false;
         } else {
            if(configure_a2dp_encoder_format() == true) {
-                a2dp.a2dp_started = true;
+                a2dp.a2dp_source_started = true;
                 ret = 0;
                 ALOGD("Start playback successful to BT library");
            } else {
                 ALOGD(" unable to configure DSP encoder");
-                a2dp.a2dp_started = false;
+                a2dp.a2dp_source_started = false;
                 ret = -ETIMEDOUT;
            }
         }
     }
 
-    if (a2dp.a2dp_started) {
-        a2dp.a2dp_total_active_session_request++;
+    if (a2dp.a2dp_source_started) {
+        a2dp.a2dp_source_total_active_session_requests++;
         a2dp_check_and_set_scrambler();
-        a2dp_set_backend_cfg();
+        a2dp_set_backend_cfg(SOURCE);
     }
 
     ALOGD("start A2DP playback total active sessions :%d",
-          a2dp.a2dp_total_active_session_request);
+          a2dp.a2dp_source_total_active_session_requests);
+    return ret;
+}
+
+uint64_t audio_extn_a2dp_get_decoder_latency()
+{
+    uint32_t latency = 0;
+
+    switch(a2dp.bt_decoder_format) {
+        case CODEC_TYPE_SBC:
+            latency = DEFAULT_SINK_LATENCY_SBC;
+            break;
+        case CODEC_TYPE_AAC:
+            latency = DEFAULT_SINK_LATENCY_AAC;
+            break;
+        default:
+            latency = 200;
+            ALOGD("No valid decoder defined, setting latency to %dms", latency);
+            break;
+    }
+    return (uint64_t)latency;
+}
+
+bool a2dp_send_sink_setup_complete(void) {
+    uint64_t system_latency = 0;
+    bool is_complete = false;
+
+    system_latency = audio_extn_a2dp_get_decoder_latency();
+
+    if (a2dp.audio_sink_session_setup_complete(system_latency) == 0) {
+        is_complete = true;
+    }
+    return is_complete;
+}
+
+int audio_extn_a2dp_start_capture()
+{
+    int ret = 0;
+
+    ALOGD("audio_extn_a2dp_start_capture start");
+
+    if(!(a2dp.bt_lib_sink_handle && a2dp.audio_sink_start
+       && a2dp.audio_get_dec_config)) {
+        ALOGE("a2dp handle is not identified, Ignoring start capture request");
+        return -ENOSYS;
+    }
+
+    if (!a2dp.a2dp_sink_started && !a2dp.a2dp_sink_total_active_session_requests) {
+        ALOGD("calling BT module stream start");
+        /* This call indicates BT IPC lib to start capture */
+        ret =  a2dp.audio_sink_start();
+        ALOGE("BT controller start capture return = %d",ret);
+        if (ret != 0 ) {
+           ALOGE("BT controller start capture failed");
+           a2dp.a2dp_sink_started = false;
+        } else {
+
+           if(!audio_extn_a2dp_sink_is_ready()) {
+                ALOGD("Wait for capture ready not successful");
+                ret = -ETIMEDOUT;
+           }
+
+           if(configure_a2dp_dsp_decoder_format() == true) {
+                a2dp.a2dp_sink_started = true;
+                ret = 0;
+                ALOGD("Start capture successful to BT library");
+           } else {
+                ALOGD(" unable to configure DSP decoder");
+                a2dp.a2dp_sink_started = false;
+                ret = -ETIMEDOUT;
+           }
+
+           if (!a2dp_send_sink_setup_complete()) {
+               ALOGD("sink_setup_complete not successful");
+               ret = -ETIMEDOUT;
+           }
+        }
+    }
+
+    if (a2dp.a2dp_sink_started) {
+        if (a2dp_set_backend_cfg(SINK) == true) {
+        	a2dp.a2dp_sink_total_active_session_requests++;
+        }
+    }
+
+    ALOGD("start A2DP sink total active sessions :%d",
+          a2dp.a2dp_sink_total_active_session_requests);
     return ret;
 }
 
@@ -1248,16 +1653,16 @@
     ctl_enc_config = mixer_get_ctl_by_name(a2dp.adev->mixer,
                                            MIXER_ENC_CONFIG_BLOCK);
     if (!ctl_enc_config) {
-        ALOGE(" ERROR  a2dp encoder format mixer control not identifed");
+        ALOGE(" ERROR  a2dp encoder format mixer control not identified");
     } else {
         ret = mixer_ctl_set_array(ctl_enc_config, (void *)&dummy_reset_config,
                                         sizeof(struct sbc_enc_cfg_t));
-         a2dp.bt_encoder_format = ENC_MEDIA_FMT_NONE;
+         a2dp.bt_encoder_format = MEDIA_FMT_NONE;
     }
     ctrl_bit_format = mixer_get_ctl_by_name(a2dp.adev->mixer,
                                             MIXER_ENC_BIT_FORMAT);
     if (!ctrl_bit_format) {
-        ALOGE(" ERROR  bit format CONFIG data mixer control not identifed");
+        ALOGE(" ERROR  bit format CONFIG data mixer control not identified");
     } else {
         ret = mixer_ctl_set_enum_by_string(ctrl_bit_format, "S16_LE");
         if (ret != 0) {
@@ -1266,33 +1671,92 @@
     }
 }
 
+static void reset_a2dp_dec_config_params()
+{
+    int ret =0;
+
+    struct mixer_ctl *ctl_dec_config, *ctrl_bit_format;
+    struct aac_dec_cfg_t dummy_reset_config;
+
+    memset(&dummy_reset_config, 0x0, sizeof(struct aac_dec_cfg_t));
+    ctl_dec_config = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                           MIXER_DEC_CONFIG_BLOCK);
+    if (!ctl_dec_config) {
+        ALOGE(" ERROR  a2dp decoder format mixer control not identified");
+    } else {
+        ret = mixer_ctl_set_array(ctl_dec_config, (void *)&dummy_reset_config,
+                                        sizeof(struct aac_dec_cfg_t));
+         a2dp.bt_decoder_format = MEDIA_FMT_NONE;
+    }
+    ctrl_bit_format = mixer_get_ctl_by_name(a2dp.adev->mixer,
+                                            MIXER_DEC_BIT_FORMAT);
+    if (!ctrl_bit_format) {
+        ALOGE(" ERROR  bit format CONFIG data mixer control not identified");
+    } else {
+        ret = mixer_ctl_set_enum_by_string(ctrl_bit_format, "S16_LE");
+        if (ret != 0) {
+            ALOGE("%s: Failed to set bit format to decoder", __func__);
+        }
+    }
+}
+
 int audio_extn_a2dp_stop_playback()
 {
     int ret =0;
 
     ALOGV("audio_extn_a2dp_stop_playback start");
-    if(!(a2dp.bt_lib_handle && a2dp.audio_stop_stream)) {
-        ALOGE("a2dp handle is not identified, Ignoring start request");
+    if(!(a2dp.bt_lib_source_handle && a2dp.audio_source_stop)) {
+        ALOGE("a2dp handle is not identified, Ignoring stop request");
         return -ENOSYS;
     }
 
-    if (a2dp.a2dp_total_active_session_request > 0)
-        a2dp.a2dp_total_active_session_request--;
+    if (a2dp.a2dp_source_total_active_session_requests > 0)
+        a2dp.a2dp_source_total_active_session_requests--;
 
-    if ( a2dp.a2dp_started && !a2dp.a2dp_total_active_session_request) {
+    if ( a2dp.a2dp_source_started && !a2dp.a2dp_source_total_active_session_requests) {
         ALOGV("calling BT module stream stop");
-        ret = a2dp.audio_stop_stream();
+        ret = a2dp.audio_source_stop();
         if (ret < 0)
             ALOGE("stop stream to BT IPC lib failed");
         else
             ALOGV("stop steam to BT IPC lib successful");
         reset_a2dp_enc_config_params();
-        a2dp_reset_backend_cfg();
+        a2dp_reset_backend_cfg(SOURCE);
     }
-    if(!a2dp.a2dp_total_active_session_request)
-       a2dp.a2dp_started = false;
-    ALOGD("Stop A2DP playback total active sessions :%d",
-          a2dp.a2dp_total_active_session_request);
+    if(!a2dp.a2dp_source_total_active_session_requests)
+       a2dp.a2dp_source_started = false;
+    ALOGD("Stop A2DP playback, total active sessions :%d",
+          a2dp.a2dp_source_total_active_session_requests);
+    return 0;
+}
+
+int audio_extn_a2dp_stop_capture()
+{
+    int ret =0;
+
+    ALOGV("audio_extn_a2dp_stop_capture start");
+    if(!(a2dp.bt_lib_sink_handle && a2dp.audio_sink_stop)) {
+        ALOGE("a2dp handle is not identified, Ignoring stop request");
+        return -ENOSYS;
+    }
+
+    if (a2dp.a2dp_sink_total_active_session_requests > 0)
+        a2dp.a2dp_sink_total_active_session_requests--;
+
+    if ( a2dp.a2dp_sink_started && !a2dp.a2dp_sink_total_active_session_requests) {
+        ALOGV("calling BT module stream stop");
+        ret = a2dp.audio_sink_stop();
+        if (ret < 0)
+            ALOGE("stop stream to BT IPC lib failed");
+        else
+            ALOGV("stop steam to BT IPC lib successful");
+        reset_a2dp_dec_config_params();
+        a2dp_reset_backend_cfg(SINK);
+    }
+    if(!a2dp.a2dp_sink_total_active_session_requests)
+       a2dp.a2dp_source_started = false;
+    ALOGD("Stop A2DP capture, total active sessions :%d",
+          a2dp.a2dp_sink_total_active_session_requests);
     return 0;
 }
 
@@ -1304,7 +1768,7 @@
      struct listnode *node;
 
      if(a2dp.is_a2dp_offload_supported == false) {
-        ALOGV("no supported encoders identified,ignoring a2dp setparam");
+        ALOGV("no supported codecs identified,ignoring a2dp setparam");
         return;
      }
 
@@ -1313,8 +1777,8 @@
      if (ret >= 0) {
          val = atoi(value);
          if (audio_is_a2dp_out_device(val)) {
-             ALOGV("Received device connect request for A2DP");
-             open_a2dp_output();
+             ALOGV("Received device connect request for A2DP source");
+             open_a2dp_source();
          }
          goto param_handled;
      }
@@ -1325,20 +1789,25 @@
      if (ret >= 0) {
          val = atoi(value);
          if (audio_is_a2dp_out_device(val)) {
-             ALOGV("Received device dis- connect request");
+             ALOGV("Received source device dis- connect request");
              close_a2dp_output();
              reset_a2dp_enc_config_params();
-             a2dp_reset_backend_cfg();
+             a2dp_reset_backend_cfg(SOURCE);
+         } else if (audio_is_a2dp_in_device(val)) {
+             ALOGV("Received sink device dis- connect request");
+             close_a2dp_input();
+             reset_a2dp_dec_config_params();
+             a2dp_reset_backend_cfg(SINK);
          }
          goto param_handled;
      }
 
      ret = str_parms_get_str(parms, "A2dpSuspended", value, sizeof(value));
      if (ret >= 0) {
-         if (a2dp.bt_lib_handle && (a2dp.bt_state != A2DP_STATE_DISCONNECTED) ) {
+         if (a2dp.bt_lib_source_handle && (a2dp.bt_state_source != A2DP_STATE_DISCONNECTED) ) {
              if ((!strncmp(value,"true",sizeof(value)))) {
                 ALOGD("Setting a2dp to suspend state");
-                a2dp.a2dp_suspended = true;
+                a2dp.a2dp_source_suspended = true;
                 list_for_each(node, &a2dp.adev->usecase_list) {
                     uc_info = node_to_item(node, struct audio_usecase, list);
                     if (uc_info->type == PCM_PLAYBACK &&
@@ -1349,15 +1818,15 @@
                     }
                 }
                 reset_a2dp_enc_config_params();
-                if(a2dp.audio_suspend_stream)
-                   a2dp.audio_suspend_stream();
-            } else if (a2dp.a2dp_suspended == true) {
+                if(a2dp.audio_source_suspend)
+                   a2dp.audio_source_suspend();
+            } else if (a2dp.a2dp_source_suspended == true) {
                 ALOGD("Resetting a2dp suspend state");
                 struct audio_usecase *uc_info;
                 struct listnode *node;
-                if(a2dp.clear_a2dpsuspend_flag)
-                    a2dp.clear_a2dpsuspend_flag();
-                a2dp.a2dp_suspended = false;
+                if(a2dp.clear_source_a2dpsuspend_flag)
+                    a2dp.clear_source_a2dpsuspend_flag();
+                a2dp.a2dp_source_suspended = false;
                 /*
                  * It is possible that before suspend,a2dp sessions can be active
                  * for example during music + voice activation concurrency
@@ -1369,13 +1838,13 @@
                  * Fix is to call a2dp start for IPC library post suspend
                  * based on number of active session count
                  */
-                if (a2dp.a2dp_total_active_session_request > 0) {
+                if (a2dp.a2dp_source_total_active_session_requests > 0) {
                     ALOGD(" Calling IPC lib start post suspend state");
-                    if(a2dp.audio_start_stream) {
-                        ret =  a2dp.audio_start_stream();
+                    if(a2dp.audio_source_start) {
+                        ret =  a2dp.audio_source_start();
                         if (ret != 0) {
                             ALOGE("BT controller start failed");
-                            a2dp.a2dp_started = false;
+                            a2dp.a2dp_source_started = false;
                         }
                     }
                 }
@@ -1406,47 +1875,70 @@
     //During encoder reconfiguration mode, force a2dp device switch
     // Or if a2dp device is selected but earlier start failed ( as a2dp
     // was suspended, force retry.
-    return a2dp.is_handoff_in_progress || !a2dp.a2dp_started;
+    return a2dp.is_handoff_in_progress || !a2dp.a2dp_source_started;
 }
 
-void audio_extn_a2dp_get_sample_rate(int *sample_rate)
+void audio_extn_a2dp_get_enc_sample_rate(int *sample_rate)
 {
     *sample_rate = a2dp.enc_sampling_rate;
 }
 
-bool audio_extn_a2dp_is_ready()
+void audio_extn_a2dp_get_dec_sample_rate(int *sample_rate)
+{
+    *sample_rate = a2dp.dec_sampling_rate;
+}
+
+bool audio_extn_a2dp_source_is_ready()
 {
     bool ret = false;
 
-    if (a2dp.a2dp_suspended)
+    if (a2dp.a2dp_source_suspended)
         return ret;
 
-    if ((a2dp.bt_state != A2DP_STATE_DISCONNECTED) &&
+    if ((a2dp.bt_state_source != A2DP_STATE_DISCONNECTED) &&
         (a2dp.is_a2dp_offload_supported) &&
-        (a2dp.audio_check_a2dp_ready))
-           ret = a2dp.audio_check_a2dp_ready();
+        (a2dp.audio_source_check_a2dp_ready))
+           ret = a2dp.audio_source_check_a2dp_ready();
     return ret;
 }
 
-bool audio_extn_a2dp_is_suspended()
+bool audio_extn_a2dp_sink_is_ready()
 {
-    return a2dp.a2dp_suspended;
+    bool ret = false;
+
+    if ((a2dp.bt_state_sink != A2DP_STATE_DISCONNECTED) &&
+        (a2dp.is_a2dp_offload_supported) &&
+        (a2dp.audio_sink_check_a2dp_ready))
+           ret = a2dp.audio_sink_check_a2dp_ready();
+    return ret;
+}
+
+bool audio_extn_a2dp_source_is_suspended()
+{
+    return a2dp.a2dp_source_suspended;
 }
 
 void audio_extn_a2dp_init (void *adev)
 {
   a2dp.adev = (struct audio_device*)adev;
-  a2dp.bt_lib_handle = NULL;
-  a2dp.a2dp_started = false;
-  a2dp.bt_state = A2DP_STATE_DISCONNECTED;
-  a2dp.a2dp_total_active_session_request = 0;
-  a2dp.a2dp_suspended = false;
-  a2dp.bt_encoder_format = ENC_CODEC_TYPE_INVALID;
+  a2dp.bt_lib_source_handle = NULL;
+  a2dp.a2dp_source_started = false;
+  a2dp.bt_state_source = A2DP_STATE_DISCONNECTED;
+  a2dp.a2dp_source_total_active_session_requests = 0;
+  a2dp.a2dp_source_suspended = false;
+  a2dp.bt_encoder_format = CODEC_TYPE_INVALID;
   a2dp.enc_sampling_rate = 48000;
-  a2dp.is_a2dp_offload_supported = false;
   a2dp.is_handoff_in_progress = false;
   a2dp.is_aptx_dual_mono_supported = false;
   reset_a2dp_enc_config_params();
+
+  a2dp.bt_lib_sink_handle = NULL;
+  a2dp.a2dp_sink_started = false;
+  a2dp.bt_state_sink = A2DP_STATE_DISCONNECTED;
+  a2dp.a2dp_sink_total_active_session_requests = 0;
+  open_a2dp_sink();
+
+  a2dp.is_a2dp_offload_supported = false;
   update_offload_codec_capabilities();
 }
 
@@ -1469,32 +1961,32 @@
     }
 
     uint32_t slatency = 0;
-    if (a2dp.audio_get_a2dp_sink_latency && a2dp.bt_state != A2DP_STATE_DISCONNECTED) {
-        slatency = a2dp.audio_get_a2dp_sink_latency();
+    if (a2dp.audio_sink_get_a2dp_latency && a2dp.bt_state_source != A2DP_STATE_DISCONNECTED) {
+        slatency = a2dp.audio_sink_get_a2dp_latency();
     }
 
     switch(a2dp.bt_encoder_format) {
-        case ENC_CODEC_TYPE_SBC:
+        case CODEC_TYPE_SBC:
             latency = (avsync_runtime_prop > 0) ? sbc_offset : ENCODER_LATENCY_SBC;
             latency += (slatency <= 0) ? DEFAULT_SINK_LATENCY_SBC : slatency;
             break;
-        case ENC_CODEC_TYPE_APTX:
+        case CODEC_TYPE_APTX:
             latency = (avsync_runtime_prop > 0) ? aptx_offset : ENCODER_LATENCY_APTX;
             latency += (slatency <= 0) ? DEFAULT_SINK_LATENCY_APTX : slatency;
             break;
-        case ENC_CODEC_TYPE_APTX_HD:
+        case CODEC_TYPE_APTX_HD:
             latency = (avsync_runtime_prop > 0) ? aptxhd_offset : ENCODER_LATENCY_APTX_HD;
             latency += (slatency <= 0) ? DEFAULT_SINK_LATENCY_APTX_HD : slatency;
             break;
-        case ENC_CODEC_TYPE_AAC:
+        case CODEC_TYPE_AAC:
             latency = (avsync_runtime_prop > 0) ? aac_offset : ENCODER_LATENCY_AAC;
             latency += (slatency <= 0) ? DEFAULT_SINK_LATENCY_AAC : slatency;
             break;
-        case ENC_CODEC_TYPE_CELT:
+        case CODEC_TYPE_CELT:
             latency = (avsync_runtime_prop > 0) ? celt_offset : ENCODER_LATENCY_CELT;
             latency += (slatency <= 0) ? DEFAULT_SINK_LATENCY_CELT : slatency;
             break;
-        case ENC_CODEC_TYPE_LDAC:
+        case CODEC_TYPE_LDAC:
             latency = (avsync_runtime_prop > 0) ? ldac_offset : ENCODER_LATENCY_LDAC;
             latency += (slatency <= 0) ? DEFAULT_SINK_LATENCY_LDAC : slatency;
             break;
diff --git a/hal/audio_extn/audio_defs.h b/hal/audio_extn/audio_defs.h
index 0e1848e..a0b1949 100644
--- a/hal/audio_extn/audio_defs.h
+++ b/hal/audio_extn/audio_defs.h
@@ -306,4 +306,12 @@
     AUDIO_EXTN_PARAM_LICENSE_PARAMS,
 } audio_extn_param_id;
 
+typedef union {
+    struct audio_out_render_window_param render_window_params;
+} audio_extn_loopback_param_payload;
+
+typedef enum {
+    AUDIO_EXTN_PARAM_LOOPBACK_RENDER_WINDOW /* PARAM to set render window */
+} audio_extn_loopback_param_id;
+
 #endif /* AUDIO_DEFS_H */
diff --git a/hal/audio_extn/audio_extn.c b/hal/audio_extn/audio_extn.c
index c6c0924..3eee428 100755
--- a/hal/audio_extn/audio_extn.c
+++ b/hal/audio_extn/audio_extn.c
@@ -1478,6 +1478,33 @@
     return ret;
 }
 
+#ifdef AUDIO_HW_LOOPBACK_ENABLED
+int audio_extn_hw_loopback_set_param_data(audio_patch_handle_t handle,
+                                          audio_extn_loopback_param_id param_id,
+                                          audio_extn_loopback_param_payload *payload) {
+    int ret = -EINVAL;
+
+    if (!payload) {
+        ALOGE("%s:: Invalid Param",__func__);
+        return ret;
+    }
+
+    ALOGD("%d: %s: param id is %d\n", __LINE__, __func__, param_id);
+
+    switch(param_id) {
+        case AUDIO_EXTN_PARAM_LOOPBACK_RENDER_WINDOW:
+            ret = audio_extn_hw_loopback_set_render_window(handle, payload);
+            break;
+        default:
+            ALOGE("%s: unsupported param id %d", __func__, param_id);
+            break;
+    }
+
+    return ret;
+}
+#endif
+
+
 /* API to get playback stream specific config parameters */
 int audio_extn_out_get_param_data(struct stream_out *out,
                              audio_extn_param_id param_id,
diff --git a/hal/audio_extn/audio_extn.h b/hal/audio_extn/audio_extn.h
index 6ec07b3..3ad7db2 100644
--- a/hal/audio_extn/audio_extn.h
+++ b/hal/audio_extn/audio_extn.h
@@ -257,10 +257,14 @@
 #define audio_extn_a2dp_set_parameters(parms)            (0)
 #define audio_extn_a2dp_is_force_device_switch()         (0)
 #define audio_extn_a2dp_set_handoff_mode(is_on)          (0)
-#define audio_extn_a2dp_get_sample_rate(sample_rate)     (0)
+#define audio_extn_a2dp_get_enc_sample_rate(sample_rate) (0)
+#define audio_extn_a2dp_get_dec_sample_rate(sample_rate) (0)
 #define audio_extn_a2dp_get_encoder_latency()            (0)
-#define audio_extn_a2dp_is_ready()                       (0)
-#define audio_extn_a2dp_is_suspended()                   (0)
+#define audio_extn_a2dp_sink_is_ready()                  (0)
+#define audio_extn_a2dp_source_is_ready()                (0)
+#define audio_extn_a2dp_source_is_suspended()            (0)
+#define audio_extn_a2dp_start_capture()                  (0)
+#define audio_extn_a2dp_stop_capture()                   (0)
 #else
 void audio_extn_a2dp_init(void *adev);
 int audio_extn_a2dp_start_playback();
@@ -268,10 +272,14 @@
 void audio_extn_a2dp_set_parameters(struct str_parms *parms);
 bool audio_extn_a2dp_is_force_device_switch();
 void audio_extn_a2dp_set_handoff_mode(bool is_on);
-void audio_extn_a2dp_get_sample_rate(int *sample_rate);
+void audio_extn_a2dp_get_enc_sample_rate(int *sample_rate);
+void audio_extn_a2dp_get_dec_sample_rate(int *sample_rate);
 uint32_t audio_extn_a2dp_get_encoder_latency();
-bool audio_extn_a2dp_is_ready();
-bool audio_extn_a2dp_is_suspended();
+bool audio_extn_a2dp_sink_is_ready();
+bool audio_extn_a2dp_source_is_ready();
+bool audio_extn_a2dp_source_is_suspended();
+int audio_extn_a2dp_start_capture();
+int audio_extn_a2dp_stop_capture();
 #endif
 
 #ifndef SSR_ENABLED
@@ -999,6 +1007,14 @@
                                     const struct audio_port_config *config);
 int audio_extn_hw_loopback_get_audio_port(struct audio_hw_device *dev,
                                     struct audio_port *port_in);
+
+int audio_extn_hw_loopback_set_param_data(audio_patch_handle_t handle,
+                                          audio_extn_loopback_param_id param_id,
+                                          audio_extn_loopback_param_payload *payload);
+
+int audio_extn_hw_loopback_set_render_window(audio_patch_handle_t handle,
+                                             struct audio_out_render_window_param *render_window);
+
 int audio_extn_hw_loopback_init(struct audio_device *adev);
 void audio_extn_hw_loopback_deinit(struct audio_device *adev);
 #else
@@ -1026,6 +1042,18 @@
 {
     return -ENOSYS;
 }
+static int __unused audio_extn_hw_loopback_set_param_data(audio_patch_handle_t handle __unused,
+                                               audio_extn_loopback_param_id param_id __unused,
+                                               audio_extn_loopback_param_payload *payload __unused)
+{
+    return -ENOSYS;
+}
+
+static int __unused audio_extn_hw_loopback_set_render_window(audio_patch_handle_t handle __unused,
+                                     struct audio_out_render_window_param *render_window __unused)
+{
+    return -ENOSYS;
+}
 static int __unused audio_extn_hw_loopback_init(struct audio_device *adev __unused)
 {
     return -ENOSYS;
diff --git a/hal/audio_extn/hw_loopback.c b/hal/audio_extn/hw_loopback.c
index 990a283..055c42f 100644
--- a/hal/audio_extn/hw_loopback.c
+++ b/hal/audio_extn/hw_loopback.c
@@ -77,9 +77,9 @@
 typedef struct loopback_patch {
     audio_patch_handle_t patch_handle_id;            /* patch unique ID */
     struct audio_port_config loopback_source;        /* Source port config */
-    struct audio_port_config loopback_sink;          /* Source port config */
+    struct audio_port_config loopback_sink;          /* Sink port config */
     struct compress *source_stream;                  /* Source stream */
-    struct compress *sink_stream;                    /* Source stream */
+    struct compress *sink_stream;                    /* Sink stream */
     struct stream_inout patch_stream;                /* InOut type stream */
     patch_state_t patch_state;                       /* Patch operation state */
 } loopback_patch_t;
@@ -195,7 +195,9 @@
             case AUDIO_PORT_TYPE_DEVICE :
                 if ((loopback_patch->loopback_source.config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
                     if ((loopback_patch->loopback_source.ext.device.type & AUDIO_DEVICE_IN_HDMI) ||
-                        (loopback_patch->loopback_source.ext.device.type & AUDIO_DEVICE_IN_SPDIF)) {
+                        (loopback_patch->loopback_source.ext.device.type & AUDIO_DEVICE_IN_SPDIF) ||
+                        (loopback_patch->loopback_source.ext.device.type & AUDIO_DEVICE_IN_BLUETOOTH_A2DP)) {
+
                        switch (loopback_patch->loopback_source.format) {
                            case AUDIO_FORMAT_PCM:
                            case AUDIO_FORMAT_PCM_16_BIT:
@@ -204,6 +206,10 @@
                            case AUDIO_FORMAT_IEC61937:
                            case AUDIO_FORMAT_AC3:
                            case AUDIO_FORMAT_E_AC3:
+                           case AUDIO_FORMAT_AAC_LATM_LC:
+                           case AUDIO_FORMAT_AAC_LATM_HE_V1:
+                           case AUDIO_FORMAT_AAC_LATM_HE_V2:
+                           case AUDIO_FORMAT_SBC:
                               is_source_supported = true;
                            break;
                        }
@@ -213,8 +219,8 @@
                 }
             break;
             default :
-            break;
-            //Unsupported as of now, need to extend for other source types
+                //Unsupported as of now, need to extend for other source types
+                break;
         }
     }
 
@@ -240,14 +246,13 @@
             }
             break;
         default :
-            break;
             //Unsupported as of now, need to extend for other sink types
+            break;
         }
     }
     if (is_source_supported && is_sink_supported) {
         return source_device | sink_device;
     }
-
     ALOGE("%s, Unsupported source or sink port config", __func__);
     return loopback_patch->patch_handle_id;
 }
@@ -357,6 +362,78 @@
     return 0;
 }
 
+#ifdef SNDRV_COMPRESS_RENDER_WINDOW
+static loopback_patch_t *get_active_loopback_patch(audio_patch_handle_t handle)
+{
+    int n = 0;
+    int patch_index = -1;
+    loopback_patch_t *active_loopback_patch = NULL;
+
+    for (n=0; n < MAX_NUM_PATCHES; n++) {
+        if (audio_loopback_mod->patch_db.num_patches > 0) {
+            if (audio_loopback_mod->patch_db.loopback_patch[n].patch_handle_id == handle) {
+                patch_index = n;
+                break;
+            }
+        } else {
+            ALOGE("%s, No active audio loopback patch", __func__);
+            return active_loopback_patch;
+        }
+    }
+
+    if ((patch_index > -1) && (patch_index < MAX_NUM_PATCHES))
+        active_loopback_patch = &(audio_loopback_mod->patch_db.loopback_patch[
+                                patch_index]);
+    else
+        ALOGE("%s, Requested Patch handle does not exist", __func__);
+
+    return active_loopback_patch;
+}
+
+int audio_extn_hw_loopback_set_render_window(audio_patch_handle_t handle,
+                      struct audio_out_render_window_param *render_window)
+{
+    struct snd_compr_metadata metadata = {0};
+    int ret = 0;
+    loopback_patch_t *active_loopback_patch = get_active_loopback_patch(handle);
+
+    if (active_loopback_patch == NULL) {
+        ALOGE("%s: Invalid patch handle", __func__);
+        ret = -EINVAL;
+        goto exit;
+    }
+
+    if (render_window == NULL) {
+        ALOGE("%s: Invalid render_window", __func__);
+        ret = -EINVAL;
+        goto exit;
+    }
+
+    metadata.key = SNDRV_COMPRESS_RENDER_WINDOW;
+    /*render window start value */
+    metadata.value[0] = 0xFFFFFFFF & render_window->render_ws; /* lsb */
+    metadata.value[1] = \
+            (0xFFFFFFFF00000000 & render_window->render_ws) >> 32; /* msb*/
+    /*render window end value */
+    metadata.value[2] = 0xFFFFFFFF & render_window->render_we; /* lsb */
+    metadata.value[3] = \
+            (0xFFFFFFFF00000000 & render_window->render_we) >> 32; /* msb*/
+
+    ret = compress_set_metadata(active_loopback_patch->sink_stream, &metadata);
+
+exit:
+    return ret;
+}
+#else
+int audio_extn_hw_loopback_set_render_window(struct audio_hw_device *dev,
+                      audio_patch_handle_t handle __unused,
+                      struct audio_out_render_window_param *render_window __unused)
+{
+    ALOGD("%s:: configuring render window not supported", __func__);
+    return 0;
+}
+#endif
+
 #if defined SNDRV_COMPRESS_LATENCY_MODE
 static void transcode_loopback_util_set_latency_mode(
                              loopback_patch_t *active_loopback_patch,
diff --git a/hal/audio_extn/utils.c b/hal/audio_extn/utils.c
index bd3fa7c..501421c 100644
--- a/hal/audio_extn/utils.c
+++ b/hal/audio_extn/utils.c
@@ -990,7 +990,14 @@
         if (usecase->id == USECASE_AUDIO_PLAYBACK_VOIP) {
             usecase->stream.out->app_type_cfg.sample_rate = usecase->stream.out->sample_rate;
         } else if (usecase->stream.out->devices & AUDIO_DEVICE_OUT_SPEAKER) {
-            usecase->stream.out->app_type_cfg.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
+            if (platform_spkr_use_default_sample_rate(adev->platform)) {
+                 usecase->stream.out->app_type_cfg.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
+            } else {
+                 platform_check_and_update_copp_sample_rate(adev->platform, snd_device,
+                                      usecase->stream.out->sample_rate,
+                                      &usecase->stream.out->app_type_cfg.sample_rate);
+            }
+
         } else if ((snd_device == SND_DEVICE_OUT_HDMI ||
                     snd_device == SND_DEVICE_OUT_USB_HEADSET ||
                     snd_device == SND_DEVICE_OUT_DISPLAY_PORT) &&
@@ -1014,7 +1021,7 @@
                   * For a2dp playback get encoder sampling rate and set copp sampling rate,
                   * for bit width use the stream param only.
                   */
-                   audio_extn_a2dp_get_sample_rate(&usecase->stream.out->app_type_cfg.sample_rate);
+                   audio_extn_a2dp_get_enc_sample_rate(&usecase->stream.out->app_type_cfg.sample_rate);
                    ALOGI("%s using %d sample rate rate for A2DP CoPP",
                         __func__, usecase->stream.out->app_type_cfg.sample_rate);
         }
@@ -1066,6 +1073,11 @@
         } else {
             audio_extn_btsco_get_sample_rate(snd_device, &usecase->stream.in->app_type_cfg.sample_rate);
         }
+        if (usecase->stream.in->device & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
+            audio_extn_a2dp_get_dec_sample_rate(&usecase->stream.in->app_type_cfg.sample_rate);
+            ALOGI("%s using %d sample rate rate for A2DP dec CoPP",
+                  __func__, usecase->stream.in->app_type_cfg.sample_rate);
+        }
         sample_rate = usecase->stream.in->app_type_cfg.sample_rate;
         app_type_cfg[len++] = sample_rate;
         if (snd_device_be_idx > 0)
diff --git a/hal/audio_hw.c b/hal/audio_hw.c
index cb2d786..dace3ac 100644
--- a/hal/audio_hw.c
+++ b/hal/audio_hw.c
@@ -1072,7 +1072,13 @@
 
        if ((SND_DEVICE_OUT_BT_A2DP == snd_device) &&
            (audio_extn_a2dp_start_playback() < 0)) {
-           ALOGE(" fail to configure A2dp control path ");
+           ALOGE(" fail to configure A2dp Source control path ");
+           return -EINVAL;
+       }
+
+       if ((SND_DEVICE_IN_BT_A2DP == snd_device) &&
+           (audio_extn_a2dp_start_capture() < 0)) {
+           ALOGE(" fail to configure A2dp Sink control path ");
            return -EINVAL;
        }
 
@@ -1160,6 +1166,9 @@
         if (SND_DEVICE_OUT_BT_A2DP == snd_device)
             audio_extn_a2dp_stop_playback();
 
+        if (SND_DEVICE_IN_BT_A2DP == snd_device)
+            audio_extn_a2dp_stop_capture();
+
         if (snd_device == SND_DEVICE_OUT_HDMI || snd_device == SND_DEVICE_OUT_DISPLAY_PORT)
             adev->is_channel_status_set = false;
         else if (SND_DEVICE_OUT_HEADPHONES == snd_device &&
@@ -1961,12 +1970,12 @@
         audio_extn_a2dp_is_force_device_switch()) {
          ALOGD("Force a2dp device switch to update new encoder config");
          ret = true;
-     }
+    }
 
-     if (usecase->stream.out->stream_config_changed) {
+    if (usecase->stream.out->stream_config_changed) {
          ALOGD("Force stream_config_changed to update iec61937 transmission config");
          return true;
-     }
+    }
     return ret;
 }
 
@@ -2125,11 +2134,18 @@
             if (out_snd_device == SND_DEVICE_NONE) {
                 out_snd_device = platform_get_output_snd_device(adev->platform,
                                             usecase->stream.out);
-                if (usecase->stream.out == adev->primary_output &&
-                        adev->active_input &&
-                        out_snd_device != usecase->out_snd_device) {
-                    select_devices(adev, adev->active_input->usecase);
-                }
+                   voip_usecase = get_usecase_from_list(adev, USECASE_AUDIO_PLAYBACK_VOIP);
+                   if (voip_usecase == NULL && adev->primary_output && !adev->primary_output->standby)
+                       voip_usecase = get_usecase_from_list(adev, adev->primary_output->usecase);
+
+                   if ((usecase->stream.out != NULL &&
+                        voip_usecase != NULL &&
+                        usecase->stream.out->usecase == voip_usecase->id) &&
+                       adev->active_input &&
+                       adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
+                       out_snd_device != usecase->out_snd_device) {
+                       select_devices(adev, adev->active_input->usecase);
+                   }
             }
         } else if (usecase->type == PCM_CAPTURE) {
             if (usecase->stream.in == NULL) {
@@ -2143,9 +2159,12 @@
                 if (adev->active_input &&
                     (adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
                     (adev->mode == AUDIO_MODE_IN_COMMUNICATION &&
-                     adev->active_input->source == AUDIO_SOURCE_MIC)) &&
-                     adev->primary_output && !adev->primary_output->standby) {
-                    out_device = adev->primary_output->devices;
+                     adev->active_input->source == AUDIO_SOURCE_MIC))) {
+                    voip_usecase = get_usecase_from_list(adev, USECASE_AUDIO_PLAYBACK_VOIP);
+                    if (voip_usecase != NULL && voip_usecase->stream.out != NULL)
+                        out_device = voip_usecase->stream.out->devices;
+                    else if (adev->primary_output && !adev->primary_output->standby)
+                        out_device = adev->primary_output->devices;
                     platform_set_echo_reference(adev, false, AUDIO_DEVICE_NONE);
                 } else if (usecase->id == USECASE_AUDIO_RECORD_AFE_PROXY) {
                     out_device = AUDIO_DEVICE_OUT_TELEPHONY_TX;
@@ -2163,7 +2182,7 @@
     }
 
     if ((is_btsco_device(out_snd_device,in_snd_device) && !adev->bt_sco_on) ||
-         (is_a2dp_device(out_snd_device) && !audio_extn_a2dp_is_ready())) {
+         (is_a2dp_device(out_snd_device) && !audio_extn_a2dp_source_is_ready())) {
           ALOGD("SCO/A2DP is selected but they are not connected/ready hence dont route");
           return 0;
     }
@@ -2197,7 +2216,7 @@
     }
 
     if ((out_snd_device == SND_DEVICE_OUT_SPEAKER_AND_BT_A2DP) &&
-        (!audio_extn_a2dp_is_ready())) {
+        (!audio_extn_a2dp_source_is_ready())) {
         ALOGW("%s: A2DP profile is not ready, routing to speaker only", __func__);
         out_snd_device = SND_DEVICE_OUT_SPEAKER;
     }
@@ -2970,7 +2989,7 @@
     }
 
     if (out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) {
-        if (!audio_extn_a2dp_is_ready()) {
+        if (!audio_extn_a2dp_source_is_ready()) {
             if (out->devices & AUDIO_DEVICE_OUT_SPEAKER) {
                 a2dp_combo = true;
             } else {
@@ -3032,7 +3051,7 @@
     }
 
     if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
-        (!audio_extn_a2dp_is_ready())) {
+        (!audio_extn_a2dp_source_is_ready())) {
         if (!a2dp_combo) {
             check_a2dp_restore_l(adev, out, false);
         } else {
@@ -3309,6 +3328,8 @@
                                     int channel_count,
                                     bool is_low_latency)
 {
+    int i = 0;
+    size_t frame_size = 0;
     size_t size = 0;
 
     if (check_input_parameters(sample_rate, format, channel_count) != 0)
@@ -3318,15 +3339,23 @@
     if (is_low_latency)
         size = configured_low_latency_capture_period_size;
 
-    size *= audio_bytes_per_sample(format) * channel_count;
+    frame_size = audio_bytes_per_sample(format) * channel_count;
+    size *= frame_size;
 
-    /* make sure the size is multiple of 32 bytes
+    /* make sure the size is multiple of 32 bytes and additionally multiple of
+     * the frame_size (required for 24bit samples and non-power-of-2 channel counts)
      * At 48 kHz mono 16-bit PCM:
      *  5.000 ms = 240 frames = 15*16*1*2 = 480, a whole multiple of 32 (15)
      *  3.333 ms = 160 frames = 10*16*1*2 = 320, a whole multiple of 32 (10)
+     *
+     *  The loop reaches result within 32 iterations, as initial size is
+     *  already a multiple of frame_size
      */
-    size += 0x1f;
-    size &= ~0x1f;
+    for (i=0; i<32; i++) {
+        if ((size & 0x1f) == 0)
+            break;
+        size += frame_size;
+    }
 
     return size;
 }
@@ -3697,13 +3726,13 @@
         /*
          * When A2DP is disconnected the
          * music playback is paused and the policy manager sends routing=0
-         * But the audioflingercontinues to write data until standby time
+         * But the audioflinger continues to write data until standby time
          * (3sec). As BT is turned off, the write gets blocked.
          * Avoid this by routing audio to speaker until standby.
          */
         if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
                 (val == AUDIO_DEVICE_NONE) &&
-                !audio_extn_a2dp_is_ready()) {
+                !audio_extn_a2dp_source_is_ready()) {
                 val = AUDIO_DEVICE_OUT_SPEAKER;
         }
         /*
@@ -3722,7 +3751,7 @@
          * check with BT lib about a2dp streaming support before routing
          */
         if (val & AUDIO_DEVICE_OUT_ALL_A2DP) {
-            if (!audio_extn_a2dp_is_ready()) {
+            if (!audio_extn_a2dp_source_is_ready()) {
                 if (val & AUDIO_DEVICE_OUT_SPEAKER) {
                     //combo usecase just by pass a2dp
                     ALOGW("%s: A2DP profile is not ready,routing to speaker only", __func__);
@@ -3817,7 +3846,7 @@
                 }
                 if ((out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
                     out->a2dp_compress_mute &&
-                    (!(out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) || audio_extn_a2dp_is_ready())) {
+                    (!(out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) || audio_extn_a2dp_source_is_ready())) {
                     pthread_mutex_lock(&out->compr_mute_lock);
                     out->a2dp_compress_mute = false;
                     out_set_compr_volume(&out->stream, out->volume_l, out->volume_r);
@@ -4432,7 +4461,7 @@
     }
 
     if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
-        (audio_extn_a2dp_is_suspended())) {
+        (audio_extn_a2dp_source_is_suspended())) {
         if (!(out->devices & AUDIO_DEVICE_OUT_SPEAKER)) {
             if (!(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
                 ret = -EIO;
@@ -4502,6 +4531,15 @@
                 audio_format_t dst_format = out->hal_op_format;
                 audio_format_t src_format = out->hal_ip_format;
 
+                /* prevent division-by-zero */
+                uint32_t bitwidth_src = format_to_bitwidth_table[src_format];
+                uint32_t bitwidth_dst = format_to_bitwidth_table[dst_format];
+                if ((bitwidth_src == 0) || (bitwidth_dst == 0)) {
+                    ALOGE("%s: Error bitwidth == 0", __func__);
+                    ATRACE_END();
+                    return -EINVAL;
+                }
+
                 uint32_t frames = bytes / format_to_bitwidth_table[src_format];
                 uint32_t bytes_to_write = frames * format_to_bitwidth_table[dst_format];
 
@@ -4642,10 +4680,18 @@
             out->standby = true;
         }
         out_on_error(&out->stream.common);
-        if (!(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))
-            usleep((uint64_t)bytes * 1000000 / audio_stream_out_frame_size(stream) /
-                            out_get_sample_rate(&out->stream.common));
+        if (!(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
+            /* prevent division-by-zero */
+            uint32_t stream_size = audio_stream_out_frame_size(stream);
+            uint32_t srate = out_get_sample_rate(&out->stream.common);
 
+            if ((stream_size == 0) || (srate == 0)) {
+                ALOGE("%s: stream_size= %d, srate = %d", __func__, stream_size, srate);
+                ATRACE_END();
+                return -EINVAL;
+             }
+             usleep((uint64_t)bytes * 1000000 / stream_size / srate);
+        }
         if (audio_extn_passthru_is_passthrough_stream(out)) {
                 ALOGE("%s: write error, ret = %zd", __func__, ret);
                 ATRACE_END();
@@ -7079,6 +7125,13 @@
                                             config->format,
                                             channel_count,
                                             is_low_latency);
+            /* prevent division-by-zero */
+            if (frame_size == 0) {
+                ALOGE("%s: Error frame_size==0", __func__);
+                ret = -EINVAL;
+                goto err_open;
+            }
+
             in->config.period_size = buffer_size / frame_size;
 
             if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
diff --git a/hal/audio_hw_extn_api.c b/hal/audio_hw_extn_api.c
index f5e0659..44591c9 100644
--- a/hal/audio_hw_extn_api.c
+++ b/hal/audio_hw_extn_api.c
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
+* Copyright (c) 2016-2017, 2018, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
@@ -423,6 +423,19 @@
     return ret;
 }
 
+int qahwi_loopback_set_param_data(audio_patch_handle_t handle,
+                                  audio_extn_loopback_param_id param_id,
+                                  audio_extn_loopback_param_payload *payload) {
+    int ret = 0;
+
+    ret = audio_extn_hw_loopback_set_param_data(
+                                             handle,
+                                             param_id,
+                                             payload);
+
+    return ret;
+}
+
 void qahwi_init(hw_device_t *device)
 {
     struct audio_device *adev = (struct audio_device *) device;
diff --git a/hal/edid.h b/hal/edid.h
index da5c592..f920a82 100644
--- a/hal/edid.h
+++ b/hal/edid.h
@@ -57,6 +57,27 @@
 #define PCM_CHANNEL_FRC  14  /* Front right of center.                        */
 #define PCM_CHANNEL_RLC  15  /* Rear left of center.                          */
 #define PCM_CHANNEL_RRC  16  /* Rear right of center.                         */
+#define PCM_CHANNEL_LFE2 17  /* Second low frequency channel.                 */
+#define PCM_CHANNEL_SL   18  /* Side left channel.                            */
+#define PCM_CHANNEL_SR   19  /* Side right channel.                           */
+#define PCM_CHANNEL_TFL  20  /* Top front left channel.                       */
+#define PCM_CHANNEL_LVH  20  /* Left vertical height channel.                 */
+#define PCM_CHANNEL_TFR  21  /* Top front right channel.                      */
+#define PCM_CHANNEL_RVH  21  /* Right vertical height channel.                */
+#define PCM_CHANNEL_TC   22  /* Top center channel.                           */
+#define PCM_CHANNEL_TBL  23  /* Top back left channel.                        */
+#define PCM_CHANNEL_TBR  24  /* Top back right channel.                       */
+#define PCM_CHANNEL_TSL  25  /* Top side left channel.                        */
+#define PCM_CHANNEL_TSR  26  /* Top side right channel.                       */
+#define PCM_CHANNEL_TBC  27  /* Top back center channel.                      */
+#define PCM_CHANNEL_BFC  28  /* Bottom front center channel.                  */
+#define PCM_CHANNEL_BFL  29  /* Bottom front left channel.                    */
+#define PCM_CHANNEL_BFR  30  /* Bottom front right channel.                   */
+#define PCM_CHANNEL_LW   31  /* Left wide channel.                            */
+#define PCM_CHANNEL_RW   32  /* Right wide channel.                           */
+#define PCM_CHANNEL_LSD  33  /* Left side direct channel.                     */
+#define PCM_CHANNEL_RSD  34  /* Right side direct channel.                    */
+
 
 #define MAX_HDMI_CHANNEL_CNT 8
 
diff --git a/hal/msm8916/platform.c b/hal/msm8916/platform.c
old mode 100755
new mode 100644
index 82fafc7..68ffd56
--- a/hal/msm8916/platform.c
+++ b/hal/msm8916/platform.c
@@ -298,6 +298,7 @@
     struct acdb_init_data_v4 acdb_init_data;
     bool use_generic_handset;
     struct  spkr_device_chmap *spkr_ch_map;
+    bool use_sprk_default_sample_rate;
 };
 
 struct  spkr_device_chmap {
@@ -2290,6 +2291,7 @@
     my_data->hw_dep_fd = -1;
     my_data->mono_speaker = SPKR_1;
     my_data->spkr_ch_map = NULL;
+    my_data->use_sprk_default_sample_rate = true;
 
     be_dai_name_table = NULL;
 
@@ -2831,6 +2833,9 @@
     /* free acdb_meta_key_list */
     platform_release_acdb_metainfo_key(platform);
 
+    if (my_data->acdb_deallocate)
+        my_data->acdb_deallocate();
+
     free(platform);
     /* deinit usb */
     audio_extn_usb_deinit();
@@ -4688,6 +4693,16 @@
               (mode == AUDIO_MODE_IN_COMMUNICATION)) {
         if (out_device & AUDIO_DEVICE_OUT_SPEAKER)
             in_device = AUDIO_DEVICE_IN_BACK_MIC;
+        else if (out_device & AUDIO_DEVICE_OUT_EARPIECE)
+            in_device = AUDIO_DEVICE_IN_BUILTIN_MIC;
+        else if (out_device & AUDIO_DEVICE_OUT_WIRED_HEADSET)
+            in_device = AUDIO_DEVICE_IN_WIRED_HEADSET;
+        else if (out_device & AUDIO_DEVICE_OUT_USB_DEVICE)
+             in_device = AUDIO_DEVICE_IN_USB_DEVICE;
+
+        in_device = ((out_device == AUDIO_DEVICE_NONE) ?
+                      AUDIO_DEVICE_IN_BUILTIN_MIC : in_device) & ~AUDIO_DEVICE_BIT_IN;
+
         if (adev->active_input) {
             snd_device = get_snd_device_for_voice_comm(my_data, out_device, in_device);
         }
@@ -7385,6 +7400,11 @@
     platform_get_edid_info(platform);
 }
 
+bool platform_spkr_use_default_sample_rate(void *platform) {
+    struct platform_data *my_data = (struct platform_data *)platform;
+    return my_data->use_sprk_default_sample_rate;
+}
+
 void platform_invalidate_backend_config(void * platform,snd_device_t snd_device)
 {
     struct platform_data *my_data = (struct platform_data *)platform;
diff --git a/hal/msm8916/platform.h b/hal/msm8916/platform.h
index 8bb0a3c..3bcba3a 100644
--- a/hal/msm8916/platform.h
+++ b/hal/msm8916/platform.h
@@ -183,6 +183,7 @@
     SND_DEVICE_IN_BT_SCO_MIC_NREC,
     SND_DEVICE_IN_BT_SCO_MIC_WB,
     SND_DEVICE_IN_BT_SCO_MIC_WB_NREC,
+    SND_DEVICE_IN_BT_A2DP,
     SND_DEVICE_IN_CAMCORDER_MIC,
     SND_DEVICE_IN_VOICE_DMIC,
     SND_DEVICE_IN_VOICE_SPEAKER_DMIC,
diff --git a/hal/msm8974/hw_info.c b/hal/msm8974/hw_info.c
old mode 100644
new mode 100755
index 1b46bf4..84d533e
--- a/hal/msm8974/hw_info.c
+++ b/hal/msm8974/hw_info.c
@@ -548,6 +548,9 @@
     } else if (!strncmp(snd_card_name, "qcs605-lc-snd-card",
                  sizeof("qcs605-lc-snd-card"))) {
         strlcpy(hw_info->name, "qcs605-lc", sizeof(hw_info->name));
+    } else if (!strncmp(snd_card_name, "qcs605-ipc-tavil-snd-card",
+                 sizeof("qcs605-ipc-tavil-snd-card"))) {
+        strlcpy(hw_info->name, "qcs605-ipc", sizeof(hw_info->name));
     } else if (!strncmp(snd_card_name, "sdm660-tavil-snd-card",
                       sizeof("sdm660-tavil-snd-card"))) {
         strlcpy(hw_info->name, "sdm660", sizeof(hw_info->name));
@@ -613,7 +616,8 @@
         ALOGV("SDM845 - variant soundcard");
         update_hardware_info_sdm845(hw_info, snd_card_name);
     } else if (strstr(snd_card_name, "sdm660") || strstr(snd_card_name, "sdm670") ||
-        strstr(snd_card_name, "qcs605-lc") || strstr(snd_card_name, "qcs405")) {
+        strstr(snd_card_name, "qcs605-lc") || strstr(snd_card_name, "qcs405") ||
+        strstr(snd_card_name, "qcs605-ipc")) {
         ALOGV("Bear - variant soundcard");
         update_hardware_info_bear(hw_info, snd_card_name);
     } else if (strstr(snd_card_name, "sdx")) {
diff --git a/hal/msm8974/platform.c b/hal/msm8974/platform.c
index 128a458..4df343f 100644
--- a/hal/msm8974/platform.c
+++ b/hal/msm8974/platform.c
@@ -65,6 +65,7 @@
 #define MIXER_XML_PATH_I2S "/etc/mixer_paths_i2s.xml"
 #define PLATFORM_INFO_XML_PATH_I2S "/etc/audio_platform_info_extcodec.xml"
 #define PLATFORM_INFO_XML_PATH_WSA  "/etc/audio_platform_info_wsa.xml"
+#define PLATFORM_INFO_XML_PATH_TDM  "/etc/audio_platform_info_tdm.xml"
 #else
 #define MIXER_XML_BASE_STRING "/vendor/etc/mixer_paths"
 #define MIXER_XML_DEFAULT_PATH "/vendor/etc/mixer_paths.xml"
@@ -76,6 +77,7 @@
 #define MIXER_XML_PATH_I2S "/vendor/etc/mixer_paths_i2s.xml"
 #define PLATFORM_INFO_XML_PATH_I2S "/vendor/etc/audio_platform_info_i2s.xml"
 #define PLATFORM_INFO_XML_PATH_WSA  "/vendor/etc/audio_platform_info_wsa.xml"
+#define PLATFORM_INFO_XML_PATH_TDM  "/vendor/etc/audio_platform_info_tdm.xml"
 #endif
 
 #include <linux/msm_audio.h>
@@ -121,7 +123,6 @@
 /* Mixer path names */
 #define AFE_SIDETONE_MIXER_PATH "afe-sidetone"
 
-#define AUDIO_PARAMETER_KEY_FLUENCE_TYPE  "fluence"
 #define AUDIO_PARAMETER_KEY_SLOWTALK      "st_enable"
 #define AUDIO_PARAMETER_KEY_HD_VOICE      "hd_voice"
 #define AUDIO_PARAMETER_KEY_VOLUME_BOOST  "volume_boost"
@@ -130,6 +131,15 @@
 
 #define AUDIO_PARAMETER_KEY_MONO_SPEAKER "mono_speaker"
 
+#define AUDIO_PARAMETER_KEY_FLUENCE_TYPE        "fluence_type"
+#define AUDIO_PARAMETER_KEY_FLUENCE_VOICE_CALL  "fluence_voice"
+#define AUDIO_PARAMETER_KEY_FLUENCE_VOICE_REC   "fluence_voice_rec"
+#define AUDIO_PARAMETER_KEY_FLUENCE_AUDIO_REC   "fluence_audio_rec"
+#define AUDIO_PARAMETER_KEY_FLUENCE_SPEAKER     "fluence_speaker"
+#define AUDIO_PARAMETER_KEY_FLUENCE_MODE        "fluence_mode"
+#define AUDIO_PARAMETER_KEY_FLUENCE_HFPCALL     "fluence_hfp"
+#define AUDIO_PARAMETER_KEY_FLUENCE_TRI_MIC     "fluence_tri_mic"
+
 #define AUDIO_PARAMETER_KEY_PERF_LOCK_OPTS "perf_lock_opts"
 
 /* Reload ACDB files from specified path */
@@ -276,6 +286,7 @@
     struct acdb_init_data_v4 acdb_init_data;
     bool use_generic_handset;
     struct  spkr_device_chmap *spkr_ch_map;
+    bool use_sprk_default_sample_rate;
 };
 
 struct  spkr_device_chmap {
@@ -488,6 +499,7 @@
     [SND_DEVICE_IN_BT_SCO_MIC_NREC] = "bt-sco-mic",
     [SND_DEVICE_IN_BT_SCO_MIC_WB] = "bt-sco-mic-wb",
     [SND_DEVICE_IN_BT_SCO_MIC_WB_NREC] = "bt-sco-mic-wb",
+    [SND_DEVICE_IN_BT_A2DP] = "bt-a2dp-cap",
     [SND_DEVICE_IN_CAMCORDER_MIC] = "camcorder-mic",
     [SND_DEVICE_IN_VOICE_DMIC] = "voice-dmic-ef",
     [SND_DEVICE_IN_VOICE_SPEAKER_DMIC] = "voice-speaker-dmic-ef",
@@ -657,6 +669,7 @@
     [SND_DEVICE_IN_BT_SCO_MIC_NREC] = 122,
     [SND_DEVICE_IN_BT_SCO_MIC_WB] = 38,
     [SND_DEVICE_IN_BT_SCO_MIC_WB_NREC] = 123,
+    [SND_DEVICE_IN_BT_A2DP] = 21,
     [SND_DEVICE_IN_CAMCORDER_MIC] = 4,
     [SND_DEVICE_IN_VOICE_DMIC] = 41,
     [SND_DEVICE_IN_VOICE_SPEAKER_DMIC] = 43,
@@ -808,6 +821,7 @@
     {TO_NAME_INDEX(SND_DEVICE_IN_BT_SCO_MIC_NREC)},
     {TO_NAME_INDEX(SND_DEVICE_IN_BT_SCO_MIC_WB)},
     {TO_NAME_INDEX(SND_DEVICE_IN_BT_SCO_MIC_WB_NREC)},
+    {TO_NAME_INDEX(SND_DEVICE_IN_BT_A2DP)},
     {TO_NAME_INDEX(SND_DEVICE_IN_CAMCORDER_MIC)},
     {TO_NAME_INDEX(SND_DEVICE_IN_VOICE_DMIC)},
     {TO_NAME_INDEX(SND_DEVICE_IN_VOICE_SPEAKER_DMIC)},
@@ -1420,6 +1434,7 @@
     backend_tag_table[SND_DEVICE_OUT_VOICE_SPEAKER_VBAT] = strdup("voice-speaker-vbat");
     backend_tag_table[SND_DEVICE_OUT_VOICE_SPEAKER_2_VBAT] = strdup("voice-speaker-2-vbat");
     backend_tag_table[SND_DEVICE_OUT_BT_A2DP] = strdup("bt-a2dp");
+    backend_tag_table[SND_DEVICE_IN_BT_A2DP] = strdup("bt-a2dp-cap");
     backend_tag_table[SND_DEVICE_OUT_SPEAKER_AND_BT_A2DP] = strdup("speaker-and-bt-a2dp");
     backend_tag_table[SND_DEVICE_OUT_VOICE_SPEAKER_AND_VOICE_HEADPHONES] = strdup("speaker-and-headphones");
     backend_tag_table[SND_DEVICE_OUT_VOICE_SPEAKER_AND_VOICE_ANC_HEADSET] = strdup("speaker-and-headphones");
@@ -1514,6 +1529,7 @@
     hw_interface_table[SND_DEVICE_IN_BT_SCO_MIC_NREC] = strdup("SLIMBUS_7_TX");
     hw_interface_table[SND_DEVICE_IN_BT_SCO_MIC_WB] = strdup("SLIMBUS_7_TX");
     hw_interface_table[SND_DEVICE_IN_BT_SCO_MIC_WB_NREC] = strdup("SLIMBUS_7_TX");
+    hw_interface_table[SND_DEVICE_IN_BT_A2DP] = strdup("SLIMBUS_7_TX");
     hw_interface_table[SND_DEVICE_IN_CAMCORDER_MIC] = strdup("SLIMBUS_0_TX");
     hw_interface_table[SND_DEVICE_IN_VOICE_DMIC] = strdup("SLIMBUS_0_TX");
     hw_interface_table[SND_DEVICE_IN_VOICE_SPEAKER_DMIC] = strdup("SLIMBUS_0_TX");
@@ -2096,7 +2112,7 @@
     my_data->mono_speaker = SPKR_1;
     my_data->speaker_lr_swap = false;
     my_data->spkr_ch_map = NULL;
-
+    my_data->use_sprk_default_sample_rate = true;
     be_dai_name_table = NULL;
 
     property_get("ro.vendor.audio.sdk.fluencetype", my_data->fluence_cap, "");
@@ -2177,11 +2193,23 @@
     else if (!strncmp(snd_card_name, "qcs405-wsa-snd-card",
                sizeof("qcs405-wsa-snd-card")))
         platform_info_init(PLATFORM_INFO_XML_PATH_WSA, my_data, PLATFORM);
+    else if (!strncmp(snd_card_name, "qcs405-tdm-snd-card",
+               sizeof("qcs405-tdm-snd-card")))
+        platform_info_init(PLATFORM_INFO_XML_PATH_TDM, my_data, PLATFORM);
     else if (my_data->is_internal_codec)
         platform_info_init(PLATFORM_INFO_XML_PATH_INTCODEC, my_data, PLATFORM);
     else
         platform_info_init(PLATFORM_INFO_XML_PATH, my_data, PLATFORM);
 
+    /* CSRA devices support multiple sample rates via I2S at spkr out */
+    if (!strncmp(snd_card_name, "qcs405-csra", strlen("qcs405-csra"))) {
+        ALOGE("%s: soundcard: %s supports multiple sample rates", __func__, snd_card_name);
+        my_data->use_sprk_default_sample_rate = false;
+    } else {
+        my_data->use_sprk_default_sample_rate = true;
+        ALOGE("%s: soundcard: %s supports only default sample rate", __func__, snd_card_name);
+    }
+
     my_data->voice_feature_set = VOICE_FEATURE_SET_DEFAULT;
     my_data->acdb_handle = dlopen(LIB_ACDB_LOADER, RTLD_NOW);
     if (my_data->acdb_handle == NULL) {
@@ -2437,11 +2465,18 @@
 
     } else {
         if (!strncmp(snd_card_name, "qcs405", strlen("qcs405"))) {
-            my_data->current_backend_cfg[DEFAULT_CODEC_BACKEND].bitwidth_mixer_ctl =
-                strdup("WSA_CDC_DMA_RX_0 Format");
-            my_data->current_backend_cfg[DEFAULT_CODEC_BACKEND].samplerate_mixer_ctl =
-                strdup("WSA_CDC_DMA_RX_0 SampleRate");
 
+            if (!strncmp(snd_card_name, "qcs405-csra", strlen("qcs405-csra"))) {
+               my_data->current_backend_cfg[DEFAULT_CODEC_BACKEND].bitwidth_mixer_ctl =
+                   strdup("PRIM_MI2S_RX Format");
+               my_data->current_backend_cfg[DEFAULT_CODEC_BACKEND].samplerate_mixer_ctl =
+                   strdup("PRIM_MI2S_RX SampleRate");
+            } else {
+               my_data->current_backend_cfg[DEFAULT_CODEC_BACKEND].bitwidth_mixer_ctl =
+                   strdup("WSA_CDC_DMA_RX_0 Format");
+               my_data->current_backend_cfg[DEFAULT_CODEC_BACKEND].samplerate_mixer_ctl =
+                   strdup("WSA_CDC_DMA_RX_0 SampleRate");
+            }
             my_data->current_backend_cfg[DEFAULT_CODEC_TX_BACKEND].bitwidth_mixer_ctl =
                 strdup("VA_CDC_DMA_TX_0 Format");
             my_data->current_backend_cfg[DEFAULT_CODEC_TX_BACKEND].samplerate_mixer_ctl =
@@ -2672,6 +2707,9 @@
     /* free acdb_meta_key_list */
     platform_release_acdb_metainfo_key(platform);
 
+    if (my_data->acdb_deallocate)
+        my_data->acdb_deallocate();
+
     free(platform);
     /* deinit usb */
     audio_extn_usb_deinit();
@@ -4524,6 +4562,16 @@
               (mode == AUDIO_MODE_IN_COMMUNICATION)) {
         if (out_device & AUDIO_DEVICE_OUT_SPEAKER)
             in_device = AUDIO_DEVICE_IN_BACK_MIC;
+        else if (out_device & AUDIO_DEVICE_OUT_EARPIECE)
+            in_device = AUDIO_DEVICE_IN_BUILTIN_MIC;
+        else if (out_device & AUDIO_DEVICE_OUT_WIRED_HEADSET)
+            in_device = AUDIO_DEVICE_IN_WIRED_HEADSET;
+        else if (out_device & AUDIO_DEVICE_OUT_USB_DEVICE)
+            in_device = AUDIO_DEVICE_IN_USB_DEVICE;
+
+        in_device = ((out_device == AUDIO_DEVICE_NONE) ?
+                      AUDIO_DEVICE_IN_BUILTIN_MIC : in_device) & ~AUDIO_DEVICE_BIT_IN;
+
         if (adev->active_input) {
             snd_device = get_snd_device_for_voice_comm(my_data, out_device, in_device);
         }
@@ -4592,6 +4640,8 @@
             }
         } else if (in_device & AUDIO_DEVICE_IN_SPDIF) {
             snd_device = SND_DEVICE_IN_SPDIF;
+        } else if (in_device & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
+            snd_device = SND_DEVICE_IN_BT_A2DP;
         } else if (in_device & AUDIO_DEVICE_IN_AUX_DIGITAL) {
             snd_device = SND_DEVICE_IN_HDMI_MIC;
         } else if (in_device & AUDIO_DEVICE_IN_HDMI_ARC) {
@@ -5049,13 +5099,106 @@
             platform->spkr_ch_map->num_ch = num_ch;
             for (i = 0; i < num_ch; i++) {
                 opts = strtok_r(NULL, ", ", &test_r);
-                platform->spkr_ch_map->chmap[i] = strtoul(opts, NULL, 16);
+                if (opts == NULL) {
+                    ALOGE("%s: incorrect ch_map\n", __func__);
+                    free(platform->spkr_ch_map);
+                    platform->spkr_ch_map = NULL;
+                    str_parms_del(parms, AUDIO_PARAMETER_KEY_SPKR_DEVICE_CHMAP);
+                    return;
+                } else {
+                    platform->spkr_ch_map->chmap[i] = strtoul(opts, NULL, 16);
+                }
             }
         }
         str_parms_del(parms, AUDIO_PARAMETER_KEY_SPKR_DEVICE_CHMAP);
     }
 }
 
+static void platform_set_fluence_params(void *platform, struct str_parms *parms, char *value, int len)
+{
+    struct platform_data *my_data = (struct platform_data *)platform;
+    int err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FLUENCE_TYPE, value, len);
+
+    if (err >= 0) {
+        if (!strncmp("fluence", value, sizeof("fluence")))
+            my_data->fluence_type = FLUENCE_DUAL_MIC;
+        else if (!strncmp("fluencepro", value, sizeof("fluencepro")))
+                 my_data->fluence_type = FLUENCE_QUAD_MIC | FLUENCE_DUAL_MIC;
+        else if (!strncmp("none", value, sizeof("none")))
+                 my_data->fluence_type = FLUENCE_NONE;
+
+        str_parms_del(parms, AUDIO_PARAMETER_KEY_FLUENCE_TYPE);
+    }
+
+    err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FLUENCE_TRI_MIC, value, len);
+    if (err >= 0) {
+        if (!strncmp("true", value, sizeof("true")))
+            my_data->fluence_type |= FLUENCE_TRI_MIC;
+
+        str_parms_del(parms, AUDIO_PARAMETER_KEY_FLUENCE_TRI_MIC);
+    }
+
+    err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FLUENCE_VOICE_CALL, value, len);
+    if (err >= 0) {
+        if (!strncmp("true", value, sizeof("true")))
+            my_data->fluence_in_voice_call = true;
+        else
+            my_data->fluence_in_voice_call = false;
+
+        str_parms_del(parms, AUDIO_PARAMETER_KEY_FLUENCE_VOICE_CALL);
+    }
+
+    err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FLUENCE_VOICE_REC, value, len);
+    if (err >= 0) {
+        if (!strncmp("true", value, sizeof("true")))
+            my_data->fluence_in_voice_rec = true;
+        else
+            my_data->fluence_in_voice_rec = false;
+
+        str_parms_del(parms, AUDIO_PARAMETER_KEY_FLUENCE_VOICE_REC);
+    }
+
+    err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FLUENCE_AUDIO_REC, value, len);
+    if (err >= 0) {
+        if (!strncmp("true", value, sizeof("true")))
+            my_data->fluence_in_audio_rec = true;
+        else
+            my_data->fluence_in_audio_rec = false;
+
+        str_parms_del(parms, AUDIO_PARAMETER_KEY_FLUENCE_AUDIO_REC);
+    }
+
+    err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FLUENCE_SPEAKER, value, len);
+    if (err >= 0) {
+        if (!strncmp("true", value, sizeof("true")))
+            my_data->fluence_in_spkr_mode = true;
+        else
+            my_data->fluence_in_spkr_mode = false;
+
+        str_parms_del(parms, AUDIO_PARAMETER_KEY_FLUENCE_SPEAKER);
+    }
+
+    err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FLUENCE_MODE, value, len);
+    if (err >= 0) {
+        if (!strncmp("broadside", value, sizeof("broadside")))
+            my_data->fluence_mode = FLUENCE_BROADSIDE;
+        else if (!strncmp("endfire", value, sizeof("endfire")))
+            my_data->fluence_mode = FLUENCE_ENDFIRE;
+
+        str_parms_del(parms, AUDIO_PARAMETER_KEY_FLUENCE_MODE);
+    }
+
+    err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FLUENCE_HFPCALL, value, len);
+    if (err >= 0) {
+        if (!strncmp("true", value, sizeof("true")))
+            my_data->fluence_in_hfp_call = true;
+        else
+            my_data->fluence_in_hfp_call = false;
+
+        str_parms_del(parms, AUDIO_PARAMETER_KEY_FLUENCE_HFPCALL);
+    }
+}
+
 int platform_set_parameters(void *platform, struct str_parms *parms)
 {
     struct platform_data *my_data = (struct platform_data *)platform;
@@ -5189,6 +5332,8 @@
         ALOGV("%s: max_mic_count %d", __func__, my_data->max_mic_count);
     }
 
+    platform_set_fluence_params(platform, parms, value, len);
+
     /* handle audio calibration parameters */
     set_audiocal(platform, parms, value, len);
     native_audio_set_params(platform, parms, value, len);
@@ -6138,6 +6283,7 @@
     if (snd_device == SND_DEVICE_OUT_BT_A2DP ||
         snd_device == SND_DEVICE_OUT_BT_SCO ||
         snd_device == SND_DEVICE_OUT_BT_SCO_WB ||
+        snd_device == SND_DEVICE_IN_BT_A2DP ||
         snd_device == SND_DEVICE_OUT_AFE_PROXY) {
         backend_change = false;
         return backend_change;
@@ -6278,9 +6424,15 @@
             bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH;
             ALOGD("%s:becf: afe: reset to default bitwidth %d", __func__, bit_width);
         }
-        sample_rate = CODEC_BACKEND_DEFAULT_SAMPLE_RATE;
-        ALOGD("%s:becf: afe: playback on codec device not supporting native playback set "
+        /*
+         * In case of CSRA speaker out, all sample rates are supported, so
+         *  check platform here
+         */
+        if (platform_spkr_use_default_sample_rate(adev->platform)) {
+            sample_rate = CODEC_BACKEND_DEFAULT_SAMPLE_RATE;
+            ALOGD("%s:becf: afe: playback on codec device not supporting native playback set "
             "default Sample Rate(48k)", __func__);
+        }
     }
 
     if (backend_idx == USB_AUDIO_RX_BACKEND) {
@@ -6951,6 +7103,40 @@
                 channel_map[6] = PCM_CHANNEL_LS;
                 channel_map[7] = PCM_CHANNEL_RS;
                 break;
+           case 12:
+                /* AUDIO_CHANNEL_OUT_7POINT1POINT4 */
+                channel_map[0] = PCM_CHANNEL_FL;
+                channel_map[1] = PCM_CHANNEL_FR;
+                channel_map[2] = PCM_CHANNEL_FC;
+                channel_map[3] = PCM_CHANNEL_LFE;
+                channel_map[4] = PCM_CHANNEL_LB;
+                channel_map[5] = PCM_CHANNEL_RB;
+                channel_map[6] = PCM_CHANNEL_LS;
+                channel_map[7] = PCM_CHANNEL_RS;
+                channel_map[8] = PCM_CHANNEL_TFL;
+                channel_map[9] = PCM_CHANNEL_TFR;
+                channel_map[10] = PCM_CHANNEL_TSL;
+                channel_map[11] = PCM_CHANNEL_TSR;
+                break;
+          case 16:
+                /* 16 channels */
+                channel_map[0] = PCM_CHANNEL_FL;
+                channel_map[1] = PCM_CHANNEL_FR;
+                channel_map[2] = PCM_CHANNEL_FC;
+                channel_map[3] = PCM_CHANNEL_LFE;
+                channel_map[4] = PCM_CHANNEL_LB;
+                channel_map[5] = PCM_CHANNEL_RB;
+                channel_map[6] = PCM_CHANNEL_LS;
+                channel_map[7] = PCM_CHANNEL_RS;
+                channel_map[8] = PCM_CHANNEL_TFL;
+                channel_map[9] = PCM_CHANNEL_TFR;
+                channel_map[10] = PCM_CHANNEL_TSL;
+                channel_map[11] = PCM_CHANNEL_TSR;
+                channel_map[12] = PCM_CHANNEL_FLC;
+                channel_map[13] = PCM_CHANNEL_FRC;
+                channel_map[14] = PCM_CHANNEL_RLC;
+                channel_map[15] = PCM_CHANNEL_RRC;
+                break;
             default:
                 ALOGE("unsupported channels %d for setting channel map", channels);
                 return -1;
@@ -7075,12 +7261,21 @@
     struct mixer_ctl *ctl;
     char mixer_ctl_name[44] = {0}; // max length of name is 44 as defined
     int ret;
-    unsigned int i;
-    long set_values[FCC_8] = {0};
+    unsigned int i=0, n=0;
+    long set_values[AUDIO_MAX_DSP_CHANNELS];
     struct platform_data *my_data = (struct platform_data *)platform;
     struct audio_device *adev = my_data->adev;
     ALOGV("%s channel_count:%d",__func__, ch_count);
-    if (NULL == ch_map || (ch_count < 1) || (ch_count > FCC_8)) {
+
+    /*
+     * FIXME:
+     * Currently the channel mask in audio.h is limited to 30 channels,
+     * (=AUDIO_CHANNEL_COUNT_MAX), whereas the mixer controls already
+     * allow up to AUDIO_MAX_DSP_CHANNELS channels as per final requirement.
+     * Until channel mask definition is not changed from a uint32_t value
+     * to something else, a sanity check is needed here.
+     */
+    if (NULL == ch_map || (ch_count < 1) || (ch_count > AUDIO_CHANNEL_COUNT_MAX)) {
         ALOGE("%s: Invalid channel mapping or channel count value", __func__);
         return -EINVAL;
     }
@@ -7098,12 +7293,34 @@
     ALOGD("%s mixer_ctl_name:%s", __func__, mixer_ctl_name);
 
     ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
+
     if (!ctl) {
         ALOGE("%s: Could not get ctl for mixer cmd - %s",
               __func__, mixer_ctl_name);
         return -EINVAL;
     }
-    for (i = 0; i < (unsigned int)ch_count; i++) {
+
+    /* find out how many values the control can set */
+    n = mixer_ctl_get_num_values(ctl);
+
+    if (n != ch_count)
+        ALOGV("%s chcnt %d != mixerctl elem size %d",__func__, ch_count, n);
+
+    if (n < ch_count) {
+        ALOGE("%s chcnt %d > mixerctl elem size %d",__func__, ch_count, n);
+        return -EINVAL;
+    }
+
+    if (n > AUDIO_MAX_DSP_CHANNELS) {
+        ALOGE("%s mixerctl elem size %d > AUDIO_MAX_DSP_CHANNELS %d",__func__, n, AUDIO_MAX_DSP_CHANNELS);
+        return -EINVAL;
+    }
+
+    /* initialize all set_values to zero */
+    memset (set_values, 0, sizeof(set_values));
+
+    /* copy only as many values as corresponding mixer_ctrl allows */
+    for (i = 0; i < ch_count; i++) {
         set_values[i] = ch_map[i];
     }
 
@@ -7111,7 +7328,8 @@
         set_values[0], set_values[1], set_values[2], set_values[3], set_values[4],
         set_values[5], set_values[6], set_values[7], ch_count);
 
-    ret = mixer_ctl_set_array(ctl, set_values, ARRAY_SIZE(set_values));
+    ret = mixer_ctl_set_array(ctl, set_values, n);
+
     if (ret < 0) {
         ALOGE("%s: Could not set ctl, error:%d ch_count:%d",
               __func__, ret, ch_count);
@@ -7276,6 +7494,11 @@
     return 0;
 }
 
+bool platform_spkr_use_default_sample_rate(void *platform) {
+    struct platform_data *my_data = (struct platform_data *)platform;
+    return my_data->use_sprk_default_sample_rate;
+}
+
 int platform_set_edid_channels_configuration(void *platform, int channels) {
 
     struct platform_data *my_data = (struct platform_data *)platform;
diff --git a/hal/msm8974/platform.h b/hal/msm8974/platform.h
index c8ddaec..c060b18 100644
--- a/hal/msm8974/platform.h
+++ b/hal/msm8974/platform.h
@@ -181,6 +181,7 @@
     SND_DEVICE_IN_BT_SCO_MIC_NREC,
     SND_DEVICE_IN_BT_SCO_MIC_WB,
     SND_DEVICE_IN_BT_SCO_MIC_WB_NREC,
+    SND_DEVICE_IN_BT_A2DP,
     SND_DEVICE_IN_CAMCORDER_MIC,
     SND_DEVICE_IN_VOICE_DMIC,
     SND_DEVICE_IN_VOICE_SPEAKER_DMIC,
@@ -280,6 +281,8 @@
 
 #define AUDIO_PARAMETER_KEY_TRUE_32_BIT "true_32_bit"
 
+#define AUDIO_MAX_DSP_CHANNELS 32
+
 #define ALL_SESSION_VSID                0xFFFFFFFF
 #define DEFAULT_MUTE_RAMP_DURATION_MS   20
 #define DEFAULT_VOLUME_RAMP_DURATION_MS 20
diff --git a/hal/platform_api.h b/hal/platform_api.h
old mode 100755
new mode 100644
index 09c69de..1563673
--- a/hal/platform_api.h
+++ b/hal/platform_api.h
@@ -218,6 +218,7 @@
                                        snd_device_t snd_device,
                                        struct mix_matrix_params mm_params);
 int platform_set_edid_channels_configuration(void *platform, int channels);
+bool platform_spkr_use_default_sample_rate(void *platform);
 unsigned char platform_map_to_edid_format(int format);
 bool platform_is_edid_supported_format(void *platform, int format);
 bool platform_is_edid_supported_sample_rate(void *platform, int sample_rate);
diff --git a/hdmi_in_test/Makefile.am b/hdmi_in_test/Makefile.am
index 34e4ff5..eb74d21 100644
--- a/hdmi_in_test/Makefile.am
+++ b/hdmi_in_test/Makefile.am
@@ -1,9 +1,17 @@
 
 ACLOCAL_AMFLAGS = -I m4
 bin_PROGRAMS = hdmi_in_test
+bin_PROGRAMS += fmt_change_test
 pkgconfigdir = $(libdir)/pkgconfig
 
+REC_INCLUDES = -I $(top_srcdir)/qahw_api/inc
+REC_INCLUDES += -I $(top_srcdir)/qahw/inc
+
 hdmi_in_test_SOURCES = src/hdmi_in_event_test.c
 hdmi_in_test_CFLAGS  = $(CFLAGS) -Wno-sign-compare -Werror
 hdmi_in_test_LDADD = -llog -lpthread
 
+fmt_change_test_SOURCES = src/fmt_change_test.c
+fmt_change_test_CFLAGS  = $(CFLAGS) -Wno-sign-compare -Werror $(REC_INCLUDES)
+fmt_change_test_LDADD = -llog -lpthread ../qahw_api/libqahw.la
+
diff --git a/hdmi_in_test/src/fmt_change_test.c b/hdmi_in_test/src/fmt_change_test.c
new file mode 100644
index 0000000..6651c6d
--- /dev/null
+++ b/hdmi_in_test/src/fmt_change_test.c
@@ -0,0 +1,811 @@
+/*
+ * Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
+ * Not a Contribution.
+ *
+ * Copyright (C) 2015 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.
+ */
+
+/* Test app to capture event updates from kernel */
+/*#define LOG_NDEBUG 0*/
+#include <getopt.h>
+#include <fcntl.h>
+#include <linux/netlink.h>
+#include <pthread.h>
+#include <poll.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <sys/prctl.h>
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <utils/Log.h>
+#include <signal.h>
+#include <errno.h>
+#include "qahw_api.h"
+#include "qahw_defs.h"
+
+/* add local define to prevent compilation errors on other platforms */
+#ifndef AUDIO_DEVICE_IN_HDMI_ARC
+#define AUDIO_DEVICE_IN_HDMI_ARC (AUDIO_DEVICE_BIT_IN | 0x8000000)
+#endif
+
+static int sock_event_fd = -1;
+
+void *context = NULL;
+FILE * log_file = NULL;
+volatile bool stop_test = false;
+volatile bool stop_record = false;
+volatile bool record_active = false;
+
+#define HDMI_SYS_PATH "/sys/devices/platform/soc/78b7000.i2c/i2c-3/3-0064/"
+const char hdmi_in_audio_sys_path[] = HDMI_SYS_PATH "link_on0";
+const char hdmi_in_power_on_sys_path[] = HDMI_SYS_PATH "power_on";
+const char hdmi_in_audio_path_sys_path[] = HDMI_SYS_PATH "audio_path";
+const char hdmi_in_arc_enable_sys_path[] = HDMI_SYS_PATH "arc_enable";
+
+const char hdmi_in_audio_state_sys_path[] = HDMI_SYS_PATH "audio_state";
+const char hdmi_in_audio_format_sys_path[] = HDMI_SYS_PATH "audio_format";
+const char hdmi_in_audio_sample_rate_sys_path[] = HDMI_SYS_PATH "audio_rate";
+const char hdmi_in_audio_layout_sys_path[] = HDMI_SYS_PATH "audio_layout";
+
+#define SPDIF_SYS_PATH "/sys/devices/platform/soc/soc:qcom,msm-dai-q6-spdif-pri-tx/"
+const char spdif_in_audio_state_sys_path[] = SPDIF_SYS_PATH "audio_state";
+const char spdif_in_audio_format_sys_path[] = SPDIF_SYS_PATH "audio_format";
+const char spdif_in_audio_sample_rate_sys_path[] = SPDIF_SYS_PATH "audio_rate";
+
+#define SPDIF_ARC_SYS_PATH "/sys/devices/platform/soc/soc:qcom,msm-dai-q6-spdif-sec-tx/"
+const char spdif_arc_in_audio_state_sys_path[] = SPDIF_ARC_SYS_PATH "audio_state";
+const char spdif_arc_in_audio_format_sys_path[] = SPDIF_ARC_SYS_PATH "audio_format";
+const char spdif_arc_in_audio_sample_rate_sys_path[] = SPDIF_ARC_SYS_PATH "audio_rate";
+
+#define ID_RIFF 0x46464952
+#define ID_WAVE 0x45564157
+#define ID_FMT  0x20746d66
+#define ID_DATA 0x61746164
+
+#define FORMAT_PCM 1
+
+struct wav_header {
+    uint32_t riff_id;
+    uint32_t riff_sz;
+    uint32_t riff_fmt;
+    uint32_t fmt_id;
+    uint32_t fmt_sz;
+    uint16_t audio_format;
+    uint16_t num_channels;
+    uint32_t sample_rate;
+    uint32_t byte_rate;       /* sample_rate * num_channels * bps / 8 */
+    uint16_t block_align;     /* num_channels * bps / 8 */
+    uint16_t bits_per_sample;
+    uint32_t data_id;
+    uint32_t data_sz;
+};
+
+struct test_data {
+    qahw_module_handle_t *qahw_mod_handle;
+    audio_io_handle_t handle;
+    audio_devices_t input_device;
+    double record_length;
+    int rec_cnt;
+
+    char *audio_fmt_chg_text;
+    int audio_fmt_chg_len;
+    pthread_t record_th;
+    pthread_t poll_event_th;
+    pthread_attr_t poll_event_attr;
+
+    int bit_width;
+    audio_input_flags_t flags;
+    audio_config_t config;
+    audio_source_t source;
+
+    int spdif_audio_state;
+    int spdif_audio_mode;
+    int spdif_sample_rate;
+    int spdif_num_channels;
+
+    int hdmi_power_on;
+    int hdmi_audio_path;
+    int hdmi_arc_enable;
+
+    int hdmi_audio_state;
+    int hdmi_audio_mode;
+    int hdmi_audio_layout;
+    int hdmi_sample_rate;
+    int hdmi_num_channels;
+
+    int spdif_arc_audio_state;
+    int spdif_arc_audio_mode;
+    int spdif_arc_sample_rate;
+    int spdif_arc_num_channels;
+
+    audio_devices_t new_input_device;
+
+    audio_devices_t act_input_device; /* HDMI might use I2S and SPDIF */
+
+    int act_audio_state;    /* audio active */
+    int act_audio_mode;     /* 0=LPCM, 1=Compr */
+    int act_sample_rate;    /* transmission sample rate */
+    int act_num_channels;   /* transmission channels */
+};
+
+struct test_data tdata;
+
+void stop_signal_handler(int signal)
+{
+   stop_test = true;
+}
+
+void *start_input(void *thread_param) {
+    int rc = 0, ret = 0, count = 0;
+    ssize_t bytes_read = -1;
+    char file_name[256] = "/data/rec";
+    int data_sz = 0, name_len = strlen(file_name);
+    qahw_in_buffer_t in_buf;
+
+    qahw_module_handle_t *qahw_mod_handle = tdata.qahw_mod_handle;
+
+    /* convert/check params before use */
+    tdata.config.sample_rate = tdata.act_sample_rate;
+
+    if (tdata.act_audio_mode) {
+        tdata.config.format = AUDIO_FORMAT_IEC61937;
+        tdata.flags = QAHW_INPUT_FLAG_COMPRESS | QAHW_INPUT_FLAG_PASSTHROUGH;
+    } else {
+        if (tdata.bit_width == 32)
+            tdata.config.format = AUDIO_FORMAT_PCM_8_24_BIT;
+        else if (tdata.bit_width == 24)
+            tdata.config.format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
+        else
+            tdata.config.format = AUDIO_FORMAT_PCM_16_BIT;
+        tdata.flags = 0;
+    }
+
+    switch (tdata.act_num_channels) {
+    case 2:
+        tdata.config.channel_mask = AUDIO_CHANNEL_IN_STEREO;
+        break;
+    case 8:
+        tdata.config.channel_mask = AUDIO_CHANNEL_INDEX_MASK_8;
+        break;
+    default:
+        fprintf(log_file,
+            "ERROR :::: channel count %d not supported\n",
+            tdata.act_num_channels);
+        pthread_exit(0);
+    }
+    tdata.config.frame_count = 0;
+
+    /* Open audio input stream */
+    qahw_stream_handle_t* in_handle = NULL;
+
+    rc = qahw_open_input_stream(qahw_mod_handle, tdata.handle,
+        tdata.act_input_device, &tdata.config, &in_handle, tdata.flags,
+        "input_stream", tdata.source);
+    if (rc) {
+        fprintf(log_file,
+            "ERROR :::: Could not open input stream, handle(%d)\n",
+            tdata.handle);
+        pthread_exit(0);
+    }
+
+    /* Get buffer size to get upper bound on data to read from the HAL */
+    size_t buffer_size = qahw_in_get_buffer_size(in_handle);
+    char *buffer = (char *) calloc(1, buffer_size);
+    size_t written_size;
+    if (buffer == NULL) {
+        fprintf(log_file, "calloc failed!!, handle(%d)\n", tdata.handle);
+        pthread_exit(0);
+    }
+
+    fprintf(log_file, " input opened, buffer  %p, size %zu, handle(%d)\n", buffer,
+        buffer_size, tdata.handle);
+
+    /* set profile for the recording session */
+    qahw_in_set_parameters(in_handle, "audio_stream_profile=record_unprocessed");
+
+    if (audio_is_linear_pcm(tdata.config.format))
+        snprintf(file_name + name_len, sizeof(file_name) - name_len, "%d.wav",
+            tdata.rec_cnt);
+    else
+        snprintf(file_name + name_len, sizeof(file_name) - name_len, "%d.raw",
+            tdata.rec_cnt);
+
+    tdata.rec_cnt++;
+
+    FILE *fd = fopen(file_name, "w");
+    if (fd == NULL) {
+        fprintf(log_file, "File open failed\n");
+        free(buffer);
+        pthread_exit(0);
+    }
+
+    int bps = 16;
+
+    switch (tdata.config.format) {
+    case AUDIO_FORMAT_PCM_24_BIT_PACKED:
+        bps = 24;
+        break;
+    case AUDIO_FORMAT_PCM_8_24_BIT:
+    case AUDIO_FORMAT_PCM_32_BIT:
+        bps = 32;
+        break;
+    case AUDIO_FORMAT_PCM_16_BIT:
+    default:
+        bps = 16;
+    }
+
+    struct wav_header hdr;
+    hdr.riff_id = ID_RIFF;
+    hdr.riff_sz = 0;
+    hdr.riff_fmt = ID_WAVE;
+    hdr.fmt_id = ID_FMT;
+    hdr.fmt_sz = 16;
+    hdr.audio_format = FORMAT_PCM;
+    hdr.num_channels = tdata.act_num_channels;
+    hdr.sample_rate = tdata.config.sample_rate;
+    hdr.byte_rate = hdr.sample_rate * hdr.num_channels * (bps / 8);
+    hdr.block_align = hdr.num_channels * (bps / 8);
+    hdr.bits_per_sample = bps;
+    hdr.data_id = ID_DATA;
+    hdr.data_sz = 0;
+    if (audio_is_linear_pcm(tdata.config.format))
+        fwrite(&hdr, 1, sizeof(hdr), fd);
+
+    memset(&in_buf, 0, sizeof(qahw_in_buffer_t));
+    while (true && !stop_record) {
+        in_buf.buffer = buffer;
+        in_buf.bytes = buffer_size;
+        bytes_read = qahw_in_read(in_handle, &in_buf);
+
+        written_size = fwrite(in_buf.buffer, 1, bytes_read, fd);
+        if (written_size < bytes_read) {
+            printf("Error in fwrite(%d)=%s\n", ferror(fd),
+                strerror(ferror(fd)));
+            break;
+        }
+        data_sz += bytes_read;
+    }
+
+    if (audio_is_linear_pcm(tdata.config.format)) {
+        /* update lengths in header */
+        hdr.data_sz = data_sz;
+        hdr.riff_sz = data_sz + 44 - 8;
+        fseek(fd, 0, SEEK_SET);
+        fwrite(&hdr, 1, sizeof(hdr), fd);
+    }
+    free(buffer);
+    fclose(fd);
+    fd = NULL;
+
+    fprintf(log_file, " closing input, handle(%d), written %d bytes", tdata.handle, data_sz);
+
+    /* Close input stream and device. */
+    rc = qahw_in_standby(in_handle);
+    if (rc) {
+        fprintf(log_file, "in standby failed %d, handle(%d)\n", rc,
+            tdata.handle);
+    }
+
+    rc = qahw_close_input_stream(in_handle);
+    if (rc) {
+        fprintf(log_file, "could not close input stream %d, handle(%d)\n", rc,
+            tdata.handle);
+    }
+
+    fprintf(log_file,
+        "\n\n The audio recording has been saved to %s.\n"
+        "The audio data has the  following characteristics:\n Sample rate: %i\n Format: %d\n "
+        "Num channels: %i, handle(%d)\n\n", file_name,
+        tdata.config.sample_rate, tdata.config.format, tdata.act_num_channels,
+        tdata.handle);
+
+    return NULL;
+}
+
+void start_rec_thread(void)
+{
+    int ret = 0;
+
+    stop_record = false;
+    record_active = true;
+
+    fprintf(log_file, "\n Create record thread \n");
+    ret = pthread_create(&tdata.record_th, NULL, start_input, (void *)&tdata);
+    if (ret) {
+        fprintf(log_file, " Failed to create record thread\n");
+        exit(1);
+   }
+}
+
+void stop_rec_thread(void)
+{
+    if (record_active) {
+        record_active = false;
+        stop_record = true;
+        fprintf(log_file, "\n Stop record thread \n");
+        pthread_join(tdata.record_th, NULL);
+    }
+}
+
+
+void read_data_from_fd(const char* path, int *value)
+{
+    int fd = -1;
+    char buf[16];
+    int ret;
+
+    fd = open(path, O_RDONLY, 0);
+    if (fd < 0) {
+        ALOGE("Unable open fd for file %s", path);
+        return;
+    }
+
+    ret = read(fd, buf, 15);
+    if (ret < 0) {
+        ALOGE("File %s Data is empty", path);
+        close(fd);
+        return;
+    }
+
+    buf[ret] = '\0';
+    *value = atoi(buf);
+    close(fd);
+}
+
+void get_input_status()
+{
+    switch (tdata.input_device) {
+    case AUDIO_DEVICE_IN_SPDIF:
+        read_data_from_fd(spdif_in_audio_state_sys_path, &tdata.spdif_audio_state);
+        read_data_from_fd(spdif_in_audio_format_sys_path, &tdata.spdif_audio_mode);
+        read_data_from_fd(spdif_in_audio_sample_rate_sys_path, &tdata.spdif_sample_rate);
+        tdata.spdif_num_channels = 2;
+        tdata.new_input_device = AUDIO_DEVICE_IN_SPDIF;
+
+        fprintf(log_file, "spdif audio_state: %d, audio_format: %d, sample_rate: %d, num_channels: %d\n",
+            tdata.spdif_audio_state, tdata.spdif_audio_mode, tdata.spdif_sample_rate, tdata.spdif_num_channels);
+        break;
+    case AUDIO_DEVICE_IN_HDMI:
+        read_data_from_fd(hdmi_in_power_on_sys_path, &tdata.hdmi_power_on);
+        read_data_from_fd(hdmi_in_audio_path_sys_path, &tdata.hdmi_audio_path);
+        read_data_from_fd(hdmi_in_arc_enable_sys_path, &tdata.hdmi_arc_enable);
+
+        read_data_from_fd(hdmi_in_audio_state_sys_path, &tdata.hdmi_audio_state);
+        read_data_from_fd(hdmi_in_audio_format_sys_path, &tdata.hdmi_audio_mode);
+        read_data_from_fd(hdmi_in_audio_sample_rate_sys_path, &tdata.hdmi_sample_rate);
+        read_data_from_fd(hdmi_in_audio_layout_sys_path, &tdata.hdmi_audio_layout);
+        if (tdata.hdmi_audio_layout)
+            tdata.hdmi_num_channels = 8;
+        else
+            tdata.hdmi_num_channels = 2;
+        /* todo: read ch_count, ch_alloc */
+
+        read_data_from_fd(spdif_arc_in_audio_state_sys_path, &tdata.spdif_arc_audio_state);
+        read_data_from_fd(spdif_arc_in_audio_format_sys_path, &tdata.spdif_arc_audio_mode);
+        read_data_from_fd(spdif_arc_in_audio_sample_rate_sys_path, &tdata.spdif_arc_sample_rate);
+        tdata.spdif_arc_num_channels = 2;
+
+        if (tdata.hdmi_arc_enable ||
+            (tdata.hdmi_audio_state && (tdata.hdmi_audio_layout == 0) && tdata.hdmi_audio_mode)) {
+            tdata.new_input_device = AUDIO_DEVICE_IN_HDMI_ARC;
+            fprintf(log_file, "hdmi audio interface SPDIF_ARC\n");
+        } else {
+            tdata.new_input_device = AUDIO_DEVICE_IN_HDMI;
+            fprintf(log_file, "hdmi audio interface MI2S\n");
+        }
+
+        fprintf(log_file, "hdmi audio_state: %d, audio_format: %d, sample_rate: %d, num_channels: %d\n",
+            tdata.hdmi_audio_state, tdata.hdmi_audio_mode, tdata.hdmi_sample_rate, tdata.hdmi_num_channels);
+        fprintf(log_file, "arc  audio_state: %d, audio_format: %d, sample_rate: %d, num_channels: %d\n",
+            tdata.spdif_arc_audio_state, tdata.spdif_arc_audio_mode, tdata.spdif_arc_sample_rate, tdata.spdif_arc_num_channels);
+        break;
+    }
+}
+
+void input_restart_check(void)
+{
+    get_input_status();
+
+    switch (tdata.input_device) {
+    case AUDIO_DEVICE_IN_SPDIF:
+        if ((tdata.act_input_device != tdata.new_input_device) ||
+            (tdata.spdif_audio_state == 2)) {
+            fprintf(log_file, "old       audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                tdata.act_audio_state, tdata.act_audio_mode,
+                tdata.act_sample_rate, tdata.act_num_channels);
+            fprintf(log_file, "new spdif audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                tdata.spdif_audio_state, tdata.spdif_audio_mode,
+                tdata.spdif_sample_rate, tdata.spdif_num_channels);
+
+            stop_rec_thread();
+
+            tdata.act_input_device = AUDIO_DEVICE_IN_SPDIF;
+            tdata.act_audio_state = 1;
+            tdata.act_audio_mode = tdata.spdif_audio_mode;
+            tdata.act_sample_rate = tdata.spdif_sample_rate;
+            tdata.act_num_channels = tdata.spdif_num_channels;
+
+            start_rec_thread();
+        }
+        break;
+    case AUDIO_DEVICE_IN_HDMI:
+        if (tdata.act_input_device != tdata.new_input_device) {
+            stop_rec_thread();
+
+            if (tdata.new_input_device == AUDIO_DEVICE_IN_HDMI) {
+                fprintf(log_file, "old      audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                    tdata.act_audio_state, tdata.act_audio_mode,
+                    tdata.act_sample_rate, tdata.act_num_channels);
+                fprintf(log_file, "new hdmi audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                    tdata.hdmi_audio_state, tdata.hdmi_audio_mode,
+                    tdata.hdmi_sample_rate, tdata.hdmi_num_channels);
+
+                tdata.act_input_device = AUDIO_DEVICE_IN_HDMI;
+                tdata.act_audio_state = tdata.hdmi_audio_state;
+                tdata.act_audio_mode = tdata.hdmi_audio_mode;
+                tdata.act_sample_rate = tdata.hdmi_sample_rate;
+                tdata.act_num_channels = tdata.hdmi_num_channels;
+
+                if (tdata.hdmi_audio_state)
+                    start_rec_thread();
+            } else {
+                tdata.act_input_device = AUDIO_DEVICE_IN_HDMI_ARC;
+                if (tdata.hdmi_arc_enable) {
+                    fprintf(log_file, "old     audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                        tdata.act_audio_state, tdata.act_audio_mode,
+                        tdata.act_sample_rate, tdata.act_num_channels);
+                    fprintf(log_file, "new arc audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                        tdata.spdif_arc_audio_state, tdata.spdif_arc_audio_mode,
+                        tdata.spdif_arc_sample_rate, tdata.spdif_arc_num_channels);
+
+                    tdata.act_audio_state = 1;
+                    tdata.act_audio_mode = tdata.spdif_arc_audio_mode;
+                    tdata.act_sample_rate = tdata.spdif_arc_sample_rate;
+                    tdata.act_num_channels = tdata.spdif_arc_num_channels;
+                } else {
+                    fprintf(log_file, "old      audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                        tdata.act_audio_state, tdata.act_audio_mode,
+                        tdata.act_sample_rate, tdata.act_num_channels);
+                    fprintf(log_file, "new arc (from hdmi) audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                        tdata.hdmi_audio_state, tdata.hdmi_audio_mode,
+                        tdata.hdmi_sample_rate, tdata.hdmi_num_channels);
+
+                    tdata.act_audio_state = 1;
+                    tdata.act_audio_mode = tdata.hdmi_audio_mode;
+                    tdata.act_sample_rate = tdata.hdmi_sample_rate;
+                    tdata.act_num_channels = tdata.hdmi_num_channels;
+                }
+                start_rec_thread();
+            }
+        } else { /* check for change on same audio device */
+            if (tdata.new_input_device == AUDIO_DEVICE_IN_HDMI) {
+                if ((tdata.act_audio_state != tdata.hdmi_audio_state) ||
+                    (tdata.act_audio_mode != tdata.hdmi_audio_mode) ||
+                    (tdata.act_sample_rate != tdata.hdmi_sample_rate) ||
+                    (tdata.act_num_channels != tdata.hdmi_num_channels)) {
+
+                    fprintf(log_file, "old      audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                        tdata.act_audio_state, tdata.act_audio_mode,
+                        tdata.act_sample_rate, tdata.act_num_channels);
+                    fprintf(log_file, "new hdmi audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                        tdata.hdmi_audio_state, tdata.hdmi_audio_mode,
+                        tdata.hdmi_sample_rate, tdata.hdmi_num_channels);
+
+                    stop_rec_thread();
+
+                    tdata.act_audio_state = tdata.hdmi_audio_state;
+                    tdata.act_audio_mode = tdata.hdmi_audio_mode;
+                    tdata.act_sample_rate = tdata.hdmi_sample_rate;
+                    tdata.act_num_channels = tdata.hdmi_num_channels;
+
+                    if (tdata.hdmi_audio_state)
+                        start_rec_thread();
+                    }
+            } else {
+                if (tdata.spdif_arc_audio_state == 2) {
+                    fprintf(log_file, "old     audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                        tdata.act_audio_state, tdata.act_audio_mode,
+                        tdata.act_sample_rate, tdata.act_num_channels);
+                    fprintf(log_file, "new arc audio_state: %d, audio_format: %d, rate: %d, channels: %d\n",
+                        tdata.spdif_arc_audio_state, tdata.spdif_arc_audio_mode,
+                        tdata.spdif_arc_sample_rate, tdata.spdif_arc_num_channels);
+
+                    stop_rec_thread();
+
+                    tdata.act_audio_state = 1;
+                    tdata.act_audio_mode = tdata.spdif_arc_audio_mode;
+                    tdata.act_sample_rate = tdata.spdif_arc_sample_rate;
+                    tdata.act_num_channels = tdata.spdif_arc_num_channels;
+
+                    start_rec_thread();
+                }
+            }
+        }
+        break;
+    }
+}
+
+int poll_event_init()
+{
+    struct sockaddr_nl sock_addr;
+    int sz = (64*1024);
+    int soc;
+
+    memset(&sock_addr, 0, sizeof(sock_addr));
+    sock_addr.nl_family = AF_NETLINK;
+    sock_addr.nl_pid = getpid();
+    sock_addr.nl_groups = 0xffffffff;
+
+    soc = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
+    if (soc < 0) {
+        return 0;
+    }
+
+    setsockopt(soc, SOL_SOCKET, SO_RCVBUFFORCE, &sz, sizeof(sz));
+
+    if (bind(soc, (struct sockaddr*) &sock_addr, sizeof(sock_addr)) < 0) {
+        close(soc);
+        return 0;
+    }
+
+    sock_event_fd = soc;
+
+    return (soc > 0);
+}
+
+void* listen_uevent()
+{
+    char buffer[64*1024];
+    struct pollfd fds;
+    int i, count;
+    int j;
+    char *dev_path = NULL;
+    char *switch_state = NULL;
+    char *switch_name = NULL;
+    int audio_changed;
+
+    input_restart_check();
+
+    while(!stop_test) {
+
+        fds.fd = sock_event_fd;
+        fds.events = POLLIN;
+        fds.revents = 0;
+        i = poll(&fds, 1, 5); /* wait 5 msec */
+
+        if (i > 0 && (fds.revents & POLLIN)) {
+            count = recv(sock_event_fd, buffer, (64*1024), 0 );
+            if (count > 0) {
+                buffer[count] = '\0';
+                audio_changed = 0;
+                j = 0;
+                while(j < count) {
+                    if (strncmp(&buffer[j], "DEVPATH=", 8) == 0) {
+                        dev_path = &buffer[j+8];
+                        j += 8;
+                        continue;
+                    } else if (tdata.input_device == AUDIO_DEVICE_IN_SPDIF) {
+                        if (strncmp(&buffer[j], "PRI_SPDIF_TX=MEDIA_CONFIG_CHANGE", strlen("PRI_SPDIF_TX=MEDIA_CONFIG_CHANGE")) == 0) {
+                            audio_changed = 1;
+                            ALOGI("AUDIO CHANGE EVENT: %s\n", &buffer[j]);
+                            j += strlen("PRI_SPDIF_TX=MEDIA_CONFIG_CHANGE");
+                            continue;
+                        }
+                    } else if (tdata.input_device == AUDIO_DEVICE_IN_HDMI) {
+                        if (strncmp(&buffer[j], "EP92EVT_AUDIO=MEDIA_CONFIG_CHANGE", strlen("EP92EVT_AUDIO=MEDIA_CONFIG_CHANGE")) == 0) {
+                            audio_changed = 1;
+                            ALOGI("AUDIO CHANGE EVENT: %s\n", &buffer[j]);
+                            j += strlen("EP92EVT_AUDIO=MEDIA_CONFIG_CHANGE");
+                            continue;
+                        } else if (strncmp(&buffer[j], "SEC_SPDIF_TX=MEDIA_CONFIG_CHANGE", strlen("SEC_SPDIF_TX=MEDIA_CONFIG_CHANGE")) == 0) {
+                            audio_changed = 1;
+                            ALOGI("AUDIO CHANGE EVENT: %s\n", &buffer[j]);
+                            j += strlen("SEC_SPDIF_TX=MEDIA_CONFIG_CHANGE");
+                            continue;
+                        } else if (strncmp(&buffer[j], "EP92EVT_", 8) == 0) {
+                            ALOGI("EVENT: %s\n", &buffer[j]);
+                            j += 8;
+                            continue;
+                        }
+                    }
+                    j++;
+                }
+
+                if (audio_changed)
+                    input_restart_check();
+            }
+        } else {
+            ALOGV("NO Data\n");
+        }
+    }
+
+    stop_rec_thread();
+}
+
+void fill_default_params(struct test_data *tdata) {
+    memset(tdata, 0, sizeof(struct test_data));
+
+    tdata->input_device = AUDIO_DEVICE_IN_SPDIF;
+    tdata->bit_width = 24;
+    tdata->source = AUDIO_SOURCE_UNPROCESSED;
+    tdata->record_length = 8 /*sec*/;
+
+    tdata->handle = 0x99A;
+}
+
+void usage() {
+    printf(" \n Command \n");
+    printf(" \n fmt_change_test <options>\n");
+    printf(" \n Options\n");
+    printf(" -d  --device <int>                 - see system/media/audio/include/system/audio.h for device values\n");
+    printf("                                      spdif_in 2147549184, hdmi_in 2147483680\n");
+    printf("                                      Optional Argument and Default value is spdif_in\n\n");
+    printf(" -b  --bits  <int>                  - Bitwidth in PCM mode (16, 24 or 32), Default is 24\n\n");
+    printf(" -F  --flags  <int>                 - Integer value of flags to be used for opening input stream\n\n");
+    printf(" -t  --recording-time <in seconds>  - Time duration for the recording\n\n");
+    printf(" -l  --log-file <FILEPATH>          - File path for debug msg, to print\n");
+    printf("                                      on console use stdout or 1 \n\n");
+    printf(" -h  --help                         - Show this help\n\n");
+    printf(" \n Examples \n");
+    printf(" hdmi_in_event_test                          -> start a recording stream with default configurations\n\n");
+    printf(" hdmi_in_event_test -d 2147483680 -t 20      -> start a recording session, with device hdmi_in,\n");
+    printf("                                                record data for 20 secs.\n\n");
+}
+
+static void qti_audio_server_death_notify_cb(void *ctxt) {
+    fprintf(log_file, "qas died\n");
+    fprintf(stderr, "qas died\n");
+    stop_test = true;
+    stop_record = true;
+}
+
+int main(int argc, char* argv[])
+{
+    qahw_module_handle_t *qahw_mod_handle;
+    const  char *mod_name = "audio.primary";
+
+    char log_filename[256] = "stdout";
+    int i;
+    int ret = -1;
+
+    log_file = stdout;
+    fill_default_params(&tdata);
+    struct option long_options[] = {
+        /* These options set a flag. */
+        {"device",          required_argument,    0, 'd'},
+        {"bits",            required_argument,    0, 'b'},
+        {"flags",           required_argument,    0, 'F'},
+        {"recording-time",  required_argument,    0, 't'},
+        {"log-file",        required_argument,    0, 'l'},
+        {"help",            no_argument,          0, 'h'},
+        {0, 0, 0, 0}
+    };
+
+    int opt = 0;
+    int option_index = 0;
+    while ((opt = getopt_long(argc,
+                              argv,
+                              "-d:b:F:t:l:h",
+                              long_options,
+                              &option_index)) != -1) {
+            switch (opt) {
+            case 'd':
+                tdata.input_device = atoll(optarg);
+                break;
+            case 'b':
+                tdata.bit_width = atoll(optarg);
+                break;
+            case 'F':
+                tdata.flags = atoll(optarg);
+                break;
+            case 't':
+                tdata.record_length = atoi(optarg);
+                break;
+            case 'l':
+                snprintf(log_filename, sizeof(log_filename), "%s", optarg);
+                break;
+            case 'h':
+                usage();
+                return 0;
+                break;
+         }
+    }
+    fprintf(log_file, "registering qas callback");
+    qahw_register_qas_death_notify_cb((audio_error_callback)qti_audio_server_death_notify_cb, context);
+
+    switch (tdata.input_device) {
+    case AUDIO_DEVICE_IN_SPDIF:
+        break;
+    case AUDIO_DEVICE_IN_HDMI:
+        break;
+    default:
+        fprintf(log_file, "device %d not supported\n", tdata.input_device);
+        return -1;
+    }
+
+    switch (tdata.bit_width) {
+    case 16:
+    case 24:
+    case 32:
+        break;
+    default:
+        fprintf(log_file, "bitwidth %d not supported\n", tdata.bit_width);
+        return -1;
+    }
+
+    qahw_mod_handle = qahw_load_module(mod_name);
+    if(qahw_mod_handle == NULL) {
+        fprintf(log_file, " qahw_load_module failed");
+        return -1;
+    }
+    fprintf(log_file, " Starting audio recording test. \n");
+    if (strcasecmp(log_filename, "stdout") && strcasecmp(log_filename, "1")) {
+        if ((log_file = fopen(log_filename,"wb"))== NULL) {
+            fprintf(stderr, "Cannot open log file %s\n", log_filename);
+            /* continue to log to std out */
+            log_file = stdout;
+        }
+    }
+
+    tdata.qahw_mod_handle = qahw_mod_handle;
+
+    /* Register the SIGINT to close the App properly */
+    if (signal(SIGINT, stop_signal_handler) == SIG_ERR)
+        fprintf(log_file, "Failed to register SIGINT:%d\n", errno);
+
+    /* Register the SIGTERM to close the App properly */
+    if (signal(SIGTERM, stop_signal_handler) == SIG_ERR)
+        fprintf(log_file, "Failed to register SIGTERM:%d\n", errno);
+
+    time_t start_time = time(0);
+    double time_elapsed = 0;
+
+    pthread_attr_init(&tdata.poll_event_attr);
+    pthread_attr_setdetachstate(&tdata.poll_event_attr, PTHREAD_CREATE_JOINABLE);
+    poll_event_init();
+    pthread_create(&tdata.poll_event_th, &tdata.poll_event_attr,
+                       (void *) listen_uevent, NULL);
+
+    while(true && !stop_test) {
+        time_elapsed = difftime(time(0), start_time);
+        if (tdata.record_length && (time_elapsed > tdata.record_length)) {
+            fprintf(log_file, "\n Test completed.\n");
+            stop_test = true;
+            break;
+        }
+    }
+
+    fprintf(log_file, "\n Stop test \n");
+
+    pthread_join(tdata.poll_event_th, NULL);
+
+    fprintf(log_file, "\n Unload HAL\n");
+
+    ret = qahw_unload_module(qahw_mod_handle);
+    if (ret) {
+        fprintf(log_file, "could not unload hal %d\n", ret);
+    }
+
+    fprintf(log_file, "Done with hal record test\n");
+    if (log_file != stdout) {
+        if (log_file) {
+          fclose(log_file);
+          log_file = NULL;
+        }
+    }
+
+    return 0;
+}
diff --git a/post_proc/Android.mk b/post_proc/Android.mk
index 5da769c..4441ab0 100644
--- a/post_proc/Android.mk
+++ b/post_proc/Android.mk
@@ -39,6 +39,10 @@
     LOCAL_SRC_FILES += asphere.c
 endif
 
+ifeq ($(strip $(AUDIO_FEATURE_ENABLED_INSTANCE_ID)), true)
+    LOCAL_CFLAGS += -DINSTANCE_ID_ENABLED
+endif
+
 LOCAL_CFLAGS+= -O2 -fvisibility=hidden
 
 ifneq ($(strip $(AUDIO_FEATURE_DISABLED_DTS_EAGLE)),true)
@@ -110,10 +114,6 @@
 LOCAL_CFLAGS += -DHW_ACC_HPX
 endif
 
-ifeq ($(strip $(AUDIO_FEATURE_ENABLED_INSTANCE_ID)), true)
-    LOCAL_CFLAGS += -DINSTANCE_ID_ENABLED
-endif
-
 LOCAL_MODULE:= libhwacceffectswrapper
 LOCAL_VENDOR_MODULE := true
 
diff --git a/post_proc/bass_boost.c b/post_proc/bass_boost.c
index 68cd46f..02c68d4 100644
--- a/post_proc/bass_boost.c
+++ b/post_proc/bass_boost.c
@@ -32,6 +32,8 @@
 #include "effect_api.h"
 #include "bass_boost.h"
 
+#define BASSBOOST_MAX_LATENCY 30
+
 /* Offload bassboost UUID: 2c4a8c24-1581-487f-94f6-0002a5d5c51b */
 const effect_descriptor_t bassboost_descriptor = {
         {0x0634f220, 0xddd4, 0x11db, 0xa0fc, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b }},
@@ -101,6 +103,11 @@
            p->status = -EINVAL;
         p->vsize = sizeof(int16_t);
         break;
+    case BASSBOOST_PARAM_LATENCY:
+        if (p->vsize < sizeof(uint32_t))
+           p->status = -EINVAL;
+        p->vsize = sizeof(uint32_t);
+        break;
     default:
         p->status = -EINVAL;
     }
@@ -127,6 +134,10 @@
             *(int16_t *)value = 0;
         break;
 
+    case BASSBOOST_PARAM_LATENCY:
+        *(uint32_t *)value = BASSBOOST_MAX_LATENCY;
+        break;
+
     default:
         p->status = -EINVAL;
         break;
diff --git a/post_proc/bass_boost.h b/post_proc/bass_boost.h
index 8bf51d3..ff674d4 100644
--- a/post_proc/bass_boost.h
+++ b/post_proc/bass_boost.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013-2015, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2013-2015, 2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2013 The Android Open Source Project
@@ -20,6 +20,8 @@
 #ifndef OFFLOAD_EFFECT_BASS_BOOST_H_
 #define OFFLOAD_EFFECT_BASS_BOOST_H_
 
+#define BASSBOOST_PARAM_LATENCY 0x80000000
+
 #include "bundle.h"
 
 enum {
diff --git a/post_proc/equalizer.c b/post_proc/equalizer.c
index c1c1303..479f848 100644
--- a/post_proc/equalizer.c
+++ b/post_proc/equalizer.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013-2014, 2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2013-2014, 2017-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2013 The Android Open Source Project
@@ -29,6 +29,8 @@
 #include "effect_api.h"
 #include "equalizer.h"
 
+#define EQUALIZER_MAX_LATENCY 0
+
 /* Offload equalizer UUID: a0dac280-401c-11e3-9379-0002a5d5c51b */
 const effect_descriptor_t equalizer_descriptor = {
         {0x0bed4300, 0xddd6, 0x11db, 0x8f34, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}, // type
@@ -253,6 +255,12 @@
         p->vsize = (2 + NUM_EQ_BANDS) * sizeof(uint16_t);
         break;
 
+    case EQ_PARAM_LATENCY:
+        if (p->vsize < sizeof(uint32_t))
+           p->status = -EINVAL;
+        p->vsize = sizeof(uint32_t);
+        break;
+
     default:
         p->status = -EINVAL;
     }
@@ -352,6 +360,10 @@
         }
     } break;
 
+    case EQ_PARAM_LATENCY:
+        *(uint32_t *)value = EQUALIZER_MAX_LATENCY;
+        break;
+
     default:
         p->status = -EINVAL;
         break;
diff --git a/post_proc/equalizer.h b/post_proc/equalizer.h
index 7fec058..2cd06c2 100644
--- a/post_proc/equalizer.h
+++ b/post_proc/equalizer.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2013-2014, 2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2013 The Android Open Source Project
@@ -26,6 +26,8 @@
 #define INVALID_PRESET		 -2
 #define PRESET_CUSTOM		 -1
 
+#define EQ_PARAM_LATENCY 0x80000000
+
 extern const effect_descriptor_t equalizer_descriptor;
 
 typedef struct equalizer_context_s {
diff --git a/post_proc/reverb.c b/post_proc/reverb.c
index e97b651..a0a0441 100644
--- a/post_proc/reverb.c
+++ b/post_proc/reverb.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 - 2014, 2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2013 - 2014, 2017-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2013 The Android Open Source Project
@@ -30,6 +30,8 @@
 #include "effect_api.h"
 #include "reverb.h"
 
+#define REVERB_MAX_LATENCY 100
+
 /* Offload auxiliary environmental reverb UUID: 79a18026-18fd-4185-8233-0002a5d5c51b */
 const effect_descriptor_t aux_env_reverb_descriptor = {
         { 0xc2e5d5f0, 0x94bd, 0x4763, 0x9cac, { 0x4e, 0x23, 0x4d, 0x06, 0x83, 0x9e } },
@@ -522,6 +524,11 @@
            p->status = -EINVAL;
         p->vsize = sizeof(reverb_settings_t);
         break;
+    case REVERB_PARAM_LATENCY:
+        if (p->vsize < sizeof(uint32_t))
+            return -EINVAL;
+        p->vsize = sizeof(uint32_t);
+        break;
     default:
         p->status = -EINVAL;
     }
@@ -575,6 +582,9 @@
         reverb_settings->diffusion = reverb_get_diffusion(reverb_ctxt);
         reverb_settings->density = reverb_get_density(reverb_ctxt);
         break;
+    case REVERB_PARAM_LATENCY:
+        *(uint16_t *)value = REVERB_MAX_LATENCY;
+        break;
     default:
         p->status = -EINVAL;
         break;
diff --git a/post_proc/reverb.h b/post_proc/reverb.h
index 3bdd9af..cc11c46 100644
--- a/post_proc/reverb.h
+++ b/post_proc/reverb.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2013-2014, 2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2013 The Android Open Source Project
@@ -24,6 +24,8 @@
 
 #define REVERB_DEFAULT_PRESET REVERB_PRESET_NONE
 
+#define REVERB_PARAM_LATENCY 0x80000000
+
 extern const effect_descriptor_t aux_env_reverb_descriptor;
 extern const effect_descriptor_t ins_env_reverb_descriptor;
 extern const effect_descriptor_t aux_preset_reverb_descriptor;
diff --git a/post_proc/virtualizer.c b/post_proc/virtualizer.c
index dfa7691..578cf0b 100644
--- a/post_proc/virtualizer.c
+++ b/post_proc/virtualizer.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013-2015, 2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2013-2015, 2017-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2013 The Android Open Source Project
@@ -29,6 +29,8 @@
 #include "effect_api.h"
 #include "virtualizer.h"
 
+#define VIRUALIZER_MAX_LATENCY 30
+
 /* Offload Virtualizer UUID: 509a4498-561a-4bea-b3b1-0002a5d5c51b */
 const effect_descriptor_t virtualizer_descriptor = {
         {0x37cc2c00, 0xdddd, 0x11db, 0x8577, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
@@ -304,6 +306,11 @@
            p->status = -EINVAL;
         p->vsize = sizeof(uint32_t);
         break;
+    case VIRTUALIZER_PARAM_LATENCY:
+        if (p->vsize < sizeof(uint32_t))
+            p->status = -EINVAL;
+        p->vsize = sizeof(uint32_t);
+        break;
     default:
         p->status = -EINVAL;
     }
@@ -347,6 +354,10 @@
         *(uint32_t *)value  = (uint32_t) virtualizer_get_virtualization_mode(virt_ctxt);
         break;
 
+    case VIRTUALIZER_PARAM_LATENCY:
+        *(uint32_t *)value = VIRUALIZER_MAX_LATENCY;
+        break;
+
     default:
         p->status = -EINVAL;
         break;
diff --git a/post_proc/virtualizer.h b/post_proc/virtualizer.h
index 904a0c6..c0e6a87 100644
--- a/post_proc/virtualizer.h
+++ b/post_proc/virtualizer.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013-2015, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2013-2015, 2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2013 The Android Open Source Project
@@ -20,6 +20,8 @@
 #ifndef OFFLOAD_VIRTUALIZER_H_
 #define OFFLOAD_VIRTUALIZER_H_
 
+#define VIRTUALIZER_PARAM_LATENCY 0x80000000
+
 #include "bundle.h"
 
 extern const effect_descriptor_t virtualizer_descriptor;
diff --git a/qahw/inc/qahw.h b/qahw/inc/qahw.h
index e91fd00..dd5b403 100644
--- a/qahw/inc/qahw.h
+++ b/qahw/inc/qahw.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2011 The Android Open Source Project *
@@ -463,6 +463,13 @@
 /* Release an audio patch */
 int qahw_release_audio_patch_l(qahw_module_handle_t *hw_module,
                         audio_patch_handle_t handle);
+
+/* API to set loopback stream specific config parameters. */
+int qahw_loopback_set_param_data_l(qahw_module_handle_t *hw_module,
+                                   audio_patch_handle_t handle,
+                                   qahw_loopback_param_id param_id,
+                                   qahw_loopback_param_payload *payload);
+
 /* Fills the list of supported attributes for a given audio port.
  * As input, "port" contains the information (type, role, address etc...)
  * needed by the HAL to identify the port.
diff --git a/qahw/inc/qahw_defs.h b/qahw/inc/qahw_defs.h
index 4e7faff..755553b 100644
--- a/qahw/inc/qahw_defs.h
+++ b/qahw/inc/qahw_defs.h
@@ -417,6 +417,14 @@
     QAHW_PARAM_LICENSE_PARAMS,
 } qahw_param_id;
 
+typedef union {
+    struct qahw_out_render_window_param render_window_params;
+} qahw_loopback_param_payload;
+
+typedef enum {
+    QAHW_PARAM_LOOPBACK_RENDER_WINDOW /* PARAM to set render window */
+} qahw_loopback_param_id;
+
 __END_DECLS
 
 #endif  // QTI_AUDIO_HAL_DEFS_H
diff --git a/qahw/src/qahw.c b/qahw/src/qahw.c
index 0c00158..3390c26 100644
--- a/qahw/src/qahw.c
+++ b/qahw/src/qahw.c
@@ -69,6 +69,10 @@
                                       qahw_param_id param_id,
                                       qahw_param_payload *payload);
 
+typedef int (*qahwi_loopback_set_param_data_t)(audio_patch_handle_t patch_handle,
+                                               qahw_loopback_param_id param_id,
+                                               qahw_loopback_param_payload *payload);
+
 typedef struct {
     audio_hw_device_t *audio_device;
     char module_name[MAX_MODULE_NAME_LENGTH];
@@ -80,6 +84,7 @@
     const hw_module_t* module;
     qahwi_get_param_data_t qahwi_get_param_data;
     qahwi_set_param_data_t qahwi_set_param_data;
+    qahwi_loopback_set_param_data_t qahwi_loopback_set_param_data;
 } qahw_module_t;
 
 typedef struct {
@@ -1438,6 +1443,34 @@
      return ret;
 }
 
+int qahw_loopback_set_param_data_l(qahw_module_handle_t *hw_module,
+                                   audio_patch_handle_t handle,
+                                   qahw_loopback_param_id param_id,
+                                   qahw_loopback_param_payload *payload)
+
+{
+    int ret = -EINVAL;
+    qahw_module_t *qahw_module = (qahw_module_t *)hw_module;
+
+    if (!payload) {
+        ALOGE("%s:: invalid param", __func__);
+        goto exit;
+    }
+
+    if (qahw_module->qahwi_loopback_set_param_data) {
+        ret = qahw_module->qahwi_loopback_set_param_data(handle,
+                                                         param_id,
+                                                         payload);
+    } else {
+        ret = -ENOSYS;
+        ALOGE("%s not supported\n", __func__);
+    }
+
+exit:
+    return ret;
+
+}
+
 /* Fills the list of supported attributes for a given audio port.
  * As input, "port" contains the information (type, role, address etc...)
  * needed by the HAL to identify the port.
@@ -1889,6 +1922,12 @@
     if (!qahw_module->qahwi_set_param_data)
          ALOGD("%s::qahwi_set_param_data api is not defined\n",__func__);
 
+    qahw_module->qahwi_loopback_set_param_data = (qahwi_loopback_set_param_data_t)
+                                                  dlsym(module->dso,
+                                                  "qahwi_loopback_set_param_data");
+    if (!qahw_module->qahwi_loopback_set_param_data)
+         ALOGD("%s::qahwi_loopback_set_param_data api is not defined\n", __func__);
+
     if (!qahw_list_count)
         list_init(&qahw_module_list);
     qahw_list_count++;
diff --git a/qahw_api/inc/qahw_api.h b/qahw_api/inc/qahw_api.h
index 0aa3c79..823c6bb 100644
--- a/qahw_api/inc/qahw_api.h
+++ b/qahw_api/inc/qahw_api.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2011 The Android Open Source Project *
@@ -459,6 +459,13 @@
 /* Release an audio patch */
 int qahw_release_audio_patch(qahw_module_handle_t *hw_module,
                         audio_patch_handle_t handle);
+
+/* API to set loopback stream specific config parameters */
+int qahw_loopback_set_param_data(qahw_module_handle_t *hw_module,
+                                 audio_patch_handle_t handle,
+                                 qahw_loopback_param_id param_id,
+                                 qahw_loopback_param_payload *payload);
+
 /* Fills the list of supported attributes for a given audio port.
  * As input, "port" contains the information (type, role, address etc...)
  * needed by the HAL to identify the port.
diff --git a/qahw_api/inc/qahw_defs.h b/qahw_api/inc/qahw_defs.h
index c6d42ca..7c01c57 100644
--- a/qahw_api/inc/qahw_defs.h
+++ b/qahw_api/inc/qahw_defs.h
@@ -399,6 +399,15 @@
     QAHW_PARAM_LICENSE_PARAMS,
 } qahw_param_id;
 
+
+typedef union {
+    struct qahw_out_render_window_param render_window_params;
+} qahw_loopback_param_payload;
+
+typedef enum {
+    QAHW_PARAM_LOOPBACK_RENDER_WINDOW /* PARAM to set render window */
+} qahw_loopback_param_id;
+
 __END_DECLS
 
 #endif  // QTI_AUDIO_HAL_DEFS_H
diff --git a/qahw_api/inc/qahw_effect_bassboost.h b/qahw_api/inc/qahw_effect_bassboost.h
index 2ca8409..b397f21 100644
--- a/qahw_api/inc/qahw_effect_bassboost.h
+++ b/qahw_api/inc/qahw_effect_bassboost.h
@@ -40,7 +40,9 @@
 typedef enum
 {
     BASSBOOST_PARAM_STRENGTH_SUPPORTED,
-    BASSBOOST_PARAM_STRENGTH
+    BASSBOOST_PARAM_STRENGTH,
+    BASSBOOST_PARAM_LATENCY = 0x80000000 // Internal paramter specific to qahw.
+                                         // Used to get latency introduced by bassboost effect.
 } qahw_bassboost_params;
 
 #ifdef __cplusplus
diff --git a/qahw_api/inc/qahw_effect_environmentalreverb.h b/qahw_api/inc/qahw_effect_environmentalreverb.h
index a47eb28..61ef39e 100644
--- a/qahw_api/inc/qahw_effect_environmentalreverb.h
+++ b/qahw_api/inc/qahw_effect_environmentalreverb.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2017-2018, The Linux Foundation. All rights reserved.
  * Not a Contribution.
  *
  * Copyright (C) 2011 The Android Open Source Project
@@ -22,7 +22,7 @@
 
 #include <qahw_effect_api.h>
 
-#if __cplusplus
+#ifdef __cplusplus
 extern "C" {
 #endif
 
@@ -55,7 +55,9 @@
     REVERB_PARAM_DIFFUSION,             // in permilles,    range 0 to 1000
     REVERB_PARAM_DENSITY,               // in permilles,    range 0 to 1000
     REVERB_PARAM_PROPERTIES,
-    REVERB_PARAM_BYPASS
+    REVERB_PARAM_BYPASS,
+    REVERB_PARAM_LATENCY = 0x80000000   // Internal paramter specific to qahw.
+                                        // Used to get latency introduced by reverb effect.
 } qahw_env_reverb_params;
 
 //qahw_reverb_settings is equal to SLEnvironmentalReverbSettings defined in OpenSL ES specification.
@@ -73,7 +75,7 @@
 } __attribute__((packed)) qahw_reverb_settings;
 
 
-#if __cplusplus
+#ifdef __cplusplus
 }  // extern "C"
 #endif
 
diff --git a/qahw_api/inc/qahw_effect_equalizer.h b/qahw_api/inc/qahw_effect_equalizer.h
index fd71c4c..e4d6c5b 100644
--- a/qahw_api/inc/qahw_effect_equalizer.h
+++ b/qahw_api/inc/qahw_effect_equalizer.h
@@ -50,7 +50,9 @@
     EQ_PARAM_CUR_PRESET,            // Gets/Sets the current preset.
     EQ_PARAM_GET_NUM_OF_PRESETS,    // Gets the total number of presets the equalizer supports.
     EQ_PARAM_GET_PRESET_NAME,       // Gets the preset name based on the index.
-    EQ_PARAM_PROPERTIES             // Gets/Sets all parameters at a time.
+    EQ_PARAM_PROPERTIES,            // Gets/Sets all parameters at a time.
+    EQ_PARAM_LATENCY = 0x80000000   // Internal paramter specific to qahw.
+                                    // Used to get latency introduced by equalizer effect.
 } qahw_equalizer_params;
 
 enum
diff --git a/qahw_api/inc/qahw_effect_virtualizer.h b/qahw_api/inc/qahw_effect_virtualizer.h
index 5ff95ce..481f0ef 100644
--- a/qahw_api/inc/qahw_effect_virtualizer.h
+++ b/qahw_api/inc/qahw_effect_virtualizer.h
@@ -75,7 +75,10 @@
     //                                   AUDIO_DEVICE_NONE when not virtualizing
     //   status     int -EINVAL if an error occurred
     //                  0       if the output value is successfully retrieved
-    VIRTUALIZER_PARAM_VIRTUALIZATION_MODE
+    VIRTUALIZER_PARAM_VIRTUALIZATION_MODE,
+    // Internal paramter specific to qahw.
+    // Used to get latency introduced by virtuaizer effect.
+    VIRTUALIZER_PARAM_LATENCY = 0x80000000
 } qahw_virtualizer_params;
 
 #ifdef __cplusplus
diff --git a/qahw_api/src/qahw_api.cpp b/qahw_api/src/qahw_api.cpp
index cbd9041..f1c75f4 100644
--- a/qahw_api/src/qahw_api.cpp
+++ b/qahw_api/src/qahw_api.cpp
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2016-2017, The Linux Foundation. All rights reserved.
+* Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
@@ -915,6 +915,15 @@
     }
 }
 
+int qahw_loopback_set_param_data(qahw_module_handle_t *hw_module __unused,
+                                 audio_patch_handle_t handle __unused,
+                                 qahw_loopback_param_id param_id __unused,
+                                 qahw_loopback_param_payload *payload __unused)
+{
+    ALOGD("%d:%s", __LINE__, __func__);
+    return -ENOSYS;
+}
+
 int qahw_get_audio_port(qahw_module_handle_t *hw_module,
                       struct audio_port *port)
 {
@@ -1699,6 +1708,15 @@
     return qahw_release_audio_patch_l(hw_module, handle);
 }
 
+int qahw_loopback_set_param_data(qahw_module_handle_t *hw_module,
+                                 audio_patch_handle_t handle,
+                                 qahw_loopback_param_id param_id,
+                                 qahw_loopback_param_payload *payload)
+{
+    ALOGV("%d:%s\n", __LINE__, __func__);
+    return qahw_loopback_set_param_data_l(hw_module, handle, param_id, payload);
+}
+
 int qahw_get_audio_port(qahw_module_handle_t *hw_module,
                       struct audio_port *port)
 {
diff --git a/qahw_api/test/qahw_playback_test.c b/qahw_api/test/qahw_playback_test.c
index af3cc57..556f520 100644
--- a/qahw_api/test/qahw_playback_test.c
+++ b/qahw_api/test/qahw_playback_test.c
@@ -1228,7 +1228,6 @@
 
     char latency_buf[200] = {0};
     fread((void *) latency_buf, 100, 1, fd_latency_node);
-    fclose(fd_latency_node);
     sscanf(latency_buf, " %llu,%llu,%*llu,%*llu,%llu,%llu", &scold, &uscold, &scont, &uscont);
     tcold = scold*1000 - ((uint64_t)ts_cold.tv_sec)*1000 + uscold/1000 - ((uint64_t)ts_cold.tv_nsec)/1000000;
     tcont = scont*1000 - ((uint64_t)ts_cont.tv_sec)*1000 + uscont/1000 - ((uint64_t)ts_cont.tv_nsec)/1000000;
@@ -2572,6 +2571,7 @@
         fprintf(log_file, "stream %d: Output Flags:%d\n", stream->stream_index, stream->flags);
         fprintf(log_file, "stream %d: Sample Rate:%d\n", stream->stream_index, stream->config.offload_info.sample_rate);
         fprintf(log_file, "stream %d: Channels:%d\n", stream->stream_index, stream->channels);
+        fprintf(log_file, "stream %d: Channel Mask:%x\n", stream->stream_index, stream->config.channel_mask);
         fprintf(log_file, "stream %d: Bitwidth:%d\n", stream->stream_index, stream->config.offload_info.bit_width);
         fprintf(log_file, "stream %d: AAC Format Type:%d\n", stream->stream_index, stream->aac_fmt_type);
         fprintf(log_file, "stream %d: Kvpair Values:%s\n", stream->stream_index, stream->kvpair_values);