Add generic audio HW module for Bluetooth audio HAL V2

This is loaded from audio HAL when initials the audio HW module,
bluetooth_audio, and uses Bluetooth audio HAL V2 to provide stream APIs
for control and data path. When the audio framework opens different
input or output streams, it uses the audio device type to choose which
SessionType is and pass to Bluetooth audio HAL so associates with the
Provider / Port pair and communicate with the Bluetooth stack.

* Audio contrl path uses IBluetoothAudioPort interface to interact with
  the Bluetooth stack.
* Audio data path uses HIDL Fast Message Queue that is maintained within
  IBluetoothAudioProvider HIDL and is ready after session started.

Bug: 111519504
Bug: 122503379
Test: manual

Change-Id: Ie668456179357c26397f5c6234ff46b5308dfe24
diff --git a/Android.bp b/Android.bp
index dd1d7fa..174b8cd 100644
--- a/Android.bp
+++ b/Android.bp
@@ -5,6 +5,7 @@
     "btcore",
     "common",
     "audio_a2dp_hw",
+    "audio_bluetooth_hw",
     "audio_hearing_aid_hw",
     "hci",
     "utils",
diff --git a/audio_bluetooth_hw/Android.bp b/audio_bluetooth_hw/Android.bp
new file mode 100644
index 0000000..df4904b
--- /dev/null
+++ b/audio_bluetooth_hw/Android.bp
@@ -0,0 +1,49 @@
+// The format of the name is audio.<type>.<hardware/etc>.so
+
+cc_library_shared {
+    name: "audio.bluetooth.default",
+    relative_install_path: "hw",
+    proprietary: true,
+    srcs: [
+        "audio_bluetooth_hw.cc",
+        "stream_apis.cc",
+        "device_port_proxy.cc",
+        "utils.cc",
+    ],
+    header_libs: ["libhardware_headers"],
+    shared_libs: [
+        "android.hardware.bluetooth.audio@2.0",
+        "libbase",
+        "libbluetooth_audio_session",
+        "libcutils",
+        "libfmq",
+        "libhidlbase",
+        "libhidltransport",
+        "liblog",
+        "libutils",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wno-unused-parameter",
+    ],
+}
+
+cc_test {
+    name: "audio_bluetooth_hw_test",
+    srcs: [
+        "utils.cc",
+        "utils_unittest.cc",
+    ],
+    shared_libs: [
+        "libbase",
+        "libcutils",
+        "liblog",
+        "libutils",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wno-unused-parameter",
+    ],
+}
diff --git a/audio_bluetooth_hw/audio_bluetooth_hw.cc b/audio_bluetooth_hw/audio_bluetooth_hw.cc
new file mode 100644
index 0000000..e32d88b
--- /dev/null
+++ b/audio_bluetooth_hw/audio_bluetooth_hw.cc
@@ -0,0 +1,140 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "BTAudioHw"
+
+#include <android-base/logging.h>
+#include <errno.h>
+#include <hardware/audio.h>
+#include <hardware/hardware.h>
+#include <log/log.h>
+#include <malloc.h>
+#include <string.h>
+#include <system/audio.h>
+
+#include "stream_apis.h"
+#include "utils.h"
+
+static int adev_set_parameters(struct audio_hw_device* dev,
+                               const char* kvpairs) {
+  LOG(VERBOSE) << __func__ << ": kevpairs=[" << kvpairs << "]";
+  return -ENOSYS;
+}
+
+static char* adev_get_parameters(const struct audio_hw_device* dev,
+                                 const char* keys) {
+  LOG(VERBOSE) << __func__ << ": keys=[" << keys << "]";
+  return strdup("");
+}
+
+static int adev_init_check(const struct audio_hw_device* dev) { return 0; }
+
+static int adev_set_voice_volume(struct audio_hw_device* dev, float volume) {
+  LOG(VERBOSE) << __func__ << ": volume=" << volume;
+  return -ENOSYS;
+}
+
+static int adev_set_master_volume(struct audio_hw_device* dev, float volume) {
+  LOG(VERBOSE) << __func__ << ": volume=" << volume;
+  return -ENOSYS;
+}
+
+static int adev_get_master_volume(struct audio_hw_device* dev, float* volume) {
+  return -ENOSYS;
+}
+
+static int adev_set_master_mute(struct audio_hw_device* dev, bool muted) {
+  LOG(VERBOSE) << __func__ << ": mute=" << muted;
+  return -ENOSYS;
+}
+
+static int adev_get_master_mute(struct audio_hw_device* dev, bool* muted) {
+  return -ENOSYS;
+}
+
+static int adev_set_mode(struct audio_hw_device* dev, audio_mode_t mode) {
+  LOG(VERBOSE) << __func__ << ": mode=" << mode;
+  return 0;
+}
+
+static int adev_set_mic_mute(struct audio_hw_device* dev, bool state) {
+  LOG(VERBOSE) << __func__ << ": state=" << state;
+  return -ENOSYS;
+}
+
+static int adev_get_mic_mute(const struct audio_hw_device* dev, bool* state) {
+  return -ENOSYS;
+}
+
+static int adev_dump(const audio_hw_device_t* device, int fd) { return 0; }
+
+static int adev_close(hw_device_t* device) {
+  free(device);
+  return 0;
+}
+
+static int adev_open(const hw_module_t* module, const char* name,
+                     hw_device_t** device) {
+  LOG(VERBOSE) << __func__ << ": name=[" << name << "]";
+  if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL;
+
+  struct audio_hw_device* adev =
+      (struct audio_hw_device*)calloc(1, sizeof(struct audio_hw_device));
+  if (!adev) return -ENOMEM;
+
+  adev->common.tag = HARDWARE_DEVICE_TAG;
+  adev->common.version = AUDIO_DEVICE_API_VERSION_2_0;
+  adev->common.module = (struct hw_module_t*)module;
+  adev->common.close = adev_close;
+
+  adev->init_check = adev_init_check;
+  adev->set_voice_volume = adev_set_voice_volume;
+  adev->set_master_volume = adev_set_master_volume;
+  adev->get_master_volume = adev_get_master_volume;
+  adev->set_mode = adev_set_mode;
+  adev->set_mic_mute = adev_set_mic_mute;
+  adev->get_mic_mute = adev_get_mic_mute;
+  adev->set_parameters = adev_set_parameters;
+  adev->get_parameters = adev_get_parameters;
+  adev->get_input_buffer_size = adev_get_input_buffer_size;
+  adev->open_output_stream = adev_open_output_stream;
+  adev->close_output_stream = adev_close_output_stream;
+  adev->open_input_stream = adev_open_input_stream;
+  adev->close_input_stream = adev_close_input_stream;
+  adev->dump = adev_dump;
+  adev->set_master_mute = adev_set_master_mute;
+  adev->get_master_mute = adev_get_master_mute;
+
+  *device = &adev->common;
+  return 0;
+}
+
+static struct hw_module_methods_t hal_module_methods = {
+    .open = adev_open,
+};
+
+struct audio_module HAL_MODULE_INFO_SYM = {
+    .common =
+        {
+            .tag = HARDWARE_MODULE_TAG,
+            .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
+            .hal_api_version = HARDWARE_HAL_API_VERSION,
+            .id = AUDIO_HARDWARE_MODULE_ID,
+            .name = "Bluetooth Audio HW HAL",
+            .author = "The Android Open Source Project",
+            .methods = &hal_module_methods,
+        },
+};
diff --git a/audio_bluetooth_hw/device_port_proxy.cc b/audio_bluetooth_hw/device_port_proxy.cc
new file mode 100644
index 0000000..d38608e
--- /dev/null
+++ b/audio_bluetooth_hw/device_port_proxy.cc
@@ -0,0 +1,473 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "BTAudioHalDeviceProxy"
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <inttypes.h>
+#include <log/log.h>
+#include <stdlib.h>
+
+#include "BluetoothAudioSessionControl.h"
+#include "device_port_proxy.h"
+#include "stream_apis.h"
+#include "utils.h"
+
+namespace android {
+namespace bluetooth {
+namespace audio {
+
+using ::android::bluetooth::audio::BluetoothAudioSessionControl;
+using ::android::hardware::bluetooth::audio::V2_0::BitsPerSample;
+using ::android::hardware::bluetooth::audio::V2_0::ChannelMode;
+using ::android::hardware::bluetooth::audio::V2_0::PcmParameters;
+using ::android::hardware::bluetooth::audio::V2_0::SampleRate;
+using ::android::hardware::bluetooth::audio::V2_0::SessionType;
+using BluetoothAudioStatus =
+    ::android::hardware::bluetooth::audio::V2_0::Status;
+using ControlResultCallback = std::function<void(
+    uint16_t cookie, bool start_resp, const BluetoothAudioStatus& status)>;
+using SessionChangedCallback = std::function<void(uint16_t cookie)>;
+
+namespace {
+
+unsigned int SampleRateToAudioFormat(SampleRate sample_rate) {
+  switch (sample_rate) {
+    case SampleRate::RATE_16000:
+      return 16000;
+    case SampleRate::RATE_24000:
+      return 24000;
+    case SampleRate::RATE_44100:
+      return 44100;
+    case SampleRate::RATE_48000:
+      return 48000;
+    case SampleRate::RATE_88200:
+      return 88200;
+    case SampleRate::RATE_96000:
+      return 96000;
+    case SampleRate::RATE_176400:
+      return 176400;
+    case SampleRate::RATE_192000:
+      return 192000;
+    default:
+      return kBluetoothDefaultSampleRate;
+  }
+}
+audio_channel_mask_t ChannelModeToAudioFormat(ChannelMode channel_mode) {
+  switch (channel_mode) {
+    case ChannelMode::MONO:
+      return AUDIO_CHANNEL_OUT_MONO;
+    case ChannelMode::STEREO:
+      return AUDIO_CHANNEL_OUT_STEREO;
+    default:
+      return kBluetoothDefaultOutputChannelModeMask;
+  }
+}
+
+audio_format_t BitsPerSampleToAudioFormat(BitsPerSample bits_per_sample) {
+  switch (bits_per_sample) {
+    case BitsPerSample::BITS_16:
+      return AUDIO_FORMAT_PCM_16_BIT;
+    case BitsPerSample::BITS_24:
+      return AUDIO_FORMAT_PCM_24_BIT_PACKED;
+    case BitsPerSample::BITS_32:
+      return AUDIO_FORMAT_PCM_32_BIT;
+    default:
+      return kBluetoothDefaultAudioFormatBitsPerSample;
+  }
+}
+
+// The maximum time to wait in std::condition_variable::wait_for()
+constexpr unsigned int kMaxWaitingTimeMs = 4500;
+
+}  // namespace
+
+BluetoothAudioPortOut::BluetoothAudioPortOut()
+    : state_(BluetoothStreamState::DISABLED),
+      session_type_(SessionType::UNKNOWN),
+      cookie_(android::bluetooth::audio::kObserversCookieUndefined) {}
+
+bool BluetoothAudioPortOut::SetUp(audio_devices_t devices) {
+  if (!init_session_type(devices)) return false;
+
+  state_ = BluetoothStreamState::STANDBY;
+
+  auto control_result_cb = [port = this](uint16_t cookie, bool start_resp,
+                                         const BluetoothAudioStatus& status) {
+    if (!port->in_use()) {
+      LOG(ERROR) << ": BluetoothAudioPortOut is not in use";
+      return;
+    }
+    if (port->cookie_ != cookie) {
+      LOG(ERROR) << "control_result_cb: proxy of device port (cookie=0x"
+                 << android::base::StringPrintf("%04hx", cookie)
+                 << ") is corrupted";
+      return;
+    }
+    port->ControlResultHandler(status);
+  };
+  auto session_changed_cb = [port = this](uint16_t cookie) {
+    if (!port->in_use()) {
+      LOG(ERROR) << ": BluetoothAudioPortOut is not in use";
+      return;
+    }
+    if (port->cookie_ != cookie) {
+      LOG(ERROR) << "session_changed_cb: proxy of device port (cookie=0x"
+                 << android::base::StringPrintf("%04hx", cookie)
+                 << ") is corrupted";
+      return;
+    }
+    port->SessionChangedHandler();
+  };
+  ::android::bluetooth::audio::PortStatusCallbacks cbacks = {
+      .control_result_cb_ = control_result_cb,
+      .session_changed_cb_ = session_changed_cb};
+  cookie_ = BluetoothAudioSessionControl::RegisterControlResultCback(
+      session_type_, cbacks);
+  LOG(INFO) << __func__ << ": session_type=" << toString(session_type_)
+            << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_);
+
+  return (cookie_ != android::bluetooth::audio::kObserversCookieUndefined);
+}
+
+bool BluetoothAudioPortOut::init_session_type(audio_devices_t device) {
+  switch (device) {
+    case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
+    case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
+    case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
+      LOG(VERBOSE)
+          << __func__
+          << "device=AUDIO_DEVICE_OUT_BLUETOOTH_A2DP (HEADPHONES/SPEAKER) (0x"
+          << android::base::StringPrintf("%08x", device) << ")";
+      session_type_ = SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH;
+      break;
+    case AUDIO_DEVICE_OUT_HEARING_AID:
+      LOG(VERBOSE) << __func__
+                   << "device=AUDIO_DEVICE_OUT_HEARING_AID (MEDIA/VOICE) (0x"
+                   << android::base::StringPrintf("%08x", device) << ")";
+      session_type_ = SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH;
+      break;
+    default:
+      LOG(ERROR) << __func__ << "unknown device=0x"
+                 << android::base::StringPrintf("%08x", device);
+      return false;
+  }
+
+  if (!BluetoothAudioSessionControl::IsSessionReady(session_type_)) {
+    LOG(ERROR) << __func__ << "device=0x"
+               << android::base::StringPrintf("%08x", device)
+               << ", session_type=" << toString(session_type_)
+               << " is not ready";
+    return false;
+  }
+  return true;
+}
+
+void BluetoothAudioPortOut::TearDown() {
+  if (!in_use()) {
+    LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_)
+               << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+               << " unknown monitor";
+    return;
+  }
+
+  LOG(INFO) << __func__ << ": session_type=" << toString(session_type_)
+            << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_);
+  BluetoothAudioSessionControl::UnregisterControlResultCback(session_type_,
+                                                             cookie_);
+  cookie_ = android::bluetooth::audio::kObserversCookieUndefined;
+}
+
+void BluetoothAudioPortOut::ControlResultHandler(
+    const BluetoothAudioStatus& status) {
+  if (!in_use()) {
+    LOG(ERROR) << __func__ << ": BluetoothAudioPortOut is not in use";
+    return;
+  }
+  std::unique_lock<std::mutex> port_lock(cv_mutex_);
+  BluetoothStreamState previous_state = state_;
+  LOG(INFO) << "control_result_cb: session_type=" << toString(session_type_)
+            << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+            << ", previous_state=" << previous_state
+            << ", status=" << toString(status);
+
+  switch (previous_state) {
+    case BluetoothStreamState::STARTING:
+      if (status == BluetoothAudioStatus::SUCCESS) {
+        state_ = BluetoothStreamState::STARTED;
+      } else {
+        // Set to standby since the stack may be busy switching
+        LOG(ERROR) << "control_result_cb: status=" << toString(status)
+                   << " failure for session_type=" << toString(session_type_)
+                   << ", cookie=0x"
+                   << android::base::StringPrintf("%04hx", cookie_)
+                   << ", previous_state=" << previous_state;
+        state_ = BluetoothStreamState::STANDBY;
+      }
+      break;
+    case BluetoothStreamState::SUSPENDING:
+      if (status == BluetoothAudioStatus::SUCCESS) {
+        state_ = BluetoothStreamState::STANDBY;
+      } else {
+        // This should never fail and we need to recover
+        LOG(FATAL) << "control_result_cb: status=" << toString(status)
+                   << " failure for session_type=" << toString(session_type_)
+                   << ", cookie=0x"
+                   << android::base::StringPrintf("%04hx", cookie_)
+                   << ", previous_state=" << previous_state;
+        state_ = BluetoothStreamState::DISABLED;
+      }
+      break;
+    default:
+      LOG(ERROR) << "control_result_cb: unexpected status=" << toString(status)
+                 << " for session_type=" << toString(session_type_)
+                 << ", cookie=0x"
+                 << android::base::StringPrintf("%04hx", cookie_)
+                 << ", previous_state=" << previous_state;
+      return;
+  }
+  port_lock.unlock();
+  internal_cv_.notify_all();
+}
+
+void BluetoothAudioPortOut::SessionChangedHandler() {
+  if (!in_use()) {
+    LOG(ERROR) << __func__ << ": BluetoothAudioPortOut is not in use";
+    return;
+  }
+  std::unique_lock<std::mutex> port_lock(cv_mutex_);
+  BluetoothStreamState previous_state = state_;
+  LOG(INFO) << "session_changed_cb: session_type=" << toString(session_type_)
+            << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+            << ", previous_state=" << previous_state;
+  if (previous_state != BluetoothStreamState::DISABLED) {
+    state_ = BluetoothStreamState::DISABLED;
+  } else {
+    state_ = BluetoothStreamState::STANDBY;
+  }
+  port_lock.unlock();
+  internal_cv_.notify_all();
+}
+
+bool BluetoothAudioPortOut::in_use() const {
+  return (cookie_ != android::bluetooth::audio::kObserversCookieUndefined);
+}
+
+bool BluetoothAudioPortOut::LoadAudioConfig(audio_config_t* audio_cfg) const {
+  if (!in_use()) {
+    LOG(ERROR) << __func__ << ": BluetoothAudioPortOut is not in use";
+    audio_cfg->sample_rate = kBluetoothDefaultSampleRate;
+    audio_cfg->channel_mask = kBluetoothDefaultOutputChannelModeMask;
+    audio_cfg->format = kBluetoothDefaultAudioFormatBitsPerSample;
+    return false;
+  }
+
+  const AudioConfiguration& hal_audio_cfg =
+      BluetoothAudioSessionControl::GetAudioConfig(session_type_);
+  if (hal_audio_cfg.getDiscriminator() !=
+      AudioConfiguration::hidl_discriminator::pcmConfig) {
+    audio_cfg->sample_rate = kBluetoothDefaultSampleRate;
+    audio_cfg->channel_mask = kBluetoothDefaultOutputChannelModeMask;
+    audio_cfg->format = kBluetoothDefaultAudioFormatBitsPerSample;
+    return false;
+  }
+  const PcmParameters& pcm_cfg = hal_audio_cfg.pcmConfig();
+  LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_)
+               << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+               << ", state=" << state_ << ", PcmConfig=[" << toString(pcm_cfg)
+               << "]";
+  if (pcm_cfg.sampleRate == SampleRate::RATE_UNKNOWN ||
+      pcm_cfg.channelMode == ChannelMode::UNKNOWN ||
+      pcm_cfg.bitsPerSample == BitsPerSample::BITS_UNKNOWN) {
+    return false;
+  }
+  audio_cfg->sample_rate = SampleRateToAudioFormat(pcm_cfg.sampleRate);
+  audio_cfg->channel_mask = ChannelModeToAudioFormat(pcm_cfg.channelMode);
+  audio_cfg->format = BitsPerSampleToAudioFormat(pcm_cfg.bitsPerSample);
+  return true;
+}
+
+bool BluetoothAudioPortOut::CondwaitState(BluetoothStreamState state) {
+  bool retval;
+  std::unique_lock<std::mutex> port_lock(cv_mutex_);
+  switch (state) {
+    case BluetoothStreamState::STARTING:
+      LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_)
+                   << ", cookie=0x"
+                   << android::base::StringPrintf("%04hx", cookie_)
+                   << " waiting for STARTED";
+      retval = internal_cv_.wait_for(
+          port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs),
+          [this] { return this->state_ == BluetoothStreamState::STARTED; });
+      break;
+    case BluetoothStreamState::SUSPENDING:
+      LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_)
+                   << ", cookie=0x"
+                   << android::base::StringPrintf("%04hx", cookie_)
+                   << " waiting for SUSPENDED";
+      retval = internal_cv_.wait_for(
+          port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs),
+          [this] { return this->state_ == BluetoothStreamState::STANDBY; });
+      break;
+    default:
+      LOG(WARNING) << __func__ << ": session_type=" << toString(session_type_)
+                   << ", cookie=0x"
+                   << android::base::StringPrintf("%04hx", cookie_)
+                   << " waiting for KNOWN";
+      return false;
+  }
+
+  return retval;  // false if any failure like timeout
+}
+
+bool BluetoothAudioPortOut::Start() {
+  if (!in_use()) {
+    LOG(ERROR) << __func__ << ": BluetoothAudioPortOut is not in use";
+    return false;
+  }
+
+  LOG(INFO) << __func__ << ": session_type=" << toString(session_type_)
+            << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+            << ", state=" << state_ << " request";
+  bool retval = false;
+  if (state_ == BluetoothStreamState::STANDBY) {
+    state_ = BluetoothStreamState::STARTING;
+    if (BluetoothAudioSessionControl::StartStream(session_type_)) {
+      retval = CondwaitState(BluetoothStreamState::STARTING);
+    } else {
+      LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_)
+                 << ", cookie=0x"
+                 << android::base::StringPrintf("%04hx", cookie_)
+                 << ", state=" << state_ << " Hal fails";
+    }
+  }
+
+  if (retval) {
+    LOG(INFO) << __func__ << ": session_type=" << toString(session_type_)
+              << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+              << ", state=" << state_ << " done";
+  } else {
+    LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_)
+               << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+               << ", state=" << state_ << " failure";
+  }
+
+  return retval;  // false if any failure like timeout
+}
+
+bool BluetoothAudioPortOut::Suspend() {
+  if (!in_use()) {
+    LOG(ERROR) << __func__ << ": BluetoothAudioPortOut is not in use";
+    return false;
+  }
+
+  LOG(INFO) << __func__ << ": session_type=" << toString(session_type_)
+            << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+            << ", state=" << state_ << " request";
+  bool retval = false;
+  if (state_ == BluetoothStreamState::STARTED) {
+    state_ = BluetoothStreamState::SUSPENDING;
+    if (BluetoothAudioSessionControl::SuspendStream(session_type_)) {
+      retval = CondwaitState(BluetoothStreamState::SUSPENDING);
+    } else {
+      LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_)
+                 << ", cookie=0x"
+                 << android::base::StringPrintf("%04hx", cookie_)
+                 << ", state=" << state_ << " Hal fails";
+    }
+  }
+
+  if (retval) {
+    LOG(INFO) << __func__ << ": session_type=" << toString(session_type_)
+              << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+              << ", state=" << state_ << " done";
+  } else {
+    LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_)
+               << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+               << ", state=" << state_ << " failure";
+  }
+
+  return retval;  // false if any failure like timeout
+}
+
+void BluetoothAudioPortOut::Stop() {
+  if (!in_use()) {
+    LOG(ERROR) << __func__ << ": BluetoothAudioPortOut is not in use";
+    return;
+  }
+  LOG(INFO) << __func__ << ": session_type=" << toString(session_type_)
+            << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+            << ", state=" << state_ << " request";
+  state_ = BluetoothStreamState::DISABLED;
+  BluetoothAudioSessionControl::StopStream(session_type_);
+  LOG(INFO) << __func__ << ": session_type=" << toString(session_type_)
+            << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+            << ", state=" << state_ << " done";
+}
+
+size_t BluetoothAudioPortOut::WriteData(const void* buffer,
+                                        size_t bytes) const {
+  if (!in_use()) return 0;
+  return BluetoothAudioSessionControl::OutWritePcmData(session_type_, buffer,
+                                                       bytes);
+}
+
+bool BluetoothAudioPortOut::GetPresentationPosition(uint64_t* delay_ns,
+                                                    uint64_t* bytes,
+                                                    timespec* timestamp) const {
+  if (!in_use()) {
+    LOG(ERROR) << __func__ << ": BluetoothAudioPortOut is not in use";
+    return false;
+  }
+  bool retval = BluetoothAudioSessionControl::GetPresentationPosition(
+      session_type_, delay_ns, bytes, timestamp);
+  LOG(VERBOSE) << __func__ << ": session_type=0x"
+               << android::base::StringPrintf("%02hhx", session_type_)
+               << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+               << ", state=" << state_ << ", delay=" << *delay_ns
+               << "ns, data=" << *bytes
+               << " bytes, timestamp=" << timestamp->tv_sec << "."
+               << android::base::StringPrintf("%09ld", timestamp->tv_nsec)
+               << "s";
+
+  return retval;
+}
+
+void BluetoothAudioPortOut::UpdateMetadata(
+    const source_metadata* source_metadata) const {
+  if (!in_use()) {
+    LOG(ERROR) << __func__ << ": BluetoothAudioPortOut is not in use";
+    return;
+  }
+  LOG(DEBUG) << __func__ << ": session_type=" << toString(session_type_)
+             << ", cookie=0x" << android::base::StringPrintf("%04hx", cookie_)
+             << ", state=" << state_ << ", " << source_metadata->track_count
+             << " track(s)";
+  if (source_metadata->track_count == 0) return;
+  BluetoothAudioSessionControl::UpdateTracksMetadata(session_type_,
+                                                     source_metadata);
+}
+
+BluetoothStreamState BluetoothAudioPortOut::GetState() const { return state_; }
+
+void BluetoothAudioPortOut::SetState(BluetoothStreamState state) {
+  state_ = state;
+}
+
+}  // namespace audio
+}  // namespace bluetooth
+}  // namespace android
diff --git a/audio_bluetooth_hw/device_port_proxy.h b/audio_bluetooth_hw/device_port_proxy.h
new file mode 100644
index 0000000..e4b6b25
--- /dev/null
+++ b/audio_bluetooth_hw/device_port_proxy.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android/hardware/bluetooth/audio/2.0/types.h>
+#include <hardware/audio.h>
+#include <condition_variable>
+#include <mutex>
+#include <unordered_map>
+
+enum class BluetoothStreamState : uint8_t;
+
+namespace android {
+namespace bluetooth {
+namespace audio {
+
+// Proxy for Bluetooth Audio HW Module to communicate with Bluetooth Audio
+// Session Control. All methods are not thread safe, so users must acquire a
+// lock. Note: currently, in stream_apis.cc, if GetState() is only used for
+// verbose logging, it is not locked, so the state may not be synchronized.
+class BluetoothAudioPortOut {
+ public:
+  BluetoothAudioPortOut();
+  ~BluetoothAudioPortOut() = default;
+
+  // Fetch output control / data path of BluetoothAudioPortOut and setup
+  // callbacks into BluetoothAudioProvider. If SetUp() returns false, the audio
+  // HAL must delete this BluetoothAudioPortOut and return EINVAL to caller
+  bool SetUp(audio_devices_t devices);
+
+  // Unregister this BluetoothAudioPortOut from BluetoothAudioSessionControl.
+  // Audio HAL must delete this BluetoothAudioPortOut after calling this.
+  void TearDown();
+
+  // When the Audio framework / HAL tries to query audio config about format,
+  // channel mask and sample rate, it uses this function to fetch from the
+  // Bluetooth stack
+  bool LoadAudioConfig(audio_config_t* audio_cfg) const;
+
+  // When the Audio framework / HAL wants to change the stream state, it invokes
+  // these 3 functions to control the Bluetooth stack (Audio Control Path).
+  // Note: Both Start() and Suspend() will return ture when there are no errors.
+  // Called by Audio framework / HAL to start the stream
+  bool Start();
+  // Called by Audio framework / HAL to suspend the stream
+  bool Suspend();
+  // Called by Audio framework / HAL to stop the stream
+  void Stop();
+
+  // The audio data path to the Bluetooth stack (Software encoding)
+  size_t WriteData(const void* buffer, size_t bytes) const;
+
+  // Called by the Audio framework / HAL to fetch informaiton about audio frames
+  // presented to an external sink.
+  bool GetPresentationPosition(uint64_t* delay_ns, uint64_t* bytes,
+                               timespec* timestamp) const;
+
+  // Called by the Audio framework / HAL when the metadata of the stream's
+  // source has been changed.
+  void UpdateMetadata(const source_metadata* source_metadata) const;
+
+  // Return the current BluetoothStreamState
+  BluetoothStreamState GetState() const;
+
+  // Set the current BluetoothStreamState
+  void SetState(BluetoothStreamState state);
+
+ private:
+  BluetoothStreamState state_;
+  ::android::hardware::bluetooth::audio::V2_0::SessionType session_type_;
+  uint16_t cookie_;
+  mutable std::mutex cv_mutex_;
+  std::condition_variable internal_cv_;
+
+  // Check and initialize session type for |devices| If failed, this
+  // BluetoothAudioPortOut is not initialized and must be deleted.
+  bool init_session_type(audio_devices_t device);
+
+  bool in_use() const;
+
+  bool CondwaitState(BluetoothStreamState state);
+
+  void ControlResultHandler(
+      const ::android::hardware::bluetooth::audio::V2_0::Status& status);
+  void SessionChangedHandler();
+};
+
+}  // namespace audio
+}  // namespace bluetooth
+}  // namespace android
diff --git a/audio_bluetooth_hw/stream_apis.cc b/audio_bluetooth_hw/stream_apis.cc
new file mode 100644
index 0000000..10218b8
--- /dev/null
+++ b/audio_bluetooth_hw/stream_apis.cc
@@ -0,0 +1,697 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "BTAudioHalStream"
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <cutils/properties.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <log/log.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "stream_apis.h"
+#include "utils.h"
+
+using ::android::bluetooth::audio::BluetoothAudioPortOut;
+using ::android::bluetooth::audio::utils::GetAudioParamString;
+using ::android::bluetooth::audio::utils::ParseAudioParams;
+
+namespace {
+
+constexpr unsigned int kMinimumDelayMs = 100;
+constexpr unsigned int kMaximumDelayMs = 1000;
+constexpr int kExtraAudioSyncMs = 200;
+
+std::ostream& operator<<(std::ostream& os, const audio_config& config) {
+  return os << "audio_config[sample_rate=" << config.sample_rate
+            << ", channels=0x"
+            << android::base::StringPrintf("%x", config.channel_mask)
+            << ", format=" << config.format << "]";
+}
+
+}  // namespace
+
+std::ostream& operator<<(std::ostream& os, const BluetoothStreamState& state) {
+  switch (state) {
+    case BluetoothStreamState::DISABLED:
+      return os << "DISABLED";
+    case BluetoothStreamState::STANDBY:
+      return os << "STANDBY";
+    case BluetoothStreamState::STARTING:
+      return os << "STARTING";
+    case BluetoothStreamState::STARTED:
+      return os << "STARTED";
+    case BluetoothStreamState::SUSPENDING:
+      return os << "SUSPENDING";
+    case BluetoothStreamState::UNKNOWN:
+      return os << "UNKNOWN";
+    default:
+      return os << "0x" + android::base::StringPrintf("%hhx", state);
+  }
+}
+
+static uint32_t out_get_sample_rate(const struct audio_stream* stream) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  audio_config_t audio_cfg;
+  if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
+    LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << " audio_cfg=" << audio_cfg;
+    return audio_cfg.sample_rate;
+  } else {
+    LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << ", sample_rate=" << out->sample_rate_ << " failed";
+    return out->sample_rate_;
+  }
+}
+
+static int out_set_sample_rate(struct audio_stream* stream, uint32_t rate) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", sample_rate=" << out->sample_rate_;
+  return (rate == out->sample_rate_ ? 0 : -1);
+}
+
+static size_t out_get_buffer_size(const struct audio_stream* stream) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  size_t buffer_size =
+      out->frames_count_ * audio_stream_out_frame_size(&out->stream_out_);
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", buffer_size=" << buffer_size;
+  return buffer_size;
+}
+
+static audio_channel_mask_t out_get_channels(
+    const struct audio_stream* stream) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  audio_config_t audio_cfg;
+  if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
+    LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << " audio_cfg=" << audio_cfg;
+    return audio_cfg.channel_mask;
+  } else {
+    LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << ", channels=0x"
+                 << android::base::StringPrintf("%x", out->channel_mask_)
+                 << " failure";
+    return out->channel_mask_;
+  }
+}
+
+static audio_format_t out_get_format(const struct audio_stream* stream) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  audio_config_t audio_cfg;
+  if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
+    LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << " audio_cfg=" << audio_cfg;
+    return audio_cfg.format;
+  } else {
+    LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << ", format=" << out->format_ << " failure";
+    return out->format_;
+  }
+}
+
+static int out_set_format(struct audio_stream* stream, audio_format_t format) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", format=" << out->format_;
+  return (format == out->format_ ? 0 : -1);
+}
+
+static int out_standby(struct audio_stream* stream) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+  int retval = 0;
+
+  // out->last_write_time_us_ = 0; unnecessary as a stale write time has same
+  // effect
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << " being standby (suspend)";
+  if (out->bluetooth_output_.GetState() == BluetoothStreamState::STARTED) {
+    out->frames_rendered_ = 0;
+    retval = (out->bluetooth_output_.Suspend() ? 0 : -EIO);
+  } else if (out->bluetooth_output_.GetState() ==
+                 BluetoothStreamState::STARTING ||
+             out->bluetooth_output_.GetState() ==
+                 BluetoothStreamState::SUSPENDING) {
+    LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << " NOT ready to be standby";
+    retval = -EBUSY;
+  } else {
+    LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << " standby already";
+  }
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << " standby (suspend) retval=" << retval;
+
+  return retval;
+}
+
+static int out_dump(const struct audio_stream* stream, int fd) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState();
+  return 0;
+}
+
+static int out_set_parameters(struct audio_stream* stream,
+                              const char* kvpairs) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+  int retval = 0;
+
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", kvpairs=[" << kvpairs << "]";
+
+  std::unordered_map<std::string, std::string> params =
+      ParseAudioParams(kvpairs);
+  if (params.empty()) return retval;
+
+  LOG(VERBOSE) << __func__ << ": ParamsMap=[" << GetAudioParamString(params)
+               << "]";
+
+  audio_config_t audio_cfg;
+  if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end() ||
+      params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end() ||
+      params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) {
+    if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
+      out->sample_rate_ = audio_cfg.sample_rate;
+      out->channel_mask_ = audio_cfg.channel_mask;
+      out->format_ = audio_cfg.format;
+      LOG(VERBOSE) << "state=" << out->bluetooth_output_.GetState()
+                   << ", sample_rate=" << out->sample_rate_ << ", channels=0x"
+                   << android::base::StringPrintf("%x", out->channel_mask_)
+                   << ", format=" << out->format_;
+    } else {
+      LOG(WARNING) << __func__
+                   << ": state=" << out->bluetooth_output_.GetState()
+                   << " failed to get audio config";
+    }
+  }
+
+  if (params.find("routing") != params.end()) {
+    auto routing_param = params.find("routing");
+    LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+              << ", stream param '" << routing_param->first.c_str() << "="
+              << routing_param->second.c_str() << "'";
+  }
+
+  if (params.find("A2dpSuspended") != params.end()) {
+    if (params["A2dpSuspended"] == "true") {
+      LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                << " stream param stopped";
+      if (out->bluetooth_output_.GetState() != BluetoothStreamState::DISABLED) {
+        out->frames_rendered_ = 0;
+        out->bluetooth_output_.Stop();
+      }
+    } else {
+      LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                << " stream param standby";
+      if (out->bluetooth_output_.GetState() == BluetoothStreamState::DISABLED) {
+        out->bluetooth_output_.SetState(BluetoothStreamState::STANDBY);
+      }
+    }
+  }
+
+  if (params.find("closing") != params.end()) {
+    if (params["closing"] == "true") {
+      LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                << " stream param closing, disallow any writes?";
+      if (out->bluetooth_output_.GetState() != BluetoothStreamState::DISABLED) {
+        out->frames_rendered_ = 0;
+        out->frames_presented_ = 0;
+        out->bluetooth_output_.Stop();
+      }
+    }
+  }
+
+  if (params.find("exiting") != params.end()) {
+    if (params["exiting"] == "1") {
+      LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                << " stream param exiting";
+      if (out->bluetooth_output_.GetState() != BluetoothStreamState::DISABLED) {
+        out->frames_rendered_ = 0;
+        out->frames_presented_ = 0;
+        out->bluetooth_output_.Stop();
+      }
+    }
+  }
+
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", kvpairs=[" << kvpairs << "], retval=" << retval;
+  return retval;
+}
+
+static char* out_get_parameters(const struct audio_stream* stream,
+                                const char* keys) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", keys=[" << keys << "]";
+
+  std::unordered_map<std::string, std::string> params = ParseAudioParams(keys);
+  if (params.empty()) return strdup("");
+
+  audio_config_t audio_cfg;
+  if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
+    LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << " audio_cfg=" << audio_cfg;
+  } else {
+    LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << " failed to get audio config";
+  }
+
+  std::unordered_map<std::string, std::string> return_params;
+  if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end()) {
+    std::string param;
+    if (audio_cfg.sample_rate == 16000) {
+      param = "16000";
+    }
+    if (audio_cfg.sample_rate == 24000) {
+      param = "24000";
+    }
+    if (audio_cfg.sample_rate == 44100) {
+      param = "44100";
+    }
+    if (audio_cfg.sample_rate == 48000) {
+      param = "48000";
+    }
+    if (audio_cfg.sample_rate == 88200) {
+      param = "88200";
+    }
+    if (audio_cfg.sample_rate == 96000) {
+      param = "96000";
+    }
+    if (audio_cfg.sample_rate == 176400) {
+      param = "176400";
+    }
+    if (audio_cfg.sample_rate == 192000) {
+      param = "192000";
+    }
+    return_params[AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES] = param;
+  }
+
+  if (params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end()) {
+    std::string param;
+    if (audio_cfg.channel_mask == AUDIO_CHANNEL_OUT_MONO) {
+      param = "AUDIO_CHANNEL_OUT_MONO";
+    }
+    if (audio_cfg.channel_mask == AUDIO_CHANNEL_OUT_STEREO) {
+      param = "AUDIO_CHANNEL_OUT_STEREO";
+    }
+    return_params[AUDIO_PARAMETER_STREAM_SUP_CHANNELS] = param;
+  }
+
+  if (params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) {
+    std::string param;
+    if (audio_cfg.format == AUDIO_FORMAT_PCM_16_BIT) {
+      param = "AUDIO_FORMAT_PCM_16_BIT";
+    }
+    if (audio_cfg.format == AUDIO_FORMAT_PCM_24_BIT_PACKED) {
+      param = "AUDIO_FORMAT_PCM_24_BIT_PACKED";
+    }
+    if (audio_cfg.format == AUDIO_FORMAT_PCM_32_BIT) {
+      param = "AUDIO_FORMAT_PCM_32_BIT";
+    }
+    return_params[AUDIO_PARAMETER_STREAM_SUP_FORMATS] = param;
+  }
+
+  std::string result;
+  for (const auto& ptr : return_params) {
+    result += ptr.first + "=" + ptr.second + ";";
+  }
+
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", result=[" << result << "]";
+  return strdup(result.c_str());
+}
+
+static uint32_t out_get_latency_ms(const struct audio_stream_out* stream) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+  /***
+   * audio_a2dp_hw:
+   *   frames_count = buffer_size / frame_size
+   *   latency (sec.) = frames_count / sample_rate
+   */
+  uint32_t latency_ms = out->frames_count_ * 1000 / out->sample_rate_;
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", latency_ms=" << latency_ms;
+  // Sync from audio_a2dp_hw to add extra +200ms
+  return latency_ms + kExtraAudioSyncMs;
+}
+
+static int out_set_volume(struct audio_stream_out* stream, float left,
+                          float right) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", Left=" << left << ", Right=" << right;
+  return -1;
+}
+
+static ssize_t out_write(struct audio_stream_out* stream, const void* buffer,
+                         size_t bytes) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+  size_t totalWritten = 0;
+
+  if (out->bluetooth_output_.GetState() != BluetoothStreamState::STARTED) {
+    LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+              << " first time bytes=" << bytes;
+    lock.unlock();
+    if (stream->resume(stream)) {
+      LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << " failed to resume";
+      lock.unlock();
+      usleep(kBluetoothDefaultOutputBufferMs * 1000);
+      return totalWritten;
+    }
+    lock.lock();
+  }
+  lock.unlock();
+  totalWritten = out->bluetooth_output_.WriteData(buffer, bytes);
+  lock.lock();
+
+  struct timespec ts = {.tv_sec = 0, .tv_nsec = 0};
+  clock_gettime(CLOCK_MONOTONIC, &ts);
+  if (totalWritten) {
+    const size_t frames = bytes / audio_stream_out_frame_size(stream);
+    out->frames_rendered_ += frames;
+    out->frames_presented_ += frames;
+    out->last_write_time_us_ = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
+  } else {
+    const int64_t now = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
+    const int64_t elapsed_time_since_last_write =
+        now - out->last_write_time_us_;
+    // frames_count = written_data / frame_size
+    // play_time (ms) = frames_count / (sample_rate (Sec.) / 1000000)
+    // sleep_time (ms) = play_time - elapsed_time
+    int64_t sleep_time = bytes * 1000000LL /
+                             audio_stream_out_frame_size(stream) /
+                             out_get_sample_rate(&stream->common) -
+                         elapsed_time_since_last_write;
+    if (sleep_time > 0) {
+      LOG(VERBOSE) << __func__ << ": sleep " << (sleep_time / 1000)
+                   << " ms when writting FMQ datapath";
+      lock.unlock();
+      usleep(sleep_time);
+      lock.lock();
+    } else {
+      // we don't sleep when we exit standby (this is typical for a real alsa
+      // buffer).
+      sleep_time = 0;
+    }
+    out->last_write_time_us_ = now + sleep_time;
+  }
+  return totalWritten;
+}
+
+static int out_get_render_position(const struct audio_stream_out* stream,
+                                   uint32_t* dsp_frames) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+
+  if (dsp_frames == nullptr) return -EINVAL;
+
+  /* frames = (latency (ms) / 1000) * sample_per_seconds */
+  uint64_t latency_frames =
+      (uint64_t)out_get_latency_ms(stream) * out->sample_rate_ / 1000;
+  if (out->frames_rendered_ >= latency_frames) {
+    *dsp_frames = (uint32_t)(out->frames_rendered_ - latency_frames);
+  } else {
+    *dsp_frames = 0;
+  }
+
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", dsp_frames=" << *dsp_frames;
+  return 0;
+}
+
+static int out_add_audio_effect(const struct audio_stream* stream,
+                                effect_handle_t effect) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", effect=" << effect;
+  return 0;
+}
+
+static int out_remove_audio_effect(const struct audio_stream* stream,
+                                   effect_handle_t effect) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", effect=" << effect;
+  return 0;
+}
+
+static int out_get_next_write_timestamp(const struct audio_stream_out* stream,
+                                        int64_t* timestamp) {
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  *timestamp = 0;
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", timestamp=" << *timestamp;
+  return -EINVAL;
+}
+
+static int out_pause(struct audio_stream_out* stream) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+  int retval = 0;
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", pausing (suspend)";
+  if (out->bluetooth_output_.GetState() == BluetoothStreamState::STARTED) {
+    out->frames_rendered_ = 0;
+    retval = (out->bluetooth_output_.Suspend() ? 0 : -EIO);
+  } else if (out->bluetooth_output_.GetState() ==
+                 BluetoothStreamState::STARTING ||
+             out->bluetooth_output_.GetState() ==
+                 BluetoothStreamState::SUSPENDING) {
+    LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << " NOT ready to pause?!";
+    retval = -EBUSY;
+  } else {
+    LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << " paused already";
+  }
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", pausing (suspend) retval=" << retval;
+
+  return retval;
+}
+
+static int out_resume(struct audio_stream_out* stream) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+  int retval = 0;
+
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", resuming (start)";
+  if (out->bluetooth_output_.GetState() == BluetoothStreamState::STANDBY) {
+    retval = (out->bluetooth_output_.Start() ? 0 : -EIO);
+  } else if (out->bluetooth_output_.GetState() ==
+                 BluetoothStreamState::STARTING ||
+             out->bluetooth_output_.GetState() ==
+                 BluetoothStreamState::SUSPENDING) {
+    LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << " NOT ready to resume?!";
+    retval = -EBUSY;
+  } else if (out->bluetooth_output_.GetState() ==
+             BluetoothStreamState::DISABLED) {
+    LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << " NOT allow to resume?!";
+    retval = -EINVAL;
+  } else {
+    LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << " resumed already";
+  }
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", resuming (start) retval=" << retval;
+
+  return retval;
+}
+
+static int out_get_presentation_position(const struct audio_stream_out* stream,
+                                         uint64_t* frames,
+                                         struct timespec* timestamp) {
+  if (frames == nullptr || timestamp == nullptr) {
+    return -EINVAL;
+  }
+
+  // bytes is the total number of bytes sent by the Bluetooth stack to a
+  // remote headset
+  uint64_t bytes = 0;
+  // delay_report is the audio delay from the remote headset receiving data to
+  // the headset playing sound in units of nanoseconds
+  uint64_t delay_report_ns = 0;
+  const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+
+  if (out->bluetooth_output_.GetPresentationPosition(&delay_report_ns, &bytes,
+                                                     timestamp)) {
+    // assume kMinimumDelayMs (100ms) < delay_report_ns < kMaximumDelayMs
+    // (1000ms), or it is invalid / ignored and use old delay calculated
+    // by ourselves.
+    if (delay_report_ns > kMinimumDelayMs * 1000000 &&
+        delay_report_ns < kMaximumDelayMs * 1000000) {
+      *frames = bytes / audio_stream_out_frame_size(stream);
+      timestamp->tv_nsec += delay_report_ns;
+      if (timestamp->tv_nsec > 1000000000) {
+        timestamp->tv_sec += static_cast<int>(timestamp->tv_nsec / 1000000000);
+        timestamp->tv_nsec %= 1000000000;
+      }
+      LOG(VERBOSE) << __func__
+                   << ": state=" << out->bluetooth_output_.GetState()
+                   << ", frames=" << *frames << " (" << bytes
+                   << " bytes), timestamp=" << timestamp->tv_sec << "."
+                   << android::base::StringPrintf("%09ld", timestamp->tv_nsec)
+                   << "s";
+      return 0;
+    } else if (delay_report_ns >= kMaximumDelayMs * 1000000) {
+      LOG(WARNING) << __func__
+                   << ": state=" << out->bluetooth_output_.GetState()
+                   << ", delay_report=" << delay_report_ns << "ns abnormal";
+    }
+  }
+
+  // default to old delay if any failure is found when fetching from ports
+  if (out->frames_presented_ >= out->frames_count_) {
+    clock_gettime(CLOCK_MONOTONIC, timestamp);
+    *frames = out->frames_presented_ - out->frames_count_;
+    LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+                 << ", frames=" << *frames << " (" << bytes
+                 << " bytes), timestamp=" << timestamp->tv_sec << "."
+                 << android::base::StringPrintf("%09ld", timestamp->tv_nsec)
+                 << "s";
+    return 0;
+  }
+
+  *frames = 0;
+  *timestamp = {};
+  return -EWOULDBLOCK;
+}
+
+static void out_update_source_metadata(
+    struct audio_stream_out* stream,
+    const struct source_metadata* source_metadata) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  std::unique_lock<std::mutex> lock(out->mutex_);
+  if (source_metadata == nullptr || source_metadata->track_count == 0) {
+    return;
+  }
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", " << source_metadata->track_count << " track(s)";
+  out->bluetooth_output_.UpdateMetadata(source_metadata);
+}
+
+static size_t samples_per_ticks(size_t milliseconds, uint32_t sample_rate,
+                                size_t channel_count) {
+  return milliseconds * sample_rate * channel_count / 1000;
+}
+
+int adev_open_output_stream(struct audio_hw_device* dev,
+                            audio_io_handle_t handle, audio_devices_t devices,
+                            audio_output_flags_t flags,
+                            struct audio_config* config,
+                            struct audio_stream_out** stream_out,
+                            const char* address __unused) {
+  *stream_out = nullptr;
+  auto* out = new BluetoothStreamOut;
+  if (!out->bluetooth_output_.SetUp(devices)) {
+    delete out;
+    return -EINVAL;
+  }
+  LOG(VERBOSE) << __func__ << ": device=0x"
+               << android::base::StringPrintf("%08x", devices);
+
+  out->stream_out_.common.get_sample_rate = out_get_sample_rate;
+  out->stream_out_.common.set_sample_rate = out_set_sample_rate;
+  out->stream_out_.common.get_buffer_size = out_get_buffer_size;
+  out->stream_out_.common.get_channels = out_get_channels;
+  out->stream_out_.common.get_format = out_get_format;
+  out->stream_out_.common.set_format = out_set_format;
+  out->stream_out_.common.standby = out_standby;
+  out->stream_out_.common.dump = out_dump;
+  out->stream_out_.common.set_parameters = out_set_parameters;
+  out->stream_out_.common.get_parameters = out_get_parameters;
+  out->stream_out_.common.add_audio_effect = out_add_audio_effect;
+  out->stream_out_.common.remove_audio_effect = out_remove_audio_effect;
+  out->stream_out_.get_latency = out_get_latency_ms;
+  out->stream_out_.set_volume = out_set_volume;
+  out->stream_out_.write = out_write;
+  out->stream_out_.get_render_position = out_get_render_position;
+  out->stream_out_.get_next_write_timestamp = out_get_next_write_timestamp;
+  out->stream_out_.pause = out_pause;
+  out->stream_out_.resume = out_resume;
+  out->stream_out_.get_presentation_position = out_get_presentation_position;
+  out->stream_out_.update_source_metadata = out_update_source_metadata;
+
+  if (!out->bluetooth_output_.LoadAudioConfig(config)) {
+    LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << " failed to get audio config";
+  }
+  out->sample_rate_ = config->sample_rate;
+  out->channel_mask_ = config->channel_mask;
+  out->format_ = config->format;
+  // frame is number of samples per channel
+  out->frames_count_ =
+      samples_per_ticks(kBluetoothDefaultOutputBufferMs, out->sample_rate_, 1);
+  out->frames_rendered_ = 0;
+  out->frames_presented_ = 0;
+
+  *stream_out = &out->stream_out_;
+  LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+            << ", sample_rate=" << out->sample_rate_ << ", channels="
+            << android::base::StringPrintf("%x", out->channel_mask_)
+            << ", format=" << out->format_ << ", frames=" << out->frames_count_;
+  return 0;
+}
+
+void adev_close_output_stream(struct audio_hw_device* dev,
+                              struct audio_stream_out* stream) {
+  auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", stopping";
+  if (out->bluetooth_output_.GetState() != BluetoothStreamState::DISABLED) {
+    out->frames_rendered_ = 0;
+    out->frames_presented_ = 0;
+    out->bluetooth_output_.Stop();
+  }
+  out->bluetooth_output_.TearDown();
+  LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
+               << ", stopped";
+  delete out;
+}
+
+size_t adev_get_input_buffer_size(const struct audio_hw_device* dev,
+                                  const struct audio_config* config) {
+  return 320;
+}
+
+int adev_open_input_stream(struct audio_hw_device* dev,
+                           audio_io_handle_t handle, audio_devices_t devices,
+                           struct audio_config* config,
+                           struct audio_stream_in** stream_in,
+                           audio_input_flags_t flags __unused,
+                           const char* address __unused,
+                           audio_source_t source __unused) {
+  return -EINVAL;
+}
+
+void adev_close_input_stream(struct audio_hw_device* dev,
+                             struct audio_stream_in* stream_in) {}
diff --git a/audio_bluetooth_hw/stream_apis.h b/audio_bluetooth_hw/stream_apis.h
new file mode 100644
index 0000000..14a955c
--- /dev/null
+++ b/audio_bluetooth_hw/stream_apis.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <hardware/audio.h>
+#include <system/audio.h>
+
+#include "device_port_proxy.h"
+
+constexpr unsigned int kBluetoothDefaultSampleRate = 44100;
+constexpr audio_format_t kBluetoothDefaultAudioFormatBitsPerSample =
+    AUDIO_FORMAT_PCM_16_BIT;
+
+constexpr unsigned int kBluetoothDefaultInputBufferMs = 20;
+
+constexpr unsigned int kBluetoothDefaultOutputBufferMs = 10;
+constexpr audio_channel_mask_t kBluetoothDefaultOutputChannelModeMask =
+    AUDIO_CHANNEL_OUT_STEREO;
+
+enum class BluetoothStreamState : uint8_t {
+  DISABLED = 0,  // This stream is closing or set param "suspend=true"
+  STANDBY,
+  STARTING,
+  STARTED,
+  SUSPENDING,
+  UNKNOWN,
+};
+
+std::ostream& operator<<(std::ostream& os, const BluetoothStreamState& state);
+
+struct BluetoothStreamOut {
+  // Must be the first member so it can be cast from audio_stream
+  // or audio_stream_out pointer
+  audio_stream_out stream_out_;
+  ::android::bluetooth::audio::BluetoothAudioPortOut bluetooth_output_;
+  int64_t last_write_time_us_;
+  // Audio PCM Configs
+  uint32_t sample_rate_;
+  audio_channel_mask_t channel_mask_;
+  audio_format_t format_;
+  // frame is the number of samples per channel
+  // frames count per tick
+  size_t frames_count_;
+  // total frames written, reset on standby
+  uint64_t frames_rendered_;
+  // total frames written after opened, never reset
+  uint64_t frames_presented_;
+  mutable std::mutex mutex_;
+};
+
+int adev_open_output_stream(struct audio_hw_device* dev,
+                            audio_io_handle_t handle, audio_devices_t devices,
+                            audio_output_flags_t flags,
+                            struct audio_config* config,
+                            struct audio_stream_out** stream_out,
+                            const char* address __unused);
+
+void adev_close_output_stream(struct audio_hw_device* dev,
+                              struct audio_stream_out* stream);
+
+size_t adev_get_input_buffer_size(const struct audio_hw_device* dev,
+                                  const struct audio_config* config);
+
+int adev_open_input_stream(struct audio_hw_device* dev,
+                           audio_io_handle_t handle, audio_devices_t devices,
+                           struct audio_config* config,
+                           struct audio_stream_in** stream_in,
+                           audio_input_flags_t flags __unused,
+                           const char* address __unused,
+                           audio_source_t source __unused);
+
+void adev_close_input_stream(struct audio_hw_device* dev,
+                             struct audio_stream_in* in);
diff --git a/audio_bluetooth_hw/utils.cc b/audio_bluetooth_hw/utils.cc
new file mode 100644
index 0000000..b3ac7a5
--- /dev/null
+++ b/audio_bluetooth_hw/utils.cc
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "BTAudioHalUtils"
+
+#include "utils.h"
+
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <log/log.h>
+#include <stdlib.h>
+#include <sstream>
+#include <vector>
+
+namespace android {
+namespace bluetooth {
+namespace audio {
+namespace utils {
+
+std::unordered_map<std::string, std::string> ParseAudioParams(
+    const std::string& params) {
+  std::vector<std::string> segments = android::base::Split(params, ";");
+  std::unordered_map<std::string, std::string> params_map;
+  for (const auto& segment : segments) {
+    if (segment.length() == 0) {
+      continue;
+    }
+    std::vector<std::string> kv = android::base::Split(segment, "=");
+    if (kv[0].empty()) {
+      LOG(WARNING) << __func__ << ": Invalid audio parameter " << segment;
+      continue;
+    }
+    params_map[kv[0]] = (kv.size() > 1 ? kv[1] : "");
+  }
+  return params_map;
+}
+
+std::string GetAudioParamString(
+    std::unordered_map<std::string, std::string>& params_map) {
+  std::ostringstream sout;
+  for (const auto& ptr : params_map) {
+    sout << "key: '" << ptr.first << "' value: '" << ptr.second << "'\n";
+  }
+  return sout.str();
+}
+
+}  // namespace utils
+}  // namespace audio
+}  // namespace bluetooth
+}  // namespace android
diff --git a/audio_bluetooth_hw/utils.h b/audio_bluetooth_hw/utils.h
new file mode 100644
index 0000000..817a432
--- /dev/null
+++ b/audio_bluetooth_hw/utils.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <string>
+#include <unordered_map>
+
+namespace android {
+namespace bluetooth {
+namespace audio {
+namespace utils {
+
+// Creates a hash map based on the |params| string containing key and value
+// pairs.  Pairs are expected in the form "key=value" separated by the ';'
+// character.  Both ';' and '=' characters are invalid in keys or values.
+// Examples:
+//   "key0"                      -> map: [key0]=""
+//   "key0=value0;key1=value1;"  -> map: [key0]="value0" [key1]="value1"
+//   "key0=;key1=value1;"        -> map: [key0]="" [key1]="value1"
+//   "=value0;key1=value1;"      -> map: [key1]="value1"
+std::unordered_map<std::string, std::string> ParseAudioParams(
+    const std::string& params);
+
+// Dumps the contents of the hash_map to the log for debugging purposes.
+// If |map| is not NULL, all entries of |map| will be dumped, otherwise
+// nothing will be dumped. Note that this function does not take the ownership
+// of the |map|.
+std::string GetAudioParamString(
+    std::unordered_map<std::string, std::string>& params_map);
+
+}  // namespace utils
+}  // namespace audio
+}  // namespace bluetooth
+}  // namespace android
diff --git a/audio_bluetooth_hw/utils_unittest.cc b/audio_bluetooth_hw/utils_unittest.cc
new file mode 100644
index 0000000..a457797
--- /dev/null
+++ b/audio_bluetooth_hw/utils_unittest.cc
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <unordered_map>
+
+#include "utils.h"
+
+namespace {
+
+using ::android::bluetooth::audio::utils::ParseAudioParams;
+
+class UtilsTest : public testing::Test {
+ protected:
+  virtual void SetUp() {}
+  virtual void TearDown() { map_.clear(); }
+
+  std::unordered_map<std::string, std::string> map_;
+};
+
+TEST_F(UtilsTest, HashMapEmptyParams) {
+  std::string params = "";
+  map_ = ParseAudioParams(params);
+  // map = {}
+  EXPECT_TRUE(map_.empty());
+}
+
+TEST_F(UtilsTest, HashMapDelimitOnly) {
+  std::string params = ";";
+  map_ = ParseAudioParams(params);
+  // map = {}
+  EXPECT_TRUE(map_.empty());
+}
+
+TEST_F(UtilsTest, HashMapNotKeyValuePair) {
+  std::string params = "key0";
+  map_ = ParseAudioParams(params);
+  // map = {[key0]=""}
+  EXPECT_EQ(map_.size(), 1);
+  EXPECT_NE(map_.find("key0"), map_.end());
+  EXPECT_EQ(map_["key0"].length(), 0);
+}
+
+TEST_F(UtilsTest, HashMapEmptyValue) {
+  std::string params = "key0=";
+  map_ = ParseAudioParams(params);
+  // map = {[key0]=""}
+  EXPECT_EQ(map_.size(), 1);
+  EXPECT_NE(map_.find("key0"), map_.end());
+  EXPECT_EQ(map_["key0"].length(), 0);
+}
+
+TEST_F(UtilsTest, HashMapEmptyValueWithDelimit) {
+  std::string params = "key0=;";
+  map_ = ParseAudioParams(params);
+  // map = {[key0]=""}
+  EXPECT_EQ(map_.size(), 1);
+  EXPECT_NE(map_.find("key0"), map_.end());
+  EXPECT_EQ(map_["key0"].length(), 0);
+}
+
+TEST_F(UtilsTest, HashMapOneKeyValuePair) {
+  std::string params = "key0=value0";
+  map_ = ParseAudioParams(params);
+  // map = {[key0]="value0"}
+  EXPECT_EQ(map_.size(), 1);
+  EXPECT_EQ(map_["key0"], "value0");
+}
+
+TEST_F(UtilsTest, HashMapOneKeyValuePairWithDelimit) {
+  std::string params = "key0=value0;";
+  map_ = ParseAudioParams(params);
+  // map = {[key0]="value0"}
+  EXPECT_EQ(map_.size(), 1);
+  EXPECT_EQ(map_["key0"], "value0");
+}
+
+TEST_F(UtilsTest, HashMapTwoKeyValuePairs) {
+  std::string params = "key0=value0;key1=value1";
+  map_ = ParseAudioParams(params);
+  // map = {[key0]="value0", [key1]="value1"}
+  EXPECT_EQ(map_.size(), 2);
+  EXPECT_EQ(map_["key0"], "value0");
+  EXPECT_EQ(map_["key1"], "value1");
+}
+
+TEST_F(UtilsTest, HashMapEmptyKey) {
+  std::string params = "=value";
+  map_ = ParseAudioParams(params);
+  // map = {}
+  EXPECT_TRUE(map_.empty());
+}
+
+TEST_F(UtilsTest, HashMapEmptyKeyWithDelimit) {
+  std::string params = "=value;";
+  map_ = ParseAudioParams(params);
+  // map = {}
+  EXPECT_TRUE(map_.empty());
+}
+
+TEST_F(UtilsTest, HashMapEquivalentOnly) {
+  std::string params = "=";
+  map_ = ParseAudioParams(params);
+  // map = {}
+  EXPECT_TRUE(map_.empty());
+}
+
+TEST_F(UtilsTest, HashMapNoKeyValuePair) {
+  std::string params = "=;";
+  map_ = ParseAudioParams(params);
+  // map = {}
+  EXPECT_TRUE(map_.empty());
+}
+
+TEST_F(UtilsTest, HashMapTwoPairsWithFirstKeyEmpty) {
+  std::string params = "=value0;key1=value1";
+  map_ = ParseAudioParams(params);
+  // map = {[key1]="value1"}
+  EXPECT_EQ(map_.size(), 1);
+  EXPECT_EQ(map_["key1"], "value1");
+}
+
+}  // namespace
diff --git a/test/run_unit_tests.sh b/test/run_unit_tests.sh
index c7ce3aa..a283fa3 100755
--- a/test/run_unit_tests.sh
+++ b/test/run_unit_tests.sh
@@ -1,6 +1,7 @@
 #!/bin/sh
 
 known_tests=(
+  audio_bluetooth_hw_test
   bluetooth_test_common
   bluetoothtbd_test
   net_test_audio_a2dp_hw