[automerger skipped] Updated the vts attestation tests for strongbox implementations which am: 4f4d7d7615 am: 4d4f7cb075 -s ours am: 6e6dcc5640 -s ours am: 228d7844e4 -s ours am: bb0af331ff -s ours am: cf0bc6f988 -s ours am: f728578fa2 -s ours am: 719768442d -s ours
am skip reason: Merged-In Ie3f3f33f773227d879e11f11e2ef0eaee33db648 with SHA-1 7d9bc46f6f is already in history
Original change: https://android-review.googlesource.com/c/platform/hardware/interfaces/+/2963909
Change-Id: Ie7522986010fb777f357cbeba22135e07a0514a9
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
diff --git a/audio/aidl/TEST_MAPPING b/audio/aidl/TEST_MAPPING
index 3e06595..12bce0b 100644
--- a/audio/aidl/TEST_MAPPING
+++ b/audio/aidl/TEST_MAPPING
@@ -4,6 +4,12 @@
"name": "VtsHalAudioCoreTargetTest"
},
{
+ "name": "VtsHalAudioCoreConfigTargetTest"
+ },
+ {
+ "name": "audio_policy_config_xml_converter_tests"
+ },
+ {
"name": "VtsHalAudioEffectFactoryTargetTest"
},
{
diff --git a/audio/aidl/android/hardware/audio/core/stream-in-async-sm.gv b/audio/aidl/android/hardware/audio/core/stream-in-async-sm.gv
index 818b18e..6b69845 100644
--- a/audio/aidl/android/hardware/audio/core/stream-in-async-sm.gv
+++ b/audio/aidl/android/hardware/audio/core/stream-in-async-sm.gv
@@ -14,8 +14,8 @@
// To render: dot -Tpng stream-in-async-sm.gv -o stream-in-async-sm.png
digraph stream_in_async_state_machine {
- node [shape=doublecircle style=filled fillcolor=black width=0.5] I;
- node [shape=point width=0.5] F;
+ node [shape=point style=filled fillcolor=black width=0.5] I;
+ node [shape=doublecircle width=0.5] F;
node [shape=oval width=1];
node [fillcolor=lightgreen] STANDBY; // buffer is empty
node [fillcolor=tomato] CLOSED;
diff --git a/audio/aidl/android/hardware/audio/core/stream-in-sm.gv b/audio/aidl/android/hardware/audio/core/stream-in-sm.gv
index 805dc32..aa7af54 100644
--- a/audio/aidl/android/hardware/audio/core/stream-in-sm.gv
+++ b/audio/aidl/android/hardware/audio/core/stream-in-sm.gv
@@ -14,8 +14,8 @@
// To render: dot -Tpng stream-in-sm.gv -o stream-in-sm.png
digraph stream_in_state_machine {
- node [shape=doublecircle style=filled fillcolor=black width=0.5] I;
- node [shape=point width=0.5] F;
+ node [shape=point style=filled fillcolor=black width=0.5] I;
+ node [shape=doublecircle width=0.5] F;
node [shape=oval width=1];
node [fillcolor=lightgreen] STANDBY; // buffer is empty
node [fillcolor=tomato] CLOSED;
diff --git a/audio/aidl/android/hardware/audio/core/stream-out-async-sm.gv b/audio/aidl/android/hardware/audio/core/stream-out-async-sm.gv
index 501dc01..a3f0de9 100644
--- a/audio/aidl/android/hardware/audio/core/stream-out-async-sm.gv
+++ b/audio/aidl/android/hardware/audio/core/stream-out-async-sm.gv
@@ -14,8 +14,8 @@
// To render: dot -Tpng stream-out-async-sm.gv -o stream-out-async-sm.png
digraph stream_out_async_state_machine {
- node [shape=doublecircle style=filled fillcolor=black width=0.5] I;
- node [shape=point width=0.5] F;
+ node [shape=point style=filled fillcolor=black width=0.5] I;
+ node [shape=doublecircle width=0.5] F;
node [shape=oval width=1];
node [fillcolor=lightgreen] STANDBY; // buffer is empty
node [fillcolor=lightgreen] IDLE; // buffer is empty
diff --git a/audio/aidl/android/hardware/audio/core/stream-out-sm.gv b/audio/aidl/android/hardware/audio/core/stream-out-sm.gv
index 47e7fda..23fb5d9 100644
--- a/audio/aidl/android/hardware/audio/core/stream-out-sm.gv
+++ b/audio/aidl/android/hardware/audio/core/stream-out-sm.gv
@@ -14,8 +14,8 @@
// To render: dot -Tpng stream-out-sm.gv -o stream-out-sm.png
digraph stream_out_state_machine {
- node [shape=doublecircle style=filled fillcolor=black width=0.5] I;
- node [shape=point width=0.5] F;
+ node [shape=point style=filled fillcolor=black width=0.5] I;
+ node [shape=doublecircle width=0.5] F;
node [shape=oval width=1];
node [fillcolor=lightgreen] STANDBY; // buffer is empty
node [fillcolor=lightgreen] IDLE; // buffer is empty
diff --git a/audio/aidl/android/hardware/audio/effect/state.gv b/audio/aidl/android/hardware/audio/effect/state.gv
index c88521e..ce369ba 100644
--- a/audio/aidl/android/hardware/audio/effect/state.gv
+++ b/audio/aidl/android/hardware/audio/effect/state.gv
@@ -25,12 +25,12 @@
I -> INIT[label = "IFactory.createEffect" labelfontcolor = "navy"];
INIT -> F[label = "IFactory.destroyEffect"];
- INIT -> IDLE[label = "open()" labelfontcolor = "lime"];
- IDLE -> PROCESSING[label = "command(START"];
- PROCESSING -> IDLE[label = "command(STOP)\ncommand(RESET)"];
- IDLE -> INIT[label = "close()"];
+ INIT -> IDLE[label = "IEffect.open()" labelfontcolor = "lime"];
+ IDLE -> PROCESSING[label = "IEffect.command(START"];
+ PROCESSING -> IDLE[label = "IEffect.command(STOP)\nIEffect.command(RESET)"];
+ IDLE -> INIT[label = "IEffect.close()"];
- INIT -> INIT[label = "getState\ngetDescriptor"];
- IDLE -> IDLE[label = "getXXX\nsetParameter\ncommand(RESET)"];
- PROCESSING -> PROCESSING[label = "getXXX\nsetParameter"];
+ INIT -> INIT[label = "IEffect.getState\nIEffect.getDescriptor"];
+ IDLE -> IDLE[label = "IEffect.getParameter\nIEffect.setParameter\nIEffect.getDescriptor\nIEffect.command(RESET)"];
+ PROCESSING -> PROCESSING[label = "IEffect.getParameter\nIEffect.setParameter\nIEffect.getDescriptor"];
}
diff --git a/audio/aidl/common/StreamWorker.cpp b/audio/aidl/common/StreamWorker.cpp
index 0d2121c..8107655 100644
--- a/audio/aidl/common/StreamWorker.cpp
+++ b/audio/aidl/common/StreamWorker.cpp
@@ -106,6 +106,9 @@
std::lock_guard<std::mutex> lock(mWorkerLock);
mWorkerState = error.empty() ? WorkerState::RUNNING : WorkerState::STOPPED;
mError = error;
+#if defined(__ANDROID__)
+ mTid = pthread_gettid_np(pthread_self());
+#endif
}
mWorkerCv.notify_one();
if (!error.empty()) return;
diff --git a/audio/aidl/common/include/StreamWorker.h b/audio/aidl/common/include/StreamWorker.h
index e9c1070..efdcc81 100644
--- a/audio/aidl/common/include/StreamWorker.h
+++ b/audio/aidl/common/include/StreamWorker.h
@@ -16,6 +16,8 @@
#pragma once
+#include <sys/types.h>
+
#include <atomic>
#include <condition_variable>
#include <mutex>
@@ -52,6 +54,10 @@
std::lock_guard<std::mutex> lock(mWorkerLock);
return mError;
}
+ pid_t getTid() {
+ std::lock_guard<std::mutex> lock(mWorkerLock);
+ return mTid;
+ }
void stop();
// Direct use of 'join' assumes that the StreamLogic is not intended
// to run forever, and is guaranteed to exit by itself. This normally
@@ -78,6 +84,7 @@
std::condition_variable mWorkerCv;
WorkerState mWorkerState GUARDED_BY(mWorkerLock) = WorkerState::INITIAL;
std::string mError GUARDED_BY(mWorkerLock);
+ pid_t mTid GUARDED_BY(mWorkerLock) = -1;
// The atomic lock-free variable is used to prevent priority inversions
// that can occur when a high priority worker tries to acquire the lock
// which has been taken by a lower priority control thread which in its turn
@@ -143,6 +150,7 @@
void resume() { mThread.resume(); }
bool hasError() { return mThread.hasError(); }
std::string getError() { return mThread.getError(); }
+ pid_t getTid() { return mThread.getTid(); }
void stop() { mThread.stop(); }
void join() { mThread.join(); }
bool waitForAtLeastOneCycle() { return mThread.waitForAtLeastOneCycle(); }
diff --git a/audio/aidl/common/include/Utils.h b/audio/aidl/common/include/Utils.h
index 305c924..3b08de7 100644
--- a/audio/aidl/common/include/Utils.h
+++ b/audio/aidl/common/include/Utils.h
@@ -29,6 +29,21 @@
#include <aidl/android/media/audio/common/AudioMode.h>
#include <aidl/android/media/audio/common/AudioOutputFlags.h>
#include <aidl/android/media/audio/common/PcmType.h>
+#include <android/binder_auto_utils.h>
+
+namespace ndk {
+
+// This enables use of 'error/expected_utils' for ScopedAStatus.
+
+inline bool errorIsOk(const ScopedAStatus& s) {
+ return s.isOk();
+}
+
+inline std::string errorToString(const ScopedAStatus& s) {
+ return s.getDescription();
+}
+
+} // namespace ndk
namespace aidl::android::hardware::audio::common {
@@ -102,7 +117,8 @@
constexpr bool isDefaultAudioFormat(
const ::aidl::android::media::audio::common::AudioFormatDescription& desc) {
return desc.type == ::aidl::android::media::audio::common::AudioFormatType::DEFAULT &&
- desc.pcm == ::aidl::android::media::audio::common::PcmType::DEFAULT;
+ desc.pcm == ::aidl::android::media::audio::common::PcmType::DEFAULT &&
+ desc.encoding.empty();
}
constexpr bool isTelephonyDeviceType(
@@ -111,30 +127,6 @@
device == ::aidl::android::media::audio::common::AudioDeviceType::OUT_TELEPHONY_TX;
}
-constexpr bool isUsbInputDeviceType(::aidl::android::media::audio::common::AudioDeviceType type) {
- switch (type) {
- case ::aidl::android::media::audio::common::AudioDeviceType::IN_DOCK:
- case ::aidl::android::media::audio::common::AudioDeviceType::IN_ACCESSORY:
- case ::aidl::android::media::audio::common::AudioDeviceType::IN_DEVICE:
- case ::aidl::android::media::audio::common::AudioDeviceType::IN_HEADSET:
- return true;
- default:
- return false;
- }
-}
-
-constexpr bool isUsbOutputtDeviceType(::aidl::android::media::audio::common::AudioDeviceType type) {
- switch (type) {
- case ::aidl::android::media::audio::common::AudioDeviceType::OUT_DOCK:
- case ::aidl::android::media::audio::common::AudioDeviceType::OUT_ACCESSORY:
- case ::aidl::android::media::audio::common::AudioDeviceType::OUT_DEVICE:
- case ::aidl::android::media::audio::common::AudioDeviceType::OUT_HEADSET:
- return true;
- default:
- return false;
- }
-}
-
constexpr bool isValidAudioMode(::aidl::android::media::audio::common::AudioMode mode) {
return std::find(kValidAudioModes.begin(), kValidAudioModes.end(), mode) !=
kValidAudioModes.end();
diff --git a/audio/aidl/common/tests/streamworker_tests.cpp b/audio/aidl/common/tests/streamworker_tests.cpp
index f7a30b9..2b65740 100644
--- a/audio/aidl/common/tests/streamworker_tests.cpp
+++ b/audio/aidl/common/tests/streamworker_tests.cpp
@@ -87,6 +87,7 @@
TEST_P(StreamWorkerInvalidTest, Uninitialized) {
EXPECT_FALSE(worker.hasWorkerCycleCalled());
EXPECT_FALSE(worker.hasError());
+ EXPECT_LE(worker.getTid(), 0);
}
TEST_P(StreamWorkerInvalidTest, UninitializedPauseIgnored) {
@@ -105,6 +106,9 @@
EXPECT_FALSE(worker.start());
EXPECT_FALSE(worker.hasWorkerCycleCalled());
EXPECT_TRUE(worker.hasError());
+#if defined(__ANDROID__)
+ EXPECT_GT(worker.getTid(), 0);
+#endif
}
TEST_P(StreamWorkerInvalidTest, PauseIgnored) {
@@ -136,12 +140,16 @@
TEST_P(StreamWorkerTest, Uninitialized) {
EXPECT_FALSE(worker.hasWorkerCycleCalled());
EXPECT_FALSE(worker.hasError());
+ EXPECT_LE(worker.getTid(), 0);
}
TEST_P(StreamWorkerTest, Start) {
ASSERT_TRUE(worker.start());
EXPECT_TRUE(worker.waitForAtLeastOneCycle());
EXPECT_FALSE(worker.hasError());
+#if defined(__ANDROID__)
+ EXPECT_GT(worker.getTid(), 0);
+#endif
}
TEST_P(StreamWorkerTest, StartStop) {
diff --git a/audio/aidl/default/AidlConversionXsdc.cpp b/audio/aidl/default/AidlConversionXsdc.cpp
new file mode 100644
index 0000000..c404d67
--- /dev/null
+++ b/audio/aidl/default/AidlConversionXsdc.cpp
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2023 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 "AHAL_AidlXsdc"
+#include <android-base/logging.h>
+#include <error/expected_utils.h>
+#include <media/AidlConversionCppNdk.h>
+#include <media/TypeConverter.h>
+
+#include "core-impl/AidlConversionXsdc.h"
+
+using aidl::android::media::audio::common::AudioFormatDescription;
+
+namespace xsd = android::audio::policy::configuration;
+
+namespace aidl::android::hardware::audio::core::internal {
+
+ConversionResult<AudioFormatDescription> xsdc2aidl_AudioFormatDescription(const std::string& xsdc) {
+ return legacy2aidl_audio_format_t_AudioFormatDescription(::android::formatFromString(xsdc));
+}
+
+ConversionResult<SurroundSoundConfig::SurroundFormatFamily> xsdc2aidl_SurroundFormatFamily(
+ const ::xsd::SurroundFormats::Format& xsdc) {
+ SurroundSoundConfig::SurroundFormatFamily aidl;
+ aidl.primaryFormat = VALUE_OR_RETURN(xsdc2aidl_AudioFormatDescription(xsdc.getName()));
+ if (xsdc.hasSubformats()) {
+ aidl.subFormats = VALUE_OR_RETURN(convertContainer<std::vector<AudioFormatDescription>>(
+ xsdc.getSubformats(), xsdc2aidl_AudioFormatDescription));
+ }
+ return aidl;
+}
+
+ConversionResult<SurroundSoundConfig> xsdc2aidl_SurroundSoundConfig(
+ const ::xsd::SurroundSound& xsdc) {
+ SurroundSoundConfig aidl;
+ if (!xsdc.hasFormats() || !xsdc.getFirstFormats()->hasFormat()) return aidl;
+ aidl.formatFamilies = VALUE_OR_RETURN(
+ convertContainer<std::vector<SurroundSoundConfig::SurroundFormatFamily>>(
+ xsdc.getFirstFormats()->getFormat(), xsdc2aidl_SurroundFormatFamily));
+ return aidl;
+}
+
+} // namespace aidl::android::hardware::audio::core::internal
diff --git a/audio/aidl/default/Android.bp b/audio/aidl/default/Android.bp
index c9edae0..bb8d76f 100644
--- a/audio/aidl/default/Android.bp
+++ b/audio/aidl/default/Android.bp
@@ -18,6 +18,7 @@
"libbinder_ndk",
"libcutils",
"libfmq",
+ "libnbaio_mono",
"libstagefright_foundation",
"libtinyalsav2",
"libutils",
@@ -65,20 +66,35 @@
],
export_include_dirs: ["include"],
srcs: [
+ "AidlConversionXsdc.cpp",
"AudioPolicyConfigXmlConverter.cpp",
"Bluetooth.cpp",
"Config.cpp",
"Configuration.cpp",
"EngineConfigXmlConverter.cpp",
"Module.cpp",
+ "ModulePrimary.cpp",
"SoundDose.cpp",
"Stream.cpp",
- "StreamStub.cpp",
+ "StreamSwitcher.cpp",
"Telephony.cpp",
+ "alsa/Mixer.cpp",
+ "alsa/ModuleAlsa.cpp",
+ "alsa/StreamAlsa.cpp",
+ "alsa/Utils.cpp",
+ "bluetooth/DevicePortProxy.cpp",
+ "bluetooth/ModuleBluetooth.cpp",
+ "bluetooth/StreamBluetooth.cpp",
+ "primary/PrimaryMixer.cpp",
+ "primary/StreamPrimary.cpp",
+ "r_submix/ModuleRemoteSubmix.cpp",
+ "r_submix/SubmixRoute.cpp",
+ "r_submix/StreamRemoteSubmix.cpp",
+ "stub/ModuleStub.cpp",
+ "stub/StreamStub.cpp",
"usb/ModuleUsb.cpp",
"usb/StreamUsb.cpp",
"usb/UsbAlsaMixerControl.cpp",
- "usb/UsbAlsaUtils.cpp",
],
generated_sources: [
"audio_policy_configuration_aidl_default",
@@ -92,6 +108,23 @@
"audio_policy_configuration_aidl_default",
"audio_policy_engine_configuration_aidl_default",
],
+ shared_libs: [
+ "android.hardware.bluetooth.audio-V3-ndk",
+ "libaudio_aidl_conversion_common_ndk",
+ "libbluetooth_audio_session_aidl",
+ "libmedia_helper",
+ "libstagefright_foundation",
+ ],
+ export_shared_lib_headers: [
+ "libaudio_aidl_conversion_common_ndk",
+ ],
+ cflags: [
+ "-Wall",
+ "-Wextra",
+ "-Werror",
+ "-Wthread-safety",
+ "-DBACKEND_NDK",
+ ],
}
cc_binary {
@@ -108,7 +141,65 @@
static_libs: [
"libaudioserviceexampleimpl",
],
+ shared_libs: [
+ "android.hardware.bluetooth.audio-V3-ndk",
+ "libaudio_aidl_conversion_common_ndk",
+ "libbluetooth_audio_session_aidl",
+ "libmedia_helper",
+ "libstagefright_foundation",
+ ],
srcs: ["main.cpp"],
+ cflags: [
+ "-Wall",
+ "-Wextra",
+ "-Werror",
+ "-Wthread-safety",
+ "-DBACKEND_NDK",
+ ],
+}
+
+cc_test {
+ name: "audio_policy_config_xml_converter_tests",
+ vendor_available: true,
+ defaults: [
+ "latest_android_media_audio_common_types_ndk_static",
+ "latest_android_hardware_audio_core_ndk_static",
+ ],
+ shared_libs: [
+ "libaudio_aidl_conversion_common_ndk",
+ "libaudioaidlcommon",
+ "libaudioutils",
+ "libbase",
+ "libbinder_ndk",
+ "libcutils",
+ "libmedia_helper",
+ "libstagefright_foundation",
+ "libutils",
+ "libxml2",
+ ],
+ header_libs: [
+ "libaudio_system_headers",
+ "libaudioaidl_headers",
+ "libxsdc-utils",
+ ],
+ generated_sources: [
+ "audio_policy_configuration_aidl_default",
+ ],
+ generated_headers: [
+ "audio_policy_configuration_aidl_default",
+ ],
+ srcs: [
+ "AudioPolicyConfigXmlConverter.cpp",
+ "tests/AudioPolicyConfigXmlConverterTest.cpp",
+ ],
+ cflags: [
+ "-Wall",
+ "-Wextra",
+ "-Werror",
+ "-Wthread-safety",
+ "-DBACKEND_NDK",
+ ],
+ test_suites: ["general-tests"],
}
cc_defaults {
diff --git a/audio/aidl/default/AudioPolicyConfigXmlConverter.cpp b/audio/aidl/default/AudioPolicyConfigXmlConverter.cpp
index 6290912..7452c8e 100644
--- a/audio/aidl/default/AudioPolicyConfigXmlConverter.cpp
+++ b/audio/aidl/default/AudioPolicyConfigXmlConverter.cpp
@@ -21,11 +21,17 @@
#include <functional>
#include <unordered_map>
+#define LOG_TAG "AHAL_ApmXmlConverter"
+#include <android-base/logging.h>
+
#include <aidl/android/media/audio/common/AudioHalEngineConfig.h>
+#include <media/stagefright/foundation/MediaDefs.h>
#include <system/audio-base-utils.h>
+#include "core-impl/AidlConversionXsdc.h"
#include "core-impl/AudioPolicyConfigXmlConverter.h"
+using aidl::android::media::audio::common::AudioFormatDescription;
using aidl::android::media::audio::common::AudioHalEngineConfig;
using aidl::android::media::audio::common::AudioHalVolumeCurve;
using aidl::android::media::audio::common::AudioHalVolumeGroup;
@@ -68,13 +74,13 @@
getXsdcConfig()->getVolumes());
}
aidlVolumeCurve.curvePoints =
- convertCollectionToAidl<std::string, AudioHalVolumeCurve::CurvePoint>(
+ convertCollectionToAidlUnchecked<std::string, AudioHalVolumeCurve::CurvePoint>(
mVolumesReferenceMap.at(xsdcVolumeCurve.getRef()).getPoint(),
std::bind(&AudioPolicyConfigXmlConverter::convertCurvePointToAidl, this,
std::placeholders::_1));
} else {
aidlVolumeCurve.curvePoints =
- convertCollectionToAidl<std::string, AudioHalVolumeCurve::CurvePoint>(
+ convertCollectionToAidlUnchecked<std::string, AudioHalVolumeCurve::CurvePoint>(
xsdcVolumeCurve.getPoint(),
std::bind(&AudioPolicyConfigXmlConverter::convertCurvePointToAidl, this,
std::placeholders::_1));
@@ -87,6 +93,22 @@
convertVolumeCurveToAidl(xsdcVolumeCurve));
}
+const SurroundSoundConfig& AudioPolicyConfigXmlConverter::getSurroundSoundConfig() {
+ static const SurroundSoundConfig aidlSurroundSoundConfig = [this]() {
+ if (auto xsdcConfig = getXsdcConfig(); xsdcConfig && xsdcConfig->hasSurroundSound()) {
+ auto configConv = xsdc2aidl_SurroundSoundConfig(*xsdcConfig->getFirstSurroundSound());
+ if (configConv.ok()) {
+ return configConv.value();
+ }
+ LOG(ERROR) << "There was an error converting surround formats to AIDL: "
+ << configConv.error();
+ }
+ LOG(WARNING) << "Audio policy config does not have <surroundSound> section, using default";
+ return getDefaultSurroundSoundConfig();
+ }();
+ return aidlSurroundSoundConfig;
+}
+
const AudioHalEngineConfig& AudioPolicyConfigXmlConverter::getAidlEngineConfig() {
if (mAidlEngineConfig.volumeGroups.empty() && getXsdcConfig() &&
getXsdcConfig()->hasVolumes()) {
@@ -95,6 +117,47 @@
return mAidlEngineConfig;
}
+// static
+const SurroundSoundConfig& AudioPolicyConfigXmlConverter::getDefaultSurroundSoundConfig() {
+ // Provide a config similar to the one used by the framework by default
+ // (see AudioPolicyConfig::setDefaultSurroundFormats).
+#define ENCODED_FORMAT(format) \
+ AudioFormatDescription { \
+ .encoding = ::android::format \
+ }
+#define SIMPLE_FORMAT(format) \
+ SurroundSoundConfig::SurroundFormatFamily { \
+ .primaryFormat = ENCODED_FORMAT(format) \
+ }
+
+ static const SurroundSoundConfig defaultConfig = {
+ .formatFamilies = {
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_AC3),
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_EAC3),
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_DTS),
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_DTS_HD),
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_DTS_HD_MA),
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_DTS_UHD_P1),
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_DTS_UHD_P2),
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_DOLBY_TRUEHD),
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_EAC3_JOC),
+ SurroundSoundConfig::SurroundFormatFamily{
+ .primaryFormat = ENCODED_FORMAT(MEDIA_MIMETYPE_AUDIO_AAC_LC),
+ .subFormats =
+ {
+ ENCODED_FORMAT(MEDIA_MIMETYPE_AUDIO_AAC_HE_V1),
+ ENCODED_FORMAT(MEDIA_MIMETYPE_AUDIO_AAC_HE_V2),
+ ENCODED_FORMAT(MEDIA_MIMETYPE_AUDIO_AAC_ELD),
+ ENCODED_FORMAT(MEDIA_MIMETYPE_AUDIO_AAC_XHE),
+ }},
+ SIMPLE_FORMAT(MEDIA_MIMETYPE_AUDIO_AC4),
+ }};
+#undef SIMPLE_FORMAT
+#undef ENCODED_FORMAT
+
+ return defaultConfig;
+}
+
void AudioPolicyConfigXmlConverter::mapStreamsToVolumeCurves() {
if (getXsdcConfig()->hasVolumes()) {
for (const xsd::Volumes& xsdcWrapperType : getXsdcConfig()->getVolumes()) {
diff --git a/audio/aidl/default/Bluetooth.cpp b/audio/aidl/default/Bluetooth.cpp
index c32b538..072b89f 100644
--- a/audio/aidl/default/Bluetooth.cpp
+++ b/audio/aidl/default/Bluetooth.cpp
@@ -82,19 +82,18 @@
ndk::ScopedAStatus BluetoothA2dp::isEnabled(bool* _aidl_return) {
*_aidl_return = mEnabled;
- LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus BluetoothA2dp::setEnabled(bool in_enabled) {
mEnabled = in_enabled;
LOG(DEBUG) << __func__ << ": " << mEnabled;
+ if (mHandler) return mHandler();
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus BluetoothA2dp::supportsOffloadReconfiguration(bool* _aidl_return) {
- *_aidl_return = true;
- LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
+ *_aidl_return = false;
return ndk::ScopedAStatus::ok();
}
@@ -102,24 +101,22 @@
const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& in_parameters
__unused) {
LOG(DEBUG) << __func__ << ": " << ::android::internal::ToString(in_parameters);
- return ndk::ScopedAStatus::ok();
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
ndk::ScopedAStatus BluetoothLe::isEnabled(bool* _aidl_return) {
*_aidl_return = mEnabled;
- LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus BluetoothLe::setEnabled(bool in_enabled) {
mEnabled = in_enabled;
- LOG(DEBUG) << __func__ << ": " << mEnabled;
+ if (mHandler) return mHandler();
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus BluetoothLe::supportsOffloadReconfiguration(bool* _aidl_return) {
- *_aidl_return = true;
- LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
+ *_aidl_return = false;
return ndk::ScopedAStatus::ok();
}
@@ -127,7 +124,7 @@
const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& in_parameters
__unused) {
LOG(DEBUG) << __func__ << ": " << ::android::internal::ToString(in_parameters);
- return ndk::ScopedAStatus::ok();
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/Config.cpp b/audio/aidl/default/Config.cpp
index 87c0ace..308200a 100644
--- a/audio/aidl/default/Config.cpp
+++ b/audio/aidl/default/Config.cpp
@@ -27,30 +27,41 @@
namespace aidl::android::hardware::audio::core {
ndk::ScopedAStatus Config::getSurroundSoundConfig(SurroundSoundConfig* _aidl_return) {
- SurroundSoundConfig surroundSoundConfig;
- // TODO: parse from XML; for now, use empty config as default
- *_aidl_return = std::move(surroundSoundConfig);
+ static const auto& func = __func__;
+ static const SurroundSoundConfig surroundSoundConfig = [this]() {
+ SurroundSoundConfig surroundCfg = mAudioPolicyConverter.getSurroundSoundConfig();
+ if (mAudioPolicyConverter.getStatus() != ::android::OK) {
+ LOG(WARNING) << func << ": " << mAudioPolicyConverter.getError();
+ }
+ return surroundCfg;
+ }();
+ *_aidl_return = surroundSoundConfig;
LOG(DEBUG) << __func__ << ": returning " << _aidl_return->toString();
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus Config::getEngineConfig(AudioHalEngineConfig* _aidl_return) {
+ static const auto& func = __func__;
static const AudioHalEngineConfig returnEngCfg = [this]() {
AudioHalEngineConfig engConfig;
if (mEngConfigConverter.getStatus() == ::android::OK) {
engConfig = mEngConfigConverter.getAidlEngineConfig();
} else {
- LOG(INFO) << __func__ << mEngConfigConverter.getError();
+ LOG(INFO) << func << ": " << mEngConfigConverter.getError();
if (mAudioPolicyConverter.getStatus() == ::android::OK) {
engConfig = mAudioPolicyConverter.getAidlEngineConfig();
} else {
- LOG(WARNING) << __func__ << mAudioPolicyConverter.getError();
+ LOG(WARNING) << func << ": " << mAudioPolicyConverter.getError();
}
}
+ // Logging full contents of the config is an overkill, just provide statistics.
+ LOG(DEBUG) << func
+ << ": number of strategies parsed: " << engConfig.productStrategies.size()
+ << ", default strategy: " << engConfig.defaultProductStrategyId
+ << ", number of volume groups parsed: " << engConfig.volumeGroups.size();
return engConfig;
}();
*_aidl_return = returnEngCfg;
- LOG(DEBUG) << __func__ << ": returning " << _aidl_return->toString();
return ndk::ScopedAStatus::ok();
}
} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/Configuration.cpp b/audio/aidl/default/Configuration.cpp
index e1e1f79..b9f1131 100644
--- a/audio/aidl/default/Configuration.cpp
+++ b/audio/aidl/default/Configuration.cpp
@@ -134,7 +134,7 @@
// Device ports:
// * "Speaker", OUT_SPEAKER, default
// - no profiles specified
-// * "Built-in Mic", IN_MICROPHONE, default
+// * "Built-In Mic", IN_MICROPHONE, default
// - no profiles specified
// * "Telephony Tx", OUT_TELEPHONY_TX
// - no profiles specified
@@ -142,63 +142,39 @@
// - no profiles specified
// * "FM Tuner", IN_FM_TUNER
// - no profiles specified
-// * "USB Out", OUT_DEVICE, CONNECTION_USB
-// - no profiles specified
-// * "USB In", IN_DEVICE, CONNECTION_USB
-// - no profiles specified
//
// Mix ports:
// * "primary output", PRIMARY, 1 max open, 1 max active stream
// - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-// - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-// * "compressed offload", DIRECT|COMPRESS_OFFLOAD|NON_BLOCKING, 1 max open, 1 max active stream
-// - profile MP3; MONO, STEREO; 44100, 48000
-// * "primary input", 2 max open, 2 max active streams
-// - profile PCM 16-bit; MONO, STEREO, FRONT_BACK;
-// 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000
-// - profile PCM 24-bit; MONO, STEREO, FRONT_BACK;
-// 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000
+// * "primary input", 1 max open, 1 max active stream
+// - profile PCM 16-bit; MONO, STEREO;
+// 8000, 11025, 16000, 32000, 44100, 48000
// * "telephony_tx", 1 max open, 1 max active stream
// - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-// - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
// * "telephony_rx", 1 max open, 1 max active stream
// - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-// - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
// * "fm_tuner", 1 max open, 1 max active stream
// - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-// - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
//
// Routes:
-// "primary out", "compressed offload" -> "Speaker"
-// "primary out", "compressed offload" -> "USB Out"
-// "Built-in Mic", "USB In" -> "primary input"
-// "telephony_tx" -> "Telephony Tx"
+// "primary out" -> "Speaker"
+// "Built-In Mic" -> "primary input"
// "Telephony Rx" -> "telephony_rx"
+// "telephony_tx" -> "Telephony Tx"
// "FM Tuner" -> "fm_tuner"
//
// Initial port configs:
-// * "Speaker" device port: PCM 24-bit; STEREO; 48000
-// * "Built-in Mic" device port: PCM 24-bit; MONO; 48000
-// * "Telephony Tx" device port: PCM 24-bit; MONO; 48000
-// * "Telephony Rx" device port: PCM 24-bit; MONO; 48000
-// * "FM Tuner" device port: PCM 24-bit; STEREO; 48000
-//
-// Profiles for device port connected state:
-// * USB Out":
-// - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-// - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-// * USB In":
-// - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
-// - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
+// * "Speaker" device port: PCM 16-bit; STEREO; 48000
+// * "Built-In Mic" device port: PCM 16-bit; MONO; 48000
+// * "Telephony Tx" device port: PCM 16-bit; MONO; 48000
+// * "Telephony Rx" device port: PCM 16-bit; MONO; 48000
+// * "FM Tuner" device port: PCM 16-bit; STEREO; 48000
//
std::unique_ptr<Configuration> getPrimaryConfiguration() {
static const Configuration configuration = []() {
const std::vector<AudioProfile> standardPcmAudioProfiles = {
createProfile(PcmType::INT_16_BIT,
{AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
- {8000, 11025, 16000, 32000, 44100, 48000}),
- createProfile(PcmType::INT_24_BIT,
- {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
{8000, 11025, 16000, 32000, 44100, 48000})};
Configuration c;
@@ -210,17 +186,17 @@
1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE));
c.ports.push_back(speakerOutDevice);
c.initialConfigs.push_back(
- createPortConfig(speakerOutDevice.id, speakerOutDevice.id, PcmType::INT_24_BIT,
+ createPortConfig(speakerOutDevice.id, speakerOutDevice.id, PcmType::INT_16_BIT,
AudioChannelLayout::LAYOUT_STEREO, 48000, 0, false,
createDeviceExt(AudioDeviceType::OUT_SPEAKER, 0)));
AudioPort micInDevice =
- createPort(c.nextPortId++, "Built-in Mic", 0, true,
+ createPort(c.nextPortId++, "Built-In Mic", 0, true,
createDeviceExt(AudioDeviceType::IN_MICROPHONE,
1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE));
c.ports.push_back(micInDevice);
c.initialConfigs.push_back(
- createPortConfig(micInDevice.id, micInDevice.id, PcmType::INT_24_BIT,
+ createPortConfig(micInDevice.id, micInDevice.id, PcmType::INT_16_BIT,
AudioChannelLayout::LAYOUT_MONO, 48000, 0, true,
createDeviceExt(AudioDeviceType::IN_MICROPHONE, 0)));
@@ -230,7 +206,7 @@
c.ports.push_back(telephonyTxOutDevice);
c.initialConfigs.push_back(
createPortConfig(telephonyTxOutDevice.id, telephonyTxOutDevice.id,
- PcmType::INT_24_BIT, AudioChannelLayout::LAYOUT_MONO, 48000, 0,
+ PcmType::INT_16_BIT, AudioChannelLayout::LAYOUT_MONO, 48000, 0,
false, createDeviceExt(AudioDeviceType::OUT_TELEPHONY_TX, 0)));
AudioPort telephonyRxInDevice =
@@ -239,64 +215,33 @@
c.ports.push_back(telephonyRxInDevice);
c.initialConfigs.push_back(
createPortConfig(telephonyRxInDevice.id, telephonyRxInDevice.id,
- PcmType::INT_24_BIT, AudioChannelLayout::LAYOUT_MONO, 48000, 0,
+ PcmType::INT_16_BIT, AudioChannelLayout::LAYOUT_MONO, 48000, 0,
true, createDeviceExt(AudioDeviceType::IN_TELEPHONY_RX, 0)));
AudioPort fmTunerInDevice = createPort(c.nextPortId++, "FM Tuner", 0, true,
createDeviceExt(AudioDeviceType::IN_FM_TUNER, 0));
c.ports.push_back(fmTunerInDevice);
c.initialConfigs.push_back(
- createPortConfig(fmTunerInDevice.id, fmTunerInDevice.id, PcmType::INT_24_BIT,
+ createPortConfig(fmTunerInDevice.id, fmTunerInDevice.id, PcmType::INT_16_BIT,
AudioChannelLayout::LAYOUT_STEREO, 48000, 0, true,
createDeviceExt(AudioDeviceType::IN_FM_TUNER, 0)));
- AudioPort usbOutDevice =
- createPort(c.nextPortId++, "USB Out", 0, false,
- createDeviceExt(AudioDeviceType::OUT_DEVICE, 0,
- AudioDeviceDescription::CONNECTION_USB));
- c.ports.push_back(usbOutDevice);
- c.connectedProfiles[usbOutDevice.id] = standardPcmAudioProfiles;
-
- AudioPort usbInDevice = createPort(c.nextPortId++, "USB In", 0, true,
- createDeviceExt(AudioDeviceType::IN_DEVICE, 0,
- AudioDeviceDescription::CONNECTION_USB));
- c.ports.push_back(usbInDevice);
- c.connectedProfiles[usbInDevice.id] = standardPcmAudioProfiles;
-
// Mix ports
AudioPort primaryOutMix = createPort(c.nextPortId++, "primary output",
makeBitPositionFlagMask(AudioOutputFlags::PRIMARY),
- false, createPortMixExt(1, 1));
+ false, createPortMixExt(0, 0));
primaryOutMix.profiles.insert(primaryOutMix.profiles.begin(),
standardPcmAudioProfiles.begin(),
standardPcmAudioProfiles.end());
c.ports.push_back(primaryOutMix);
- AudioPort compressedOffloadOutMix =
- createPort(c.nextPortId++, "compressed offload",
- makeBitPositionFlagMask({AudioOutputFlags::DIRECT,
- AudioOutputFlags::COMPRESS_OFFLOAD,
- AudioOutputFlags::NON_BLOCKING}),
- false, createPortMixExt(1, 1));
- compressedOffloadOutMix.profiles.push_back(
- createProfile(::android::MEDIA_MIMETYPE_AUDIO_MPEG,
- {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
- {44100, 48000}));
- c.ports.push_back(compressedOffloadOutMix);
-
AudioPort primaryInMix =
- createPort(c.nextPortId++, "primary input", 0, true, createPortMixExt(2, 2));
+ createPort(c.nextPortId++, "primary input", 0, true, createPortMixExt(0, 0));
primaryInMix.profiles.push_back(
createProfile(PcmType::INT_16_BIT,
- {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO,
- AudioChannelLayout::LAYOUT_FRONT_BACK},
- {8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000}));
- primaryInMix.profiles.push_back(
- createProfile(PcmType::INT_24_BIT,
- {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO,
- AudioChannelLayout::LAYOUT_FRONT_BACK},
- {8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000}));
+ {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
+ {8000, 11025, 16000, 32000, 44100, 48000}));
c.ports.push_back(primaryInMix);
AudioPort telephonyTxOutMix =
@@ -320,11 +265,10 @@
standardPcmAudioProfiles.end());
c.ports.push_back(fmTunerInMix);
- c.routes.push_back(createRoute({primaryOutMix, compressedOffloadOutMix}, speakerOutDevice));
- c.routes.push_back(createRoute({primaryOutMix, compressedOffloadOutMix}, usbOutDevice));
- c.routes.push_back(createRoute({micInDevice, usbInDevice}, primaryInMix));
- c.routes.push_back(createRoute({telephonyTxOutMix}, telephonyTxOutDevice));
+ c.routes.push_back(createRoute({primaryOutMix}, speakerOutDevice));
+ c.routes.push_back(createRoute({micInDevice}, primaryInMix));
c.routes.push_back(createRoute({telephonyRxInDevice}, telephonyRxInMix));
+ c.routes.push_back(createRoute({telephonyTxOutMix}, telephonyTxOutDevice));
c.routes.push_back(createRoute({fmTunerInDevice}, fmTunerInMix));
c.portConfigs.insert(c.portConfigs.end(), c.initialConfigs.begin(), c.initialConfigs.end());
@@ -345,15 +289,21 @@
//
// Device ports:
// * "Remote Submix Out", OUT_SUBMIX
-// - profile PCM 24-bit; STEREO; 48000
+// - no profiles specified
// * "Remote Submix In", IN_SUBMIX
-// - profile PCM 24-bit; STEREO; 48000
+// - no profiles specified
//
// Mix ports:
-// * "r_submix output", stream count unlimited
-// - profile PCM 24-bit; STEREO; 48000
-// * "r_submix input", stream count unlimited
-// - profile PCM 24-bit; STEREO; 48000
+// * "r_submix output", unlimited max open, unlimited max active stream
+// - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
+// - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
+// - profile PCM 32-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
+// - profile PCM 32-bit float; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
+// * "r_submix input", unlimited max open, unlimited max active stream
+// - profile PCM 16-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
+// - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
+// - profile PCM 32-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
+// - profile PCM 32-bit float; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
//
// Routes:
// "r_submix output" -> "Remote Submix Out"
@@ -362,33 +312,46 @@
std::unique_ptr<Configuration> getRSubmixConfiguration() {
static const Configuration configuration = []() {
Configuration c;
+ const std::vector<AudioProfile> standardPcmAudioProfiles{
+ createProfile(PcmType::FLOAT_32_BIT,
+ {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
+ {8000, 11025, 16000, 32000, 44100, 48000}),
+ createProfile(PcmType::INT_32_BIT,
+ {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
+ {8000, 11025, 16000, 32000, 44100, 48000}),
+ createProfile(PcmType::INT_24_BIT,
+ {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
+ {8000, 11025, 16000, 32000, 44100, 48000}),
+ createProfile(PcmType::INT_16_BIT,
+ {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
+ {8000, 11025, 16000, 32000, 44100, 48000})};
// Device ports
- AudioPort rsubmixOutDevice = createPort(c.nextPortId++, "Remote Submix Out", 0, false,
- createDeviceExt(AudioDeviceType::OUT_SUBMIX, 0));
- rsubmixOutDevice.profiles.push_back(
- createProfile(PcmType::INT_24_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {48000}));
+ AudioPort rsubmixOutDevice =
+ createPort(c.nextPortId++, "Remote Submix Out", 0, false,
+ createDeviceExt(AudioDeviceType::OUT_SUBMIX, 0,
+ AudioDeviceDescription::CONNECTION_VIRTUAL));
c.ports.push_back(rsubmixOutDevice);
+ c.connectedProfiles[rsubmixOutDevice.id] = standardPcmAudioProfiles;
- AudioPort rsubmixInDevice = createPort(c.nextPortId++, "Remote Submix In", 0, true,
- createDeviceExt(AudioDeviceType::IN_SUBMIX, 0));
- rsubmixInDevice.profiles.push_back(
- createProfile(PcmType::INT_24_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {48000}));
+ AudioPort rsubmixInDevice =
+ createPort(c.nextPortId++, "Remote Submix In", 0, true,
+ createDeviceExt(AudioDeviceType::IN_SUBMIX, 0,
+ AudioDeviceDescription::CONNECTION_VIRTUAL));
c.ports.push_back(rsubmixInDevice);
+ c.connectedProfiles[rsubmixInDevice.id] = standardPcmAudioProfiles;
// Mix ports
AudioPort rsubmixOutMix =
createPort(c.nextPortId++, "r_submix output", 0, false, createPortMixExt(0, 0));
- rsubmixOutMix.profiles.push_back(
- createProfile(PcmType::INT_24_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {48000}));
+ rsubmixOutMix.profiles = standardPcmAudioProfiles;
c.ports.push_back(rsubmixOutMix);
AudioPort rsubmixInMix =
createPort(c.nextPortId++, "r_submix input", 0, true, createPortMixExt(0, 0));
- rsubmixInMix.profiles.push_back(
- createProfile(PcmType::INT_24_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {48000}));
+ rsubmixInMix.profiles = standardPcmAudioProfiles;
c.ports.push_back(rsubmixInMix);
c.routes.push_back(createRoute({rsubmixOutMix}, rsubmixOutDevice));
@@ -402,22 +365,31 @@
// Usb configuration:
//
// Device ports:
+// * "USB Device Out", OUT_DEVICE, CONNECTION_USB
+// - no profiles specified
// * "USB Headset Out", OUT_HEADSET, CONNECTION_USB
// - no profiles specified
+// * "USB Device In", IN_DEVICE, CONNECTION_USB
+// - no profiles specified
// * "USB Headset In", IN_HEADSET, CONNECTION_USB
// - no profiles specified
//
// Mix ports:
-// * "usb_headset output", 1 max open, 1 max active stream
+// * "usb_device output", 1 max open, 1 max active stream
// - no profiles specified
-// * "usb_headset input", 1 max open, 1 max active stream
+// * "usb_device input", 1 max open, 1 max active stream
// - no profiles specified
//
+// Routes:
+// * "usb_device output" -> "USB Device Out"
+// * "usb_device output" -> "USB Headset Out"
+// * "USB Device In", "USB Headset In" -> "usb_device input"
+//
// Profiles for device port connected state:
-// * USB Headset Out":
+// * "USB Device Out", "USB Headset Out":
// - profile PCM 16-bit; MONO, STEREO, INDEX_MASK_1, INDEX_MASK_2; 44100, 48000
// - profile PCM 24-bit; MONO, STEREO, INDEX_MASK_1, INDEX_MASK_2; 44100, 48000
-// * USB Headset In":
+// * "USB Device In", "USB Headset In":
// - profile PCM 16-bit; MONO, STEREO, INDEX_MASK_1, INDEX_MASK_2; 44100, 48000
// - profile PCM 24-bit; MONO, STEREO, INDEX_MASK_1, INDEX_MASK_2; 44100, 48000
//
@@ -436,6 +408,13 @@
// Device ports
+ AudioPort usbOutDevice =
+ createPort(c.nextPortId++, "USB Device Out", 0, false,
+ createDeviceExt(AudioDeviceType::OUT_DEVICE, 0,
+ AudioDeviceDescription::CONNECTION_USB));
+ c.ports.push_back(usbOutDevice);
+ c.connectedProfiles[usbOutDevice.id] = standardPcmAudioProfiles;
+
AudioPort usbOutHeadset =
createPort(c.nextPortId++, "USB Headset Out", 0, false,
createDeviceExt(AudioDeviceType::OUT_HEADSET, 0,
@@ -443,6 +422,12 @@
c.ports.push_back(usbOutHeadset);
c.connectedProfiles[usbOutHeadset.id] = standardPcmAudioProfiles;
+ AudioPort usbInDevice = createPort(c.nextPortId++, "USB Device In", 0, true,
+ createDeviceExt(AudioDeviceType::IN_DEVICE, 0,
+ AudioDeviceDescription::CONNECTION_USB));
+ c.ports.push_back(usbInDevice);
+ c.connectedProfiles[usbInDevice.id] = standardPcmAudioProfiles;
+
AudioPort usbInHeadset =
createPort(c.nextPortId++, "USB Headset In", 0, true,
createDeviceExt(AudioDeviceType::IN_HEADSET, 0,
@@ -452,16 +437,233 @@
// Mix ports
- AudioPort usbHeadsetOutMix =
- createPort(c.nextPortId++, "usb_headset output", 0, false, createPortMixExt(1, 1));
- c.ports.push_back(usbHeadsetOutMix);
+ AudioPort usbDeviceOutMix =
+ createPort(c.nextPortId++, "usb_device output", 0, false, createPortMixExt(1, 1));
+ c.ports.push_back(usbDeviceOutMix);
- AudioPort usbHeadsetInMix =
- createPort(c.nextPortId++, "usb_headset input", 0, true, createPortMixExt(1, 1));
- c.ports.push_back(usbHeadsetInMix);
+ AudioPort usbDeviceInMix =
+ createPort(c.nextPortId++, "usb_device input", 0, true, createPortMixExt(1, 1));
+ c.ports.push_back(usbDeviceInMix);
- c.routes.push_back(createRoute({usbHeadsetOutMix}, usbOutHeadset));
- c.routes.push_back(createRoute({usbInHeadset}, usbHeadsetInMix));
+ c.routes.push_back(createRoute({usbDeviceOutMix}, usbOutDevice));
+ c.routes.push_back(createRoute({usbDeviceOutMix}, usbOutHeadset));
+ c.routes.push_back(createRoute({usbInDevice, usbInHeadset}, usbDeviceInMix));
+
+ return c;
+ }();
+ return std::make_unique<Configuration>(configuration);
+}
+
+// Stub configuration:
+//
+// Device ports:
+// * "Test Out", OUT_AFE_PROXY
+// - no profiles specified
+// * "Test In", IN_AFE_PROXY
+// - no profiles specified
+// * "Wired Headset", OUT_HEADSET
+// - profile PCM 24-bit; STEREO; 48000
+// * "Wired Headset Mic", IN_HEADSET
+// - profile PCM 24-bit; MONO; 48000
+//
+// Mix ports:
+// * "test output", 1 max open, 1 max active stream
+// - profile PCM 24-bit; MONO, STEREO; 8000, 11025, 16000, 32000, 44100, 48000
+// * "test fast output", 1 max open, 1 max active stream
+// - profile PCM 24-bit; STEREO; 44100, 48000
+// * "test compressed offload", DIRECT|COMPRESS_OFFLOAD|NON_BLOCKING, 1 max open, 1 max active
+// stream
+// - profile MP3; MONO, STEREO; 44100, 48000
+// * "test input", 2 max open, 2 max active streams
+// - profile PCM 24-bit; MONO, STEREO, FRONT_BACK;
+// 8000, 11025, 16000, 22050, 32000, 44100, 48000
+//
+// Routes:
+// "test output", "test fast output", "test compressed offload" -> "Test Out"
+// "test output" -> "Wired Headset"
+// "Test In", "Wired Headset Mic" -> "test input"
+//
+// Initial port configs:
+// * "Test Out" device port: PCM 24-bit; STEREO; 48000
+// * "Test In" device port: PCM 24-bit; MONO; 48000
+//
+std::unique_ptr<Configuration> getStubConfiguration() {
+ static const Configuration configuration = []() {
+ Configuration c;
+
+ // Device ports
+
+ AudioPort testOutDevice = createPort(c.nextPortId++, "Test Out", 0, false,
+ createDeviceExt(AudioDeviceType::OUT_AFE_PROXY, 0));
+ c.ports.push_back(testOutDevice);
+ c.initialConfigs.push_back(
+ createPortConfig(testOutDevice.id, testOutDevice.id, PcmType::INT_24_BIT,
+ AudioChannelLayout::LAYOUT_STEREO, 48000, 0, false,
+ createDeviceExt(AudioDeviceType::OUT_AFE_PROXY, 0)));
+
+ AudioPort headsetOutDevice =
+ createPort(c.nextPortId++, "Wired Headset", 0, false,
+ createDeviceExt(AudioDeviceType::OUT_HEADSET, 0,
+ AudioDeviceDescription::CONNECTION_ANALOG));
+ headsetOutDevice.profiles.push_back(
+ createProfile(PcmType::INT_24_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {48000}));
+ c.ports.push_back(headsetOutDevice);
+
+ AudioPort testInDevice = createPort(c.nextPortId++, "Test In", 0, true,
+ createDeviceExt(AudioDeviceType::IN_AFE_PROXY, 0));
+ c.ports.push_back(testInDevice);
+ c.initialConfigs.push_back(
+ createPortConfig(testInDevice.id, testInDevice.id, PcmType::INT_24_BIT,
+ AudioChannelLayout::LAYOUT_MONO, 48000, 0, true,
+ createDeviceExt(AudioDeviceType::IN_AFE_PROXY, 0)));
+
+ AudioPort headsetInDevice =
+ createPort(c.nextPortId++, "Wired Headset Mic", 0, true,
+ createDeviceExt(AudioDeviceType::IN_HEADSET, 0,
+ AudioDeviceDescription::CONNECTION_ANALOG));
+ headsetInDevice.profiles.push_back(
+ createProfile(PcmType::INT_24_BIT, {AudioChannelLayout::LAYOUT_MONO}, {48000}));
+ c.ports.push_back(headsetInDevice);
+
+ // Mix ports
+
+ AudioPort testOutMix =
+ createPort(c.nextPortId++, "test output", 0, false, createPortMixExt(1, 1));
+ testOutMix.profiles.push_back(
+ createProfile(PcmType::INT_24_BIT,
+ {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
+ {8000, 11025, 16000, 32000, 44100, 48000}));
+ c.ports.push_back(testOutMix);
+
+ AudioPort testFastOutMix = createPort(c.nextPortId++, "test fast output",
+ makeBitPositionFlagMask({AudioOutputFlags::FAST}),
+ false, createPortMixExt(1, 1));
+ testFastOutMix.profiles.push_back(createProfile(
+ PcmType::INT_24_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {44100, 48000}));
+ c.ports.push_back(testFastOutMix);
+
+ AudioPort compressedOffloadOutMix =
+ createPort(c.nextPortId++, "test compressed offload",
+ makeBitPositionFlagMask({AudioOutputFlags::DIRECT,
+ AudioOutputFlags::COMPRESS_OFFLOAD,
+ AudioOutputFlags::NON_BLOCKING}),
+ false, createPortMixExt(1, 1));
+ compressedOffloadOutMix.profiles.push_back(
+ createProfile(::android::MEDIA_MIMETYPE_AUDIO_MPEG,
+ {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO},
+ {44100, 48000}));
+ c.ports.push_back(compressedOffloadOutMix);
+
+ AudioPort testInMIx =
+ createPort(c.nextPortId++, "test input", 0, true, createPortMixExt(2, 2));
+ testInMIx.profiles.push_back(
+ createProfile(PcmType::INT_16_BIT,
+ {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO,
+ AudioChannelLayout::LAYOUT_FRONT_BACK},
+ {8000, 11025, 16000, 22050, 32000, 44100, 48000}));
+ testInMIx.profiles.push_back(
+ createProfile(PcmType::INT_24_BIT,
+ {AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_STEREO,
+ AudioChannelLayout::LAYOUT_FRONT_BACK},
+ {8000, 11025, 16000, 22050, 32000, 44100, 48000}));
+ c.ports.push_back(testInMIx);
+
+ c.routes.push_back(
+ createRoute({testOutMix, testFastOutMix, compressedOffloadOutMix}, testOutDevice));
+ c.routes.push_back(createRoute({testOutMix}, headsetOutDevice));
+ c.routes.push_back(createRoute({testInDevice, headsetInDevice}, testInMIx));
+
+ c.portConfigs.insert(c.portConfigs.end(), c.initialConfigs.begin(), c.initialConfigs.end());
+
+ return c;
+ }();
+ return std::make_unique<Configuration>(configuration);
+}
+
+// Bluetooth configuration:
+//
+// Device ports:
+// * "BT A2DP Out", OUT_DEVICE, CONNECTION_BT_A2DP
+// - profile PCM 16-bit; STEREO; 44100, 48000, 88200, 96000
+// * "BT A2DP Headphones", OUT_HEADPHONE, CONNECTION_BT_A2DP
+// - profile PCM 16-bit; STEREO; 44100, 48000, 88200, 96000
+// * "BT A2DP Speaker", OUT_SPEAKER, CONNECTION_BT_A2DP
+// - profile PCM 16-bit; STEREO; 44100, 48000, 88200, 96000
+// * "BT Hearing Aid Out", OUT_HEARING_AID, CONNECTION_WIRELESS
+// - no profiles specified
+//
+// Mix ports:
+// * "a2dp output", 1 max open, 1 max active stream
+// - no profiles specified
+// * "hearing aid output", 1 max open, 1 max active stream
+// - profile PCM 16-bit; STEREO; 16000, 24000
+//
+// Routes:
+// "a2dp output" -> "BT A2DP Out"
+// "a2dp output" -> "BT A2DP Headphones"
+// "a2dp output" -> "BT A2DP Speaker"
+// "hearing aid output" -> "BT Hearing Aid Out"
+//
+std::unique_ptr<Configuration> getBluetoothConfiguration() {
+ static const Configuration configuration = []() {
+ const std::vector<AudioProfile> standardPcmAudioProfiles = {
+ createProfile(PcmType::INT_16_BIT, {AudioChannelLayout::LAYOUT_STEREO},
+ {44100, 48000, 88200, 96000})};
+ Configuration c;
+
+ // Device ports
+ AudioPort btOutDevice =
+ createPort(c.nextPortId++, "BT A2DP Out", 0, false,
+ createDeviceExt(AudioDeviceType::OUT_DEVICE, 0,
+ AudioDeviceDescription::CONNECTION_BT_A2DP));
+ btOutDevice.profiles.insert(btOutDevice.profiles.begin(), standardPcmAudioProfiles.begin(),
+ standardPcmAudioProfiles.end());
+ c.ports.push_back(btOutDevice);
+ c.connectedProfiles[btOutDevice.id] = standardPcmAudioProfiles;
+
+ AudioPort btOutHeadphone =
+ createPort(c.nextPortId++, "BT A2DP Headphones", 0, false,
+ createDeviceExt(AudioDeviceType::OUT_HEADPHONE, 0,
+ AudioDeviceDescription::CONNECTION_BT_A2DP));
+ btOutHeadphone.profiles.insert(btOutHeadphone.profiles.begin(),
+ standardPcmAudioProfiles.begin(),
+ standardPcmAudioProfiles.end());
+ c.ports.push_back(btOutHeadphone);
+ c.connectedProfiles[btOutHeadphone.id] = standardPcmAudioProfiles;
+
+ AudioPort btOutSpeaker =
+ createPort(c.nextPortId++, "BT A2DP Speaker", 0, false,
+ createDeviceExt(AudioDeviceType::OUT_SPEAKER, 0,
+ AudioDeviceDescription::CONNECTION_BT_A2DP));
+ btOutSpeaker.profiles.insert(btOutSpeaker.profiles.begin(),
+ standardPcmAudioProfiles.begin(),
+ standardPcmAudioProfiles.end());
+ c.ports.push_back(btOutSpeaker);
+ c.connectedProfiles[btOutSpeaker.id] = standardPcmAudioProfiles;
+
+ AudioPort btOutHearingAid =
+ createPort(c.nextPortId++, "BT Hearing Aid Out", 0, false,
+ createDeviceExt(AudioDeviceType::OUT_HEARING_AID, 0,
+ AudioDeviceDescription::CONNECTION_WIRELESS));
+ c.ports.push_back(btOutHearingAid);
+ c.connectedProfiles[btOutHearingAid.id] = std::vector<AudioProfile>(
+ {createProfile(PcmType::INT_16_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {16000})});
+
+ // Mix ports
+ AudioPort btOutMix =
+ createPort(c.nextPortId++, "a2dp output", 0, false, createPortMixExt(1, 1));
+ c.ports.push_back(btOutMix);
+
+ AudioPort btHearingOutMix =
+ createPort(c.nextPortId++, "hearing aid output", 0, false, createPortMixExt(1, 1));
+ btHearingOutMix.profiles.push_back(createProfile(
+ PcmType::INT_16_BIT, {AudioChannelLayout::LAYOUT_STEREO}, {16000, 24000}));
+ c.ports.push_back(btHearingOutMix);
+
+ c.routes.push_back(createRoute({btOutMix}, btOutDevice));
+ c.routes.push_back(createRoute({btOutMix}, btOutHeadphone));
+ c.routes.push_back(createRoute({btOutMix}, btOutSpeaker));
+ c.routes.push_back(createRoute({btHearingOutMix}, btOutHearingAid));
return c;
}();
diff --git a/audio/aidl/default/EffectConfig.cpp b/audio/aidl/default/EffectConfig.cpp
index 71d111b..730c0bf 100644
--- a/audio/aidl/default/EffectConfig.cpp
+++ b/audio/aidl/default/EffectConfig.cpp
@@ -18,6 +18,7 @@
#include <string>
#define LOG_TAG "AHAL_EffectConfig"
#include <android-base/logging.h>
+#include <system/audio_aidl_utils.h>
#include <system/audio_effects/audio_effects_conf.h>
#include <system/audio_effects/effect_uuid.h>
@@ -116,53 +117,59 @@
bool EffectConfig::parseEffect(const tinyxml2::XMLElement& xml) {
struct EffectLibraries effectLibraries;
- std::vector<LibraryUuid> libraryUuids;
+ std::vector<Library> libraries;
std::string name = xml.Attribute("name");
RETURN_VALUE_IF(name == "", false, "effectsNoName");
LOG(DEBUG) << __func__ << dump(xml);
- struct LibraryUuid libraryUuid;
+ struct Library library;
if (std::strcmp(xml.Name(), "effectProxy") == 0) {
// proxy lib and uuid
- RETURN_VALUE_IF(!parseLibraryUuid(xml, libraryUuid, true), false, "parseProxyLibFailed");
- effectLibraries.proxyLibrary = libraryUuid;
+ RETURN_VALUE_IF(!parseLibrary(xml, library, true), false, "parseProxyLibFailed");
+ effectLibraries.proxyLibrary = library;
// proxy effect libs and UUID
auto xmlProxyLib = xml.FirstChildElement();
RETURN_VALUE_IF(!xmlProxyLib, false, "noLibForProxy");
while (xmlProxyLib) {
- struct LibraryUuid tempLibraryUuid;
- RETURN_VALUE_IF(!parseLibraryUuid(*xmlProxyLib, tempLibraryUuid), false,
+ struct Library tempLibrary;
+ RETURN_VALUE_IF(!parseLibrary(*xmlProxyLib, tempLibrary), false,
"parseEffectLibFailed");
- libraryUuids.push_back(std::move(tempLibraryUuid));
+ libraries.push_back(std::move(tempLibrary));
xmlProxyLib = xmlProxyLib->NextSiblingElement();
}
} else {
// expect only one library if not proxy
- RETURN_VALUE_IF(!parseLibraryUuid(xml, libraryUuid), false, "parseEffectLibFailed");
- libraryUuids.push_back(std::move(libraryUuid));
+ RETURN_VALUE_IF(!parseLibrary(xml, library), false, "parseEffectLibFailed");
+ libraries.push_back(std::move(library));
}
- effectLibraries.libraries = std::move(libraryUuids);
+ effectLibraries.libraries = std::move(libraries);
mEffectsMap[name] = std::move(effectLibraries);
return true;
}
-bool EffectConfig::parseLibraryUuid(const tinyxml2::XMLElement& xml,
- struct LibraryUuid& libraryUuid, bool isProxy) {
+bool EffectConfig::parseLibrary(const tinyxml2::XMLElement& xml, struct Library& library,
+ bool isProxy) {
// Retrieve library name only if not effectProxy element
if (!isProxy) {
const char* name = xml.Attribute("library");
RETURN_VALUE_IF(!name, false, "noLibraryAttribute");
- libraryUuid.name = name;
+ library.name = name;
}
const char* uuidStr = xml.Attribute("uuid");
RETURN_VALUE_IF(!uuidStr, false, "noUuidAttribute");
- libraryUuid.uuid = stringToUuid(uuidStr);
- RETURN_VALUE_IF((libraryUuid.uuid == getEffectUuidZero()), false, "invalidUuidAttribute");
+ library.uuid = stringToUuid(uuidStr);
+ if (const char* typeUuidStr = xml.Attribute("type")) {
+ library.type = stringToUuid(typeUuidStr);
+ }
+ RETURN_VALUE_IF((library.uuid == getEffectUuidZero()), false, "invalidUuidAttribute");
- LOG(DEBUG) << __func__ << (isProxy ? " proxy " : libraryUuid.name) << " : "
- << libraryUuid.uuid.toString();
+ LOG(DEBUG) << __func__ << (isProxy ? " proxy " : library.name) << " : uuid "
+ << ::android::audio::utils::toString(library.uuid)
+ << (library.type.has_value()
+ ? ::android::audio::utils::toString(library.type.value())
+ : "");
return true;
}
@@ -240,7 +247,8 @@
return mProcessingMap;
}
-bool EffectConfig::findUuid(const std::string& xmlEffectName, AudioUuid* uuid) {
+bool EffectConfig::findUuid(const std::pair<std::string, struct EffectLibraries>& effectElem,
+ AudioUuid* uuid) {
// Difference from EFFECT_TYPE_LIST_DEF, there could be multiple name mapping to same Effect Type
#define EFFECT_XML_TYPE_LIST_DEF(V) \
V("acoustic_echo_canceler", AcousticEchoCanceler) \
@@ -250,6 +258,7 @@
V("downmix", Downmix) \
V("dynamics_processing", DynamicsProcessing) \
V("equalizer", Equalizer) \
+ V("extensioneffect", Extension) \
V("haptic_generator", HapticGenerator) \
V("loudness_enhancer", LoudnessEnhancer) \
V("env_reverb", EnvReverb) \
@@ -266,6 +275,7 @@
#define GENERATE_MAP_ENTRY_V(s, symbol) {s, &getEffectTypeUuid##symbol},
+ const std::string xmlEffectName = effectElem.first;
typedef const AudioUuid& (*UuidGetter)(void);
static const std::map<std::string, UuidGetter> uuidMap{
// std::make_pair("s", &getEffectTypeUuidExtension)};
@@ -274,6 +284,14 @@
*uuid = (*it->second)();
return true;
}
+
+ const auto& libs = effectElem.second.libraries;
+ for (const auto& lib : libs) {
+ if (lib.type.has_value()) {
+ *uuid = lib.type.value();
+ return true;
+ }
+ }
return false;
}
diff --git a/audio/aidl/default/EffectFactory.cpp b/audio/aidl/default/EffectFactory.cpp
index 7073a10..96f13ba 100644
--- a/audio/aidl/default/EffectFactory.cpp
+++ b/audio/aidl/default/EffectFactory.cpp
@@ -25,6 +25,7 @@
#include <android-base/logging.h>
#include <android/binder_ibinder_platform.h>
+#include <system/audio_aidl_utils.h>
#include <system/audio_effects/effect_uuid.h>
#include <system/thread_defs.h>
@@ -47,19 +48,19 @@
for (const auto& it : mEffectMap) {
if (auto spEffect = it.first.lock()) {
LOG(ERROR) << __func__ << " erase remaining instance UUID "
- << it.second.first.toString();
- destroyEffectImpl(spEffect);
+ << ::android::audio::utils::toString(it.second.first);
+ destroyEffectImpl_l(spEffect);
}
}
}
}
-ndk::ScopedAStatus Factory::getDescriptorWithUuid(const AudioUuid& uuid, Descriptor* desc) {
+ndk::ScopedAStatus Factory::getDescriptorWithUuid_l(const AudioUuid& uuid, Descriptor* desc) {
RETURN_IF(!desc, EX_NULL_POINTER, "nullDescriptor");
if (mEffectLibMap.count(uuid)) {
auto& entry = mEffectLibMap[uuid];
- getDlSyms(entry);
+ getDlSyms_l(entry);
auto& libInterface = std::get<kMapEntryInterfaceIndex>(entry);
RETURN_IF(!libInterface || !libInterface->queryEffectFunc, EX_NULL_POINTER,
"dlNullQueryEffectFunc");
@@ -74,6 +75,7 @@
const std::optional<AudioUuid>& in_impl_uuid,
const std::optional<AudioUuid>& in_proxy_uuid,
std::vector<Descriptor>* _aidl_return) {
+ std::lock_guard lg(mMutex);
// get the matching list
std::vector<Descriptor::Identity> idList;
std::copy_if(mIdentitySet.begin(), mIdentitySet.end(), std::back_inserter(idList),
@@ -87,7 +89,8 @@
for (const auto& id : idList) {
if (mEffectLibMap.count(id.uuid)) {
Descriptor desc;
- RETURN_IF_ASTATUS_NOT_OK(getDescriptorWithUuid(id.uuid, &desc), "getDescriptorFailed");
+ RETURN_IF_ASTATUS_NOT_OK(getDescriptorWithUuid_l(id.uuid, &desc),
+ "getDescriptorFailed");
// update proxy UUID with information from config xml
desc.common.id.proxy = id.proxy;
_aidl_return->emplace_back(std::move(desc));
@@ -98,18 +101,19 @@
ndk::ScopedAStatus Factory::queryProcessing(const std::optional<Processing::Type>& in_type,
std::vector<Processing>* _aidl_return) {
+ std::lock_guard lg(mMutex);
const auto& processings = mConfig.getProcessingMap();
// Processing stream type
for (const auto& procIter : processings) {
if (!in_type.has_value() || in_type.value() == procIter.first) {
Processing process = {.type = procIter.first /* Processing::Type */};
for (const auto& libs : procIter.second /* std::vector<struct EffectLibraries> */) {
- for (const auto& lib : libs.libraries /* std::vector<struct LibraryUuid> */) {
+ for (const auto& lib : libs.libraries /* std::vector<struct Library> */) {
Descriptor desc;
if (libs.proxyLibrary.has_value()) {
desc.common.id.proxy = libs.proxyLibrary.value().uuid;
}
- RETURN_IF_ASTATUS_NOT_OK(getDescriptorWithUuid(lib.uuid, &desc),
+ RETURN_IF_ASTATUS_NOT_OK(getDescriptorWithUuid_l(lib.uuid, &desc),
"getDescriptorFailed");
process.ids.emplace_back(desc);
}
@@ -123,10 +127,11 @@
ndk::ScopedAStatus Factory::createEffect(const AudioUuid& in_impl_uuid,
std::shared_ptr<IEffect>* _aidl_return) {
- LOG(DEBUG) << __func__ << ": UUID " << in_impl_uuid.toString();
+ LOG(DEBUG) << __func__ << ": UUID " << ::android::audio::utils::toString(in_impl_uuid);
+ std::lock_guard lg(mMutex);
if (mEffectLibMap.count(in_impl_uuid)) {
auto& entry = mEffectLibMap[in_impl_uuid];
- getDlSyms(entry);
+ getDlSyms_l(entry);
auto& libInterface = std::get<kMapEntryInterfaceIndex>(entry);
RETURN_IF(!libInterface || !libInterface->createEffectFunc, EX_NULL_POINTER,
@@ -151,7 +156,7 @@
return ndk::ScopedAStatus::ok();
}
-ndk::ScopedAStatus Factory::destroyEffectImpl(const std::shared_ptr<IEffect>& in_handle) {
+ndk::ScopedAStatus Factory::destroyEffectImpl_l(const std::shared_ptr<IEffect>& in_handle) {
std::weak_ptr<IEffect> wpHandle(in_handle);
// find the effect entry with key (std::weak_ptr<IEffect>)
if (auto effectIt = mEffectMap.find(wpHandle); effectIt != mEffectMap.end()) {
@@ -163,7 +168,8 @@
"dlNulldestroyEffectFunc");
RETURN_IF_BINDER_EXCEPTION(interface->destroyEffectFunc(in_handle));
} else {
- LOG(ERROR) << __func__ << ": UUID " << uuid.toString() << " does not exist in libMap!";
+ LOG(ERROR) << __func__ << ": UUID " << ::android::audio::utils::toString(uuid)
+ << " does not exist in libMap!";
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
mEffectMap.erase(effectIt);
@@ -175,7 +181,7 @@
}
// go over the map and cleanup all expired weak_ptrs.
-void Factory::cleanupEffectMap() {
+void Factory::cleanupEffectMap_l() {
for (auto it = mEffectMap.begin(); it != mEffectMap.end();) {
if (nullptr == it->first.lock()) {
it = mEffectMap.erase(it);
@@ -187,13 +193,15 @@
ndk::ScopedAStatus Factory::destroyEffect(const std::shared_ptr<IEffect>& in_handle) {
LOG(DEBUG) << __func__ << ": instance " << in_handle.get();
- ndk::ScopedAStatus status = destroyEffectImpl(in_handle);
+ std::lock_guard lg(mMutex);
+ ndk::ScopedAStatus status = destroyEffectImpl_l(in_handle);
// always do the cleanup
- cleanupEffectMap();
+ cleanupEffectMap_l();
return status;
}
-bool Factory::openEffectLibrary(const AudioUuid& impl, const std::string& path) {
+bool Factory::openEffectLibrary(const AudioUuid& impl,
+ const std::string& path) NO_THREAD_SAFETY_ANALYSIS {
std::function<void(void*)> dlClose = [](void* handle) -> void {
if (handle && dlclose(handle)) {
LOG(ERROR) << "dlclose failed " << dlerror();
@@ -207,8 +215,8 @@
return false;
}
- LOG(INFO) << __func__ << " dlopen lib:" << path << "\nimpl:" << impl.toString()
- << "\nhandle:" << libHandle;
+ LOG(INFO) << __func__ << " dlopen lib:" << path
+ << "\nimpl:" << ::android::audio::utils::toString(impl) << "\nhandle:" << libHandle;
auto interface = new effect_dl_interface_s{nullptr, nullptr, nullptr};
mEffectLibMap.insert(
{impl,
@@ -217,9 +225,9 @@
return true;
}
-void Factory::createIdentityWithConfig(const EffectConfig::LibraryUuid& configLib,
- const AudioUuid& typeUuid,
- const std::optional<AudioUuid> proxyUuid) {
+void Factory::createIdentityWithConfig(
+ const EffectConfig::Library& configLib, const AudioUuid& typeUuid,
+ const std::optional<AudioUuid> proxyUuid) NO_THREAD_SAFETY_ANALYSIS {
static const auto& libMap = mConfig.getLibraryMap();
const std::string& libName = configLib.name;
if (auto path = libMap.find(libName); path != libMap.end()) {
@@ -228,8 +236,10 @@
id.uuid = configLib.uuid;
id.proxy = proxyUuid;
LOG(DEBUG) << __func__ << " loading lib " << path->second << ": typeUuid "
- << id.type.toString() << "\nimplUuid " << id.uuid.toString() << " proxyUuid "
- << (proxyUuid.has_value() ? proxyUuid->toString() : "null");
+ << ::android::audio::utils::toString(id.type) << "\nimplUuid "
+ << ::android::audio::utils::toString(id.uuid) << " proxyUuid "
+ << (proxyUuid.has_value() ? ::android::audio::utils::toString(proxyUuid.value())
+ : "null");
if (openEffectLibrary(id.uuid, path->second)) {
mIdentitySet.insert(std::move(id));
}
@@ -242,8 +252,7 @@
void Factory::loadEffectLibs() {
const auto& configEffectsMap = mConfig.getEffectsMap();
for (const auto& configEffects : configEffectsMap) {
- if (AudioUuid uuid;
- EffectConfig::findUuid(configEffects.first /* xml effect name */, &uuid)) {
+ if (AudioUuid type; EffectConfig::findUuid(configEffects /* xml effect */, &type)) {
const auto& configLibs = configEffects.second;
std::optional<AudioUuid> proxyUuid;
if (configLibs.proxyLibrary.has_value()) {
@@ -251,7 +260,7 @@
proxyUuid = proxyLib.uuid;
}
for (const auto& configLib : configLibs.libraries) {
- createIdentityWithConfig(configLib, uuid, proxyUuid);
+ createIdentityWithConfig(configLib, type, proxyUuid);
}
} else {
LOG(ERROR) << __func__ << ": can not find type UUID for effect " << configEffects.first
@@ -260,7 +269,7 @@
}
}
-void Factory::getDlSyms(DlEntry& entry) {
+void Factory::getDlSyms_l(DlEntry& entry) {
auto& dlHandle = std::get<kMapEntryHandleIndex>(entry);
RETURN_VALUE_IF(!dlHandle, void(), "dlNullHandle");
// Get the reference of the DL interfaces in library map tuple.
diff --git a/audio/aidl/default/EffectImpl.cpp b/audio/aidl/default/EffectImpl.cpp
index da1ad11..c81c731 100644
--- a/audio/aidl/default/EffectImpl.cpp
+++ b/audio/aidl/default/EffectImpl.cpp
@@ -76,7 +76,7 @@
}
ndk::ScopedAStatus EffectImpl::setParameter(const Parameter& param) {
- LOG(DEBUG) << getEffectName() << __func__ << " with: " << param.toString();
+ LOG(VERBOSE) << getEffectName() << __func__ << " with: " << param.toString();
const auto tag = param.getTag();
switch (tag) {
@@ -100,7 +100,6 @@
}
ndk::ScopedAStatus EffectImpl::getParameter(const Parameter::Id& id, Parameter* param) {
- LOG(DEBUG) << getEffectName() << __func__ << id.toString();
auto tag = id.getTag();
switch (tag) {
case Parameter::Id::commonTag: {
@@ -117,7 +116,7 @@
break;
}
}
- LOG(DEBUG) << getEffectName() << __func__ << param->toString();
+ LOG(VERBOSE) << getEffectName() << __func__ << id.toString() << param->toString();
return ndk::ScopedAStatus::ok();
}
@@ -254,7 +253,7 @@
for (int i = 0; i < samples; i++) {
*out++ = *in++;
}
- LOG(DEBUG) << getEffectName() << __func__ << " done processing " << samples << " samples";
+ LOG(VERBOSE) << getEffectName() << __func__ << " done processing " << samples << " samples";
return {STATUS_OK, samples, samples};
}
diff --git a/audio/aidl/default/EffectThread.cpp b/audio/aidl/default/EffectThread.cpp
index 574dc69..47ba9f4 100644
--- a/audio/aidl/default/EffectThread.cpp
+++ b/audio/aidl/default/EffectThread.cpp
@@ -48,6 +48,8 @@
mPriority = priority;
{
std::lock_guard lg(mThreadMutex);
+ mStop = true;
+ mExit = false;
mThreadContext = std::move(context);
auto statusMQ = mThreadContext->getStatusFmq();
EventFlag* efGroup = nullptr;
@@ -149,8 +151,8 @@
IEffect::Status status = effectProcessImpl(buffer, buffer, processSamples);
outputMQ->write(buffer, status.fmqProduced);
statusMQ->writeBlocking(&status, 1);
- LOG(DEBUG) << mName << __func__ << ": done processing, effect consumed "
- << status.fmqConsumed << " produced " << status.fmqProduced;
+ LOG(VERBOSE) << mName << __func__ << ": done processing, effect consumed "
+ << status.fmqConsumed << " produced " << status.fmqProduced;
}
}
diff --git a/audio/aidl/default/EngineConfigXmlConverter.cpp b/audio/aidl/default/EngineConfigXmlConverter.cpp
index 5f17d71..96b555c 100644
--- a/audio/aidl/default/EngineConfigXmlConverter.cpp
+++ b/audio/aidl/default/EngineConfigXmlConverter.cpp
@@ -140,7 +140,7 @@
aidlAttributesGroup.volumeGroupName = xsdcAttributesGroup.getVolumeGroup();
if (xsdcAttributesGroup.hasAttributes_optional()) {
aidlAttributesGroup.attributes =
- convertCollectionToAidl<xsd::AttributesType, AudioAttributes>(
+ convertCollectionToAidlUnchecked<xsd::AttributesType, AudioAttributes>(
xsdcAttributesGroup.getAttributes_optional(),
std::bind(&EngineConfigXmlConverter::convertAudioAttributesToAidl, this,
std::placeholders::_1));
@@ -172,7 +172,7 @@
if (xsdcProductStrategy.hasAttributesGroup()) {
aidlProductStrategy.attributesGroups =
- convertCollectionToAidl<xsd::AttributesGroup, AudioHalAttributesGroup>(
+ convertCollectionToAidlUnchecked<xsd::AttributesGroup, AudioHalAttributesGroup>(
xsdcProductStrategy.getAttributesGroup(),
std::bind(&EngineConfigXmlConverter::convertAttributesGroupToAidl, this,
std::placeholders::_1));
@@ -204,13 +204,13 @@
getXsdcConfig()->getVolumes());
}
aidlVolumeCurve.curvePoints =
- convertCollectionToAidl<std::string, AudioHalVolumeCurve::CurvePoint>(
+ convertCollectionToAidlUnchecked<std::string, AudioHalVolumeCurve::CurvePoint>(
mVolumesReferenceMap.at(xsdcVolumeCurve.getRef()).getPoint(),
std::bind(&EngineConfigXmlConverter::convertCurvePointToAidl, this,
std::placeholders::_1));
} else {
aidlVolumeCurve.curvePoints =
- convertCollectionToAidl<std::string, AudioHalVolumeCurve::CurvePoint>(
+ convertCollectionToAidlUnchecked<std::string, AudioHalVolumeCurve::CurvePoint>(
xsdcVolumeCurve.getPoint(),
std::bind(&EngineConfigXmlConverter::convertCurvePointToAidl, this,
std::placeholders::_1));
@@ -224,10 +224,11 @@
aidlVolumeGroup.name = xsdcVolumeGroup.getName();
aidlVolumeGroup.minIndex = xsdcVolumeGroup.getIndexMin();
aidlVolumeGroup.maxIndex = xsdcVolumeGroup.getIndexMax();
- aidlVolumeGroup.volumeCurves = convertCollectionToAidl<xsd::Volume, AudioHalVolumeCurve>(
- xsdcVolumeGroup.getVolume(),
- std::bind(&EngineConfigXmlConverter::convertVolumeCurveToAidl, this,
- std::placeholders::_1));
+ aidlVolumeGroup.volumeCurves =
+ convertCollectionToAidlUnchecked<xsd::Volume, AudioHalVolumeCurve>(
+ xsdcVolumeGroup.getVolume(),
+ std::bind(&EngineConfigXmlConverter::convertVolumeCurveToAidl, this,
+ std::placeholders::_1));
return aidlVolumeGroup;
}
@@ -251,7 +252,7 @@
aidlCapCriterionType.name = xsdcCriterionType.getName();
aidlCapCriterionType.isInclusive = !(static_cast<bool>(xsdcCriterionType.getType()));
aidlCapCriterionType.values =
- convertWrappedCollectionToAidl<xsd::ValuesType, xsd::ValueType, std::string>(
+ convertWrappedCollectionToAidlUnchecked<xsd::ValuesType, xsd::ValueType, std::string>(
xsdcCriterionType.getValues(), &xsd::ValuesType::getValue,
std::bind(&EngineConfigXmlConverter::convertCriterionTypeValueToAidl, this,
std::placeholders::_1));
@@ -266,9 +267,9 @@
initProductStrategyMap();
if (getXsdcConfig()->hasProductStrategies()) {
mAidlEngineConfig.productStrategies =
- convertWrappedCollectionToAidl<xsd::ProductStrategies,
- xsd::ProductStrategies::ProductStrategy,
- AudioHalProductStrategy>(
+ convertWrappedCollectionToAidlUnchecked<xsd::ProductStrategies,
+ xsd::ProductStrategies::ProductStrategy,
+ AudioHalProductStrategy>(
getXsdcConfig()->getProductStrategies(),
&xsd::ProductStrategies::getProductStrategy,
std::bind(&EngineConfigXmlConverter::convertProductStrategyToAidl, this,
@@ -278,7 +279,7 @@
}
}
if (getXsdcConfig()->hasVolumeGroups()) {
- mAidlEngineConfig.volumeGroups = convertWrappedCollectionToAidl<
+ mAidlEngineConfig.volumeGroups = convertWrappedCollectionToAidlUnchecked<
xsd::VolumeGroupsType, xsd::VolumeGroupsType::VolumeGroup, AudioHalVolumeGroup>(
getXsdcConfig()->getVolumeGroups(), &xsd::VolumeGroupsType::getVolumeGroup,
std::bind(&EngineConfigXmlConverter::convertVolumeGroupToAidl, this,
@@ -287,19 +288,17 @@
if (getXsdcConfig()->hasCriteria() && getXsdcConfig()->hasCriterion_types()) {
AudioHalEngineConfig::CapSpecificConfig capSpecificConfig;
capSpecificConfig.criteria =
- convertWrappedCollectionToAidl<xsd::CriteriaType, xsd::CriterionType,
- AudioHalCapCriterion>(
+ convertWrappedCollectionToAidlUnchecked<xsd::CriteriaType, xsd::CriterionType,
+ AudioHalCapCriterion>(
getXsdcConfig()->getCriteria(), &xsd::CriteriaType::getCriterion,
std::bind(&EngineConfigXmlConverter::convertCapCriterionToAidl, this,
std::placeholders::_1));
- capSpecificConfig.criterionTypes =
- convertWrappedCollectionToAidl<xsd::CriterionTypesType, xsd::CriterionTypeType,
- AudioHalCapCriterionType>(
- getXsdcConfig()->getCriterion_types(),
- &xsd::CriterionTypesType::getCriterion_type,
- std::bind(&EngineConfigXmlConverter::convertCapCriterionTypeToAidl, this,
- std::placeholders::_1));
+ capSpecificConfig.criterionTypes = convertWrappedCollectionToAidlUnchecked<
+ xsd::CriterionTypesType, xsd::CriterionTypeType, AudioHalCapCriterionType>(
+ getXsdcConfig()->getCriterion_types(), &xsd::CriterionTypesType::getCriterion_type,
+ std::bind(&EngineConfigXmlConverter::convertCapCriterionTypeToAidl, this,
+ std::placeholders::_1));
mAidlEngineConfig.capSpecificConfig = capSpecificConfig;
}
}
-} // namespace aidl::android::hardware::audio::core::internal
\ No newline at end of file
+} // namespace aidl::android::hardware::audio::core::internal
diff --git a/audio/aidl/default/Module.cpp b/audio/aidl/default/Module.cpp
index 6b417a4..b7761bf 100644
--- a/audio/aidl/default/Module.cpp
+++ b/audio/aidl/default/Module.cpp
@@ -18,20 +18,20 @@
#include <set>
#define LOG_TAG "AHAL_Module"
-#include <android-base/logging.h>
-#include <android/binder_ibinder_platform.h>
-
#include <Utils.h>
#include <aidl/android/media/audio/common/AudioInputFlags.h>
#include <aidl/android/media/audio/common/AudioOutputFlags.h>
+#include <android-base/logging.h>
+#include <android/binder_ibinder_platform.h>
+#include <error/expected_utils.h>
-#include "core-impl/Bluetooth.h"
#include "core-impl/Module.h"
+#include "core-impl/ModuleBluetooth.h"
+#include "core-impl/ModulePrimary.h"
+#include "core-impl/ModuleRemoteSubmix.h"
+#include "core-impl/ModuleStub.h"
#include "core-impl/ModuleUsb.h"
#include "core-impl/SoundDose.h"
-#include "core-impl/StreamStub.h"
-#include "core-impl/StreamUsb.h"
-#include "core-impl/Telephony.h"
#include "core-impl/utils.h"
using aidl::android::hardware::audio::common::getFrameSizeInBytes;
@@ -110,36 +110,16 @@
// static
std::shared_ptr<Module> Module::createInstance(Type type) {
switch (type) {
- case Module::Type::USB:
- return ndk::SharedRefBase::make<ModuleUsb>(type);
case Type::DEFAULT:
+ return ndk::SharedRefBase::make<ModulePrimary>();
case Type::R_SUBMIX:
- default:
- return ndk::SharedRefBase::make<Module>(type);
- }
-}
-
-// static
-StreamIn::CreateInstance Module::getStreamInCreator(Type type) {
- switch (type) {
+ return ndk::SharedRefBase::make<ModuleRemoteSubmix>();
+ case Type::STUB:
+ return ndk::SharedRefBase::make<ModuleStub>();
case Type::USB:
- return StreamInUsb::createInstance;
- case Type::DEFAULT:
- case Type::R_SUBMIX:
- default:
- return StreamInStub::createInstance;
- }
-}
-
-// static
-StreamOut::CreateInstance Module::getStreamOutCreator(Type type) {
- switch (type) {
- case Type::USB:
- return StreamOutUsb::createInstance;
- case Type::DEFAULT:
- case Type::R_SUBMIX:
- default:
- return StreamOutStub::createInstance;
+ return ndk::SharedRefBase::make<ModuleUsb>();
+ case Type::BLUETOOTH:
+ return ndk::SharedRefBase::make<ModuleBluetooth>();
}
}
@@ -151,9 +131,15 @@
case Module::Type::R_SUBMIX:
os << "r_submix";
break;
+ case Module::Type::STUB:
+ os << "stub";
+ break;
case Module::Type::USB:
os << "usb";
break;
+ case Module::Type::BLUETOOTH:
+ os << "bluetooth";
+ break;
}
return os;
}
@@ -187,7 +173,7 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
- if (frameSize > kMaximumStreamBufferSizeBytes / in_bufferSizeFrames) {
+ if (frameSize > static_cast<size_t>(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) {
LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
<< " frames is too large, maximum size is "
<< kMaximumStreamBufferSizeBytes / frameSize;
@@ -206,8 +192,9 @@
StreamContext temp(
std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
- portConfigIt->format.value(), portConfigIt->channelMask.value(),
- portConfigIt->sampleRate.value().value,
+ portConfigIt->portId, portConfigIt->format.value(),
+ portConfigIt->channelMask.value(), portConfigIt->sampleRate.value().value, flags,
+ portConfigIt->ext.get<AudioPortExt::mix>().handle,
std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
asyncCallback, outEventCallback, params);
if (temp.isValid()) {
@@ -281,7 +268,7 @@
<< " does not correspond to a mix port";
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
- const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
+ const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
LOG(ERROR) << __func__ << ": port id " << portId
<< " has already reached maximum allowed opened stream count: "
@@ -305,19 +292,31 @@
return result;
}
+std::unique_ptr<internal::Configuration> Module::initializeConfig() {
+ std::unique_ptr<internal::Configuration> config;
+ switch (getType()) {
+ case Type::DEFAULT:
+ config = std::move(internal::getPrimaryConfiguration());
+ break;
+ case Type::R_SUBMIX:
+ config = std::move(internal::getRSubmixConfiguration());
+ break;
+ case Type::STUB:
+ config = std::move(internal::getStubConfiguration());
+ break;
+ case Type::USB:
+ config = std::move(internal::getUsbConfiguration());
+ break;
+ case Type::BLUETOOTH:
+ config = std::move(internal::getBluetoothConfiguration());
+ break;
+ }
+ return config;
+}
+
internal::Configuration& Module::getConfig() {
if (!mConfig) {
- switch (mType) {
- case Type::DEFAULT:
- mConfig = std::move(internal::getPrimaryConfiguration());
- break;
- case Type::R_SUBMIX:
- mConfig = std::move(internal::getRSubmixConfiguration());
- break;
- case Type::USB:
- mConfig = std::move(internal::getUsbConfiguration());
- break;
- }
+ mConfig = std::move(initializeConfig());
}
return *mConfig;
}
@@ -339,30 +338,61 @@
do_insert(patch.sinkPortConfigIds);
}
-void Module::updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch) {
+ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
+ const AudioPatch& newPatch) {
// Streams from the old patch need to be disconnected, streams from the new
// patch need to be connected. If the stream belongs to both patches, no need
// to update it.
- std::set<int32_t> idsToDisconnect, idsToConnect;
+ auto maybeFailure = ndk::ScopedAStatus::ok();
+ std::set<int32_t> idsToDisconnect, idsToConnect, idsToDisconnectOnFailure;
idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
oldPatch.sourcePortConfigIds.end());
idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
- if (idsToConnect.count(portConfigId) == 0) {
- LOG(DEBUG) << "The stream on port config id " << portConfigId << " is not connected";
- mStreams.setStreamIsConnected(portConfigId, {});
+ if (idsToConnect.count(portConfigId) == 0 && mStreams.count(portConfigId) != 0) {
+ if (auto status = mStreams.setStreamConnectedDevices(portConfigId, {}); status.isOk()) {
+ LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
+ << portConfigId << " has been disconnected";
+ } else {
+ // Disconnection is tricky to roll back, just register a failure.
+ maybeFailure = std::move(status);
+ }
}
});
+ if (!maybeFailure.isOk()) return maybeFailure;
std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
- if (idsToDisconnect.count(portConfigId) == 0) {
+ if (idsToDisconnect.count(portConfigId) == 0 && mStreams.count(portConfigId) != 0) {
const auto connectedDevices = findConnectedDevices(portConfigId);
- LOG(DEBUG) << "The stream on port config id " << portConfigId
- << " is connected to: " << ::android::internal::ToString(connectedDevices);
- mStreams.setStreamIsConnected(portConfigId, connectedDevices);
+ if (connectedDevices.empty()) {
+ // This is important as workers use the vector size to derive the connection status.
+ LOG(FATAL) << "updateStreamsConnectedState: No connected devices found for port "
+ "config id "
+ << portConfigId;
+ }
+ if (auto status = mStreams.setStreamConnectedDevices(portConfigId, connectedDevices);
+ status.isOk()) {
+ LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
+ << portConfigId << " has been connected to: "
+ << ::android::internal::ToString(connectedDevices);
+ } else {
+ maybeFailure = std::move(status);
+ idsToDisconnectOnFailure.insert(portConfigId);
+ }
}
});
+ if (!maybeFailure.isOk()) {
+ LOG(WARNING) << __func__ << ": Due to a failure, disconnecting streams on port config ids "
+ << ::android::internal::ToString(idsToDisconnectOnFailure);
+ std::for_each(idsToDisconnectOnFailure.begin(), idsToDisconnectOnFailure.end(),
+ [&](const auto& portConfigId) {
+ auto status = mStreams.setStreamConnectedDevices(portConfigId, {});
+ (void)status.isOk(); // Can't do much about a failure here.
+ });
+ return maybeFailure;
+ }
+ return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus Module::setModuleDebug(
@@ -386,38 +416,26 @@
}
ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
- if (!mTelephony) {
- mTelephony = ndk::SharedRefBase::make<Telephony>();
- }
- *_aidl_return = mTelephony.getPtr();
- LOG(DEBUG) << __func__ << ": returning instance of ITelephony: " << _aidl_return->get();
+ *_aidl_return = nullptr;
+ LOG(DEBUG) << __func__ << ": returning null";
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
- if (!mBluetooth) {
- mBluetooth = ndk::SharedRefBase::make<Bluetooth>();
- }
- *_aidl_return = mBluetooth.getPtr();
- LOG(DEBUG) << __func__ << ": returning instance of IBluetooth: " << _aidl_return->get();
+ *_aidl_return = nullptr;
+ LOG(DEBUG) << __func__ << ": returning null";
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
- if (!mBluetoothA2dp) {
- mBluetoothA2dp = ndk::SharedRefBase::make<BluetoothA2dp>();
- }
- *_aidl_return = mBluetoothA2dp.getPtr();
- LOG(DEBUG) << __func__ << ": returning instance of IBluetoothA2dp: " << _aidl_return->get();
+ *_aidl_return = nullptr;
+ LOG(DEBUG) << __func__ << ": returning null";
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
- if (!mBluetoothLe) {
- mBluetoothLe = ndk::SharedRefBase::make<BluetoothLe>();
- }
- *_aidl_return = mBluetoothLe.getPtr();
- LOG(DEBUG) << __func__ << ": returning instance of IBluetoothLe: " << _aidl_return->get();
+ *_aidl_return = nullptr;
+ LOG(DEBUG) << __func__ << ": returning null";
return ndk::ScopedAStatus::ok();
}
@@ -436,16 +454,15 @@
LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
- if (!templateIt->profiles.empty()) {
- LOG(ERROR) << __func__ << ": port id " << templateId
- << " does not have dynamic profiles";
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
- }
auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
if (templateDevicePort.device.type.connection.empty()) {
LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
+ if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
+ LOG(ERROR) << __func__ << ": port id " << templateId << " is a connected device port";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
// Postpone id allocation until we ensure that there are no client errors.
connectedPort = *templateIt;
connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
@@ -468,22 +485,34 @@
}
}
- if (!mDebug.simulateDeviceConnections) {
- if (ndk::ScopedAStatus status = populateConnectedDevicePort(&connectedPort);
- !status.isOk()) {
- return status;
+ if (connectedPort.profiles.empty()) {
+ if (!mDebug.simulateDeviceConnections) {
+ RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort));
+ } else {
+ auto& connectedProfiles = getConfig().connectedProfiles;
+ if (auto connectedProfilesIt = connectedProfiles.find(templateId);
+ connectedProfilesIt != connectedProfiles.end()) {
+ connectedPort.profiles = connectedProfilesIt->second;
+ }
}
- } else {
- auto& connectedProfiles = getConfig().connectedProfiles;
- if (auto connectedProfilesIt = connectedProfiles.find(templateId);
- connectedProfilesIt != connectedProfiles.end()) {
- connectedPort.profiles = connectedProfilesIt->second;
+ if (connectedPort.profiles.empty()) {
+ LOG(ERROR) << __func__
+ << ": profiles of a connected port still empty after connecting external "
+ "device "
+ << connectedPort.toString();
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
}
}
- if (connectedPort.profiles.empty()) {
- LOG(ERROR) << "Profiles of a connected port still empty after connecting external device "
- << connectedPort.toString();
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+
+ for (auto profile : connectedPort.profiles) {
+ if (profile.channelMasks.empty()) {
+ LOG(ERROR) << __func__ << ": the profile " << profile.name << " has no channel masks";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ if (profile.sampleRates.empty()) {
+ LOG(ERROR) << __func__ << ": the profile " << profile.name << " has no sample rates";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
}
connectedPort.id = ++getConfig().nextPortId;
@@ -647,34 +676,26 @@
LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
<< in_args.bufferSizeFrames << " frames";
AudioPort* port = nullptr;
- if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
- return status;
- }
+ RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
if (port->flags.getTag() != AudioIoFlags::Tag::input) {
LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
<< " does not correspond to an input mix port";
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
StreamContext context;
- if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, nullptr,
- nullptr, &context);
- !status.isOk()) {
- return status;
- }
+ RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
+ nullptr, nullptr, &context));
context.fillDescriptor(&_aidl_return->desc);
std::shared_ptr<StreamIn> stream;
- ndk::ScopedAStatus status = getStreamInCreator(mType)(in_args.sinkMetadata, std::move(context),
- mConfig->microphones, &stream);
- if (!status.isOk()) {
- return status;
- }
+ RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata,
+ mConfig->microphones, &stream));
StreamWrapper streamWrapper(stream);
+ if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
+ RETURN_STATUS_IF_ERROR(
+ streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
+ }
AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
ANDROID_PRIORITY_AUDIO);
- auto patchIt = mPatches.find(in_args.portConfigId);
- if (patchIt != mPatches.end()) {
- streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
- }
mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
_aidl_return->stream = std::move(stream);
return ndk::ScopedAStatus::ok();
@@ -686,9 +707,7 @@
<< (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
<< " frames";
AudioPort* port = nullptr;
- if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
- return status;
- }
+ RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
if (port->flags.getTag() != AudioIoFlags::Tag::output) {
LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
<< " does not correspond to an output mix port";
@@ -709,26 +728,20 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
StreamContext context;
- if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
- isNonBlocking ? in_args.callback : nullptr,
- in_args.eventCallback, &context);
- !status.isOk()) {
- return status;
- }
+ RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
+ isNonBlocking ? in_args.callback : nullptr,
+ in_args.eventCallback, &context));
context.fillDescriptor(&_aidl_return->desc);
std::shared_ptr<StreamOut> stream;
- ndk::ScopedAStatus status = getStreamOutCreator(mType)(
- in_args.sourceMetadata, std::move(context), in_args.offloadInfo, &stream);
- if (!status.isOk()) {
- return status;
- }
+ RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata,
+ in_args.offloadInfo, &stream));
StreamWrapper streamWrapper(stream);
+ if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
+ RETURN_STATUS_IF_ERROR(
+ streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
+ }
AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
ANDROID_PRIORITY_AUDIO);
- auto patchIt = mPatches.find(in_args.portConfigId);
- if (patchIt != mPatches.end()) {
- streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
- }
mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
_aidl_return->stream = std::move(stream);
return ndk::ScopedAStatus::ok();
@@ -796,10 +809,7 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
}
-
- if (auto status = checkAudioPatchEndpointsMatch(sources, sinks); !status.isOk()) {
- return status;
- }
+ RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
auto& patches = getConfig().patches;
auto existing = patches.end();
@@ -834,13 +844,20 @@
if (existing == patches.end()) {
_aidl_return->id = getConfig().nextPatchId++;
patches.push_back(*_aidl_return);
- existing = patches.begin() + (patches.size() - 1);
} else {
oldPatch = *existing;
- *existing = *_aidl_return;
}
- registerPatch(*existing);
- updateStreamsConnectedState(oldPatch, *_aidl_return);
+ patchesBackup = mPatches;
+ registerPatch(*_aidl_return);
+ if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
+ mPatches = std::move(*patchesBackup);
+ if (existing == patches.end()) {
+ patches.pop_back();
+ } else {
+ *existing = oldPatch;
+ }
+ return status;
+ }
LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
<< _aidl_return->toString();
@@ -992,8 +1009,12 @@
auto& patches = getConfig().patches;
auto patchIt = findById<AudioPatch>(patches, in_patchId);
if (patchIt != patches.end()) {
+ auto patchesBackup = mPatches;
cleanUpPatch(patchIt->id);
- updateStreamsConnectedState(*patchIt, AudioPatch{});
+ if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
+ mPatches = std::move(patchesBackup);
+ return status;
+ }
patches.erase(patchIt);
LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
return ndk::ScopedAStatus::ok();
@@ -1120,7 +1141,7 @@
if (!mSoundDose) {
mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
}
- *_aidl_return = mSoundDose.getPtr();
+ *_aidl_return = mSoundDose.getInstance();
LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get();
return ndk::ScopedAStatus::ok();
}
@@ -1353,4 +1374,13 @@
return ndk::ScopedAStatus::ok();
}
+Module::BtProfileHandles Module::getBtProfileManagerHandles() {
+ return std::make_tuple(std::weak_ptr<IBluetooth>(), std::weak_ptr<IBluetoothA2dp>(),
+ std::weak_ptr<IBluetoothLe>());
+}
+
+ndk::ScopedAStatus Module::bluetoothParametersUpdated() {
+ return mStreams.bluetoothParametersUpdated();
+}
+
} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/ModulePrimary.cpp b/audio/aidl/default/ModulePrimary.cpp
new file mode 100644
index 0000000..9919c7f
--- /dev/null
+++ b/audio/aidl/default/ModulePrimary.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2023 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 <vector>
+
+#define LOG_TAG "AHAL_ModulePrimary"
+#include <Utils.h>
+#include <android-base/logging.h>
+
+#include "core-impl/ModulePrimary.h"
+#include "core-impl/StreamPrimary.h"
+#include "core-impl/Telephony.h"
+
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
+using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::AudioPort;
+using aidl::android::media::audio::common::AudioPortConfig;
+using aidl::android::media::audio::common::MicrophoneInfo;
+
+namespace aidl::android::hardware::audio::core {
+
+ndk::ScopedAStatus ModulePrimary::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
+ if (!mTelephony) {
+ mTelephony = ndk::SharedRefBase::make<Telephony>();
+ }
+ *_aidl_return = mTelephony.getInstance();
+ LOG(DEBUG) << __func__
+ << ": returning instance of ITelephony: " << _aidl_return->get()->asBinder().get();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModulePrimary::createInputStream(StreamContext&& context,
+ const SinkMetadata& sinkMetadata,
+ const std::vector<MicrophoneInfo>& microphones,
+ std::shared_ptr<StreamIn>* result) {
+ return createStreamInstance<StreamInPrimary>(result, std::move(context), sinkMetadata,
+ microphones);
+}
+
+ndk::ScopedAStatus ModulePrimary::createOutputStream(
+ StreamContext&& context, const SourceMetadata& sourceMetadata,
+ const std::optional<AudioOffloadInfo>& offloadInfo, std::shared_ptr<StreamOut>* result) {
+ return createStreamInstance<StreamOutPrimary>(result, std::move(context), sourceMetadata,
+ offloadInfo);
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/Stream.cpp b/audio/aidl/default/Stream.cpp
index 77b0601..f7298c0 100644
--- a/audio/aidl/default/Stream.cpp
+++ b/audio/aidl/default/Stream.cpp
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+#include <pthread.h>
+
#define LOG_TAG "AHAL_Stream"
#include <android-base/logging.h>
#include <android/binder_ibinder_platform.h>
@@ -27,12 +29,16 @@
using aidl::android::hardware::audio::common::AudioOffloadMetadata;
using aidl::android::hardware::audio::common::getChannelCount;
using aidl::android::hardware::audio::common::getFrameSizeInBytes;
+using aidl::android::hardware::audio::common::isBitPositionFlagSet;
using aidl::android::hardware::audio::common::SinkMetadata;
using aidl::android::hardware::audio::common::SourceMetadata;
using aidl::android::media::audio::common::AudioDevice;
using aidl::android::media::audio::common::AudioDualMonoMode;
+using aidl::android::media::audio::common::AudioInputFlags;
+using aidl::android::media::audio::common::AudioIoFlags;
using aidl::android::media::audio::common::AudioLatencyMode;
using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::AudioOutputFlags;
using aidl::android::media::audio::common::AudioPlaybackRate;
using aidl::android::media::audio::common::MicrophoneDynamicInfo;
using aidl::android::media::audio::common::MicrophoneInfo;
@@ -47,13 +53,19 @@
desc->reply = mReplyMQ->dupeDesc();
}
if (mDataMQ) {
- const size_t frameSize = getFrameSize();
- desc->frameSizeBytes = frameSize;
- desc->bufferSizeFrames = mDataMQ->getQuantumCount() * mDataMQ->getQuantumSize() / frameSize;
+ desc->frameSizeBytes = getFrameSize();
+ desc->bufferSizeFrames = getBufferSizeInFrames();
desc->audio.set<StreamDescriptor::AudioBuffer::Tag::fmq>(mDataMQ->dupeDesc());
}
}
+size_t StreamContext::getBufferSizeInFrames() const {
+ if (mDataMQ) {
+ return mDataMQ->getQuantumCount() * mDataMQ->getQuantumSize() / getFrameSize();
+ }
+ return 0;
+}
+
size_t StreamContext::getFrameSize() const {
return getFrameSizeInBytes(mFormat, mChannelLayout);
}
@@ -84,18 +96,27 @@
mDataMQ.reset();
}
+pid_t StreamWorkerCommonLogic::getTid() const {
+#if defined(__ANDROID__)
+ return pthread_gettid_np(pthread_self());
+#else
+ return 0;
+#endif
+}
+
std::string StreamWorkerCommonLogic::init() {
- if (mCommandMQ == nullptr) return "Command MQ is null";
- if (mReplyMQ == nullptr) return "Reply MQ is null";
- if (mDataMQ == nullptr) return "Data MQ is null";
- if (sizeof(DataBufferElement) != mDataMQ->getQuantumSize()) {
- return "Unexpected Data MQ quantum size: " + std::to_string(mDataMQ->getQuantumSize());
+ if (mContext->getCommandMQ() == nullptr) return "Command MQ is null";
+ if (mContext->getReplyMQ() == nullptr) return "Reply MQ is null";
+ StreamContext::DataMQ* const dataMQ = mContext->getDataMQ();
+ if (dataMQ == nullptr) return "Data MQ is null";
+ if (sizeof(DataBufferElement) != dataMQ->getQuantumSize()) {
+ return "Unexpected Data MQ quantum size: " + std::to_string(dataMQ->getQuantumSize());
}
- mDataBufferSize = mDataMQ->getQuantumCount() * mDataMQ->getQuantumSize();
+ mDataBufferSize = dataMQ->getQuantumCount() * dataMQ->getQuantumSize();
mDataBuffer.reset(new (std::nothrow) DataBufferElement[mDataBufferSize]);
if (mDataBuffer == nullptr) {
return "Failed to allocate data buffer for element count " +
- std::to_string(mDataMQ->getQuantumCount()) +
+ std::to_string(dataMQ->getQuantumCount()) +
", size in bytes: " + std::to_string(mDataBufferSize);
}
if (::android::status_t status = mDriver->init(); status != STATUS_OK) {
@@ -108,12 +129,14 @@
bool isConnected) const {
reply->status = STATUS_OK;
if (isConnected) {
- reply->observable.frames = mFrameCount;
+ reply->observable.frames = mContext->getFrameCount();
reply->observable.timeNs = ::android::elapsedRealtimeNano();
- } else {
- reply->observable.frames = StreamDescriptor::Position::UNKNOWN;
- reply->observable.timeNs = StreamDescriptor::Position::UNKNOWN;
+ if (auto status = mDriver->refinePosition(&reply->observable); status == ::android::OK) {
+ return;
+ }
}
+ reply->observable.frames = StreamDescriptor::Position::UNKNOWN;
+ reply->observable.timeNs = StreamDescriptor::Position::UNKNOWN;
}
void StreamWorkerCommonLogic::populateReplyWrongState(
@@ -133,7 +156,7 @@
// TODO: Add a delay for transitions of async operations when/if they added.
StreamDescriptor::Command command{};
- if (!mCommandMQ->readBlocking(&command, 1)) {
+ if (!mContext->getCommandMQ()->readBlocking(&command, 1)) {
LOG(ERROR) << __func__ << ": reading of command from MQ failed";
mState = StreamDescriptor::State::ERROR;
return Status::ABORT;
@@ -151,7 +174,8 @@
switch (command.getTag()) {
case Tag::halReservedExit:
if (const int32_t cookie = command.get<Tag::halReservedExit>();
- cookie == mInternalCommandCookie) {
+ cookie == (mContext->getInternalCommandCookie() ^ getTid())) {
+ mDriver->shutdown();
setClosed();
// This is an internal command, no need to reply.
return Status::EXIT;
@@ -165,10 +189,15 @@
case Tag::start:
if (mState == StreamDescriptor::State::STANDBY ||
mState == StreamDescriptor::State::DRAINING) {
- populateReply(&reply, mIsConnected);
- mState = mState == StreamDescriptor::State::STANDBY
- ? StreamDescriptor::State::IDLE
- : StreamDescriptor::State::ACTIVE;
+ if (::android::status_t status = mDriver->start(); status == ::android::OK) {
+ populateReply(&reply, mIsConnected);
+ mState = mState == StreamDescriptor::State::STANDBY
+ ? StreamDescriptor::State::IDLE
+ : StreamDescriptor::State::ACTIVE;
+ } else {
+ LOG(ERROR) << __func__ << ": start failed: " << status;
+ mState = StreamDescriptor::State::ERROR;
+ }
} else {
populateReplyWrongState(&reply, command);
}
@@ -223,8 +252,8 @@
break;
case Tag::standby:
if (mState == StreamDescriptor::State::IDLE) {
+ populateReply(&reply, mIsConnected);
if (::android::status_t status = mDriver->standby(); status == ::android::OK) {
- populateReply(&reply, mIsConnected);
mState = StreamDescriptor::State::STANDBY;
} else {
LOG(ERROR) << __func__ << ": standby failed: " << status;
@@ -263,7 +292,7 @@
}
reply.state = mState;
LOG(severity) << __func__ << ": writing reply " << reply.toString();
- if (!mReplyMQ->writeBlocking(&reply, 1)) {
+ if (!mContext->getReplyMQ()->writeBlocking(&reply, 1)) {
LOG(ERROR) << __func__ << ": writing of reply " << reply.toString() << " to MQ failed";
mState = StreamDescriptor::State::ERROR;
return Status::ABORT;
@@ -272,14 +301,16 @@
}
bool StreamInWorkerLogic::read(size_t clientSize, StreamDescriptor::Reply* reply) {
- const size_t byteCount = std::min({clientSize, mDataMQ->availableToWrite(), mDataBufferSize});
+ StreamContext::DataMQ* const dataMQ = mContext->getDataMQ();
+ const size_t byteCount = std::min({clientSize, dataMQ->availableToWrite(), mDataBufferSize});
const bool isConnected = mIsConnected;
+ const size_t frameSize = mContext->getFrameSize();
size_t actualFrameCount = 0;
bool fatal = false;
int32_t latency = Module::kLatencyMs;
if (isConnected) {
- if (::android::status_t status = mDriver->transfer(
- mDataBuffer.get(), byteCount / mFrameSize, &actualFrameCount, &latency);
+ if (::android::status_t status = mDriver->transfer(mDataBuffer.get(), byteCount / frameSize,
+ &actualFrameCount, &latency);
status != ::android::OK) {
fatal = true;
LOG(ERROR) << __func__ << ": read failed: " << status;
@@ -287,17 +318,16 @@
} else {
usleep(3000); // Simulate blocking transfer delay.
for (size_t i = 0; i < byteCount; ++i) mDataBuffer[i] = 0;
- actualFrameCount = byteCount / mFrameSize;
+ actualFrameCount = byteCount / frameSize;
}
- const size_t actualByteCount = actualFrameCount * mFrameSize;
- if (bool success =
- actualByteCount > 0 ? mDataMQ->write(&mDataBuffer[0], actualByteCount) : true;
+ const size_t actualByteCount = actualFrameCount * frameSize;
+ if (bool success = actualByteCount > 0 ? dataMQ->write(&mDataBuffer[0], actualByteCount) : true;
success) {
LOG(VERBOSE) << __func__ << ": writing of " << actualByteCount << " bytes into data MQ"
<< " succeeded; connected? " << isConnected;
// Frames are provided and counted regardless of connection status.
reply->fmqByteCount += actualByteCount;
- mFrameCount += actualFrameCount;
+ mContext->advanceFrameCount(actualFrameCount);
populateReply(reply, isConnected);
} else {
LOG(WARNING) << __func__ << ": writing of " << actualByteCount
@@ -316,7 +346,8 @@
if (auto stateDurationMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - mTransientStateStart);
stateDurationMs >= mTransientStateDelayMs) {
- if (mAsyncCallback == nullptr) {
+ std::shared_ptr<IStreamCallback> asyncCallback = mContext->getAsyncCallback();
+ if (asyncCallback == nullptr) {
// In blocking mode, mState can only be DRAINING.
mState = StreamDescriptor::State::IDLE;
} else {
@@ -324,13 +355,13 @@
// drain or transfer completion. In the stub, we switch unconditionally.
if (mState == StreamDescriptor::State::DRAINING) {
mState = StreamDescriptor::State::IDLE;
- ndk::ScopedAStatus status = mAsyncCallback->onDrainReady();
+ ndk::ScopedAStatus status = asyncCallback->onDrainReady();
if (!status.isOk()) {
LOG(ERROR) << __func__ << ": error from onDrainReady: " << status;
}
} else {
mState = StreamDescriptor::State::ACTIVE;
- ndk::ScopedAStatus status = mAsyncCallback->onTransferReady();
+ ndk::ScopedAStatus status = asyncCallback->onTransferReady();
if (!status.isOk()) {
LOG(ERROR) << __func__ << ": error from onTransferReady: " << status;
}
@@ -344,7 +375,7 @@
}
StreamDescriptor::Command command{};
- if (!mCommandMQ->readBlocking(&command, 1)) {
+ if (!mContext->getCommandMQ()->readBlocking(&command, 1)) {
LOG(ERROR) << __func__ << ": reading of command from MQ failed";
mState = StreamDescriptor::State::ERROR;
return Status::ABORT;
@@ -363,7 +394,8 @@
switch (command.getTag()) {
case Tag::halReservedExit:
if (const int32_t cookie = command.get<Tag::halReservedExit>();
- cookie == mInternalCommandCookie) {
+ cookie == (mContext->getInternalCommandCookie() ^ getTid())) {
+ mDriver->shutdown();
setClosed();
// This is an internal command, no need to reply.
return Status::EXIT;
@@ -375,26 +407,36 @@
populateReply(&reply, mIsConnected);
break;
case Tag::start: {
- bool commandAccepted = true;
+ std::optional<StreamDescriptor::State> nextState;
switch (mState) {
case StreamDescriptor::State::STANDBY:
- mState = StreamDescriptor::State::IDLE;
+ nextState = StreamDescriptor::State::IDLE;
break;
case StreamDescriptor::State::PAUSED:
- mState = StreamDescriptor::State::ACTIVE;
+ nextState = StreamDescriptor::State::ACTIVE;
break;
case StreamDescriptor::State::DRAIN_PAUSED:
- switchToTransientState(StreamDescriptor::State::DRAINING);
+ nextState = StreamDescriptor::State::DRAINING;
break;
case StreamDescriptor::State::TRANSFER_PAUSED:
- switchToTransientState(StreamDescriptor::State::TRANSFERRING);
+ nextState = StreamDescriptor::State::TRANSFERRING;
break;
default:
populateReplyWrongState(&reply, command);
- commandAccepted = false;
}
- if (commandAccepted) {
- populateReply(&reply, mIsConnected);
+ if (nextState.has_value()) {
+ if (::android::status_t status = mDriver->start(); status == ::android::OK) {
+ populateReply(&reply, mIsConnected);
+ if (*nextState == StreamDescriptor::State::IDLE ||
+ *nextState == StreamDescriptor::State::ACTIVE) {
+ mState = *nextState;
+ } else {
+ switchToTransientState(*nextState);
+ }
+ } else {
+ LOG(ERROR) << __func__ << ": start failed: " << status;
+ mState = StreamDescriptor::State::ERROR;
+ }
}
} break;
case Tag::burst:
@@ -407,10 +449,11 @@
if (!write(fmqByteCount, &reply)) {
mState = StreamDescriptor::State::ERROR;
}
+ std::shared_ptr<IStreamCallback> asyncCallback = mContext->getAsyncCallback();
if (mState == StreamDescriptor::State::STANDBY ||
mState == StreamDescriptor::State::DRAIN_PAUSED ||
mState == StreamDescriptor::State::PAUSED) {
- if (mAsyncCallback == nullptr ||
+ if (asyncCallback == nullptr ||
mState != StreamDescriptor::State::DRAIN_PAUSED) {
mState = StreamDescriptor::State::PAUSED;
} else {
@@ -419,7 +462,7 @@
} else if (mState == StreamDescriptor::State::IDLE ||
mState == StreamDescriptor::State::DRAINING ||
mState == StreamDescriptor::State::ACTIVE) {
- if (mAsyncCallback == nullptr || reply.fmqByteCount == fmqByteCount) {
+ if (asyncCallback == nullptr || reply.fmqByteCount == fmqByteCount) {
mState = StreamDescriptor::State::ACTIVE;
} else {
switchToTransientState(StreamDescriptor::State::TRANSFERRING);
@@ -441,7 +484,8 @@
if (::android::status_t status = mDriver->drain(mode);
status == ::android::OK) {
populateReply(&reply, mIsConnected);
- if (mState == StreamDescriptor::State::ACTIVE && mForceSynchronousDrain) {
+ if (mState == StreamDescriptor::State::ACTIVE &&
+ mContext->getForceSynchronousDrain()) {
mState = StreamDescriptor::State::IDLE;
} else {
switchToTransientState(StreamDescriptor::State::DRAINING);
@@ -462,8 +506,8 @@
break;
case Tag::standby:
if (mState == StreamDescriptor::State::IDLE) {
+ populateReply(&reply, mIsConnected);
if (::android::status_t status = mDriver->standby(); status == ::android::OK) {
- populateReply(&reply, mIsConnected);
mState = StreamDescriptor::State::STANDBY;
} else {
LOG(ERROR) << __func__ << ": standby failed: " << status;
@@ -516,7 +560,7 @@
}
reply.state = mState;
LOG(severity) << __func__ << ": writing reply " << reply.toString();
- if (!mReplyMQ->writeBlocking(&reply, 1)) {
+ if (!mContext->getReplyMQ()->writeBlocking(&reply, 1)) {
LOG(ERROR) << __func__ << ": writing of reply " << reply.toString() << " to MQ failed";
mState = StreamDescriptor::State::ERROR;
return Status::ABORT;
@@ -525,38 +569,40 @@
}
bool StreamOutWorkerLogic::write(size_t clientSize, StreamDescriptor::Reply* reply) {
- const size_t readByteCount = mDataMQ->availableToRead();
+ StreamContext::DataMQ* const dataMQ = mContext->getDataMQ();
+ const size_t readByteCount = dataMQ->availableToRead();
+ const size_t frameSize = mContext->getFrameSize();
bool fatal = false;
int32_t latency = Module::kLatencyMs;
- if (bool success = readByteCount > 0 ? mDataMQ->read(&mDataBuffer[0], readByteCount) : true) {
+ if (bool success = readByteCount > 0 ? dataMQ->read(&mDataBuffer[0], readByteCount) : true) {
const bool isConnected = mIsConnected;
LOG(VERBOSE) << __func__ << ": reading of " << readByteCount << " bytes from data MQ"
<< " succeeded; connected? " << isConnected;
// Amount of data that the HAL module is going to actually use.
size_t byteCount = std::min({clientSize, readByteCount, mDataBufferSize});
- if (byteCount >= mFrameSize && mForceTransientBurst) {
+ if (byteCount >= frameSize && mContext->getForceTransientBurst()) {
// In order to prevent the state machine from going to ACTIVE state,
// simulate partial write.
- byteCount -= mFrameSize;
+ byteCount -= frameSize;
}
size_t actualFrameCount = 0;
if (isConnected) {
if (::android::status_t status = mDriver->transfer(
- mDataBuffer.get(), byteCount / mFrameSize, &actualFrameCount, &latency);
+ mDataBuffer.get(), byteCount / frameSize, &actualFrameCount, &latency);
status != ::android::OK) {
fatal = true;
LOG(ERROR) << __func__ << ": write failed: " << status;
}
} else {
- if (mAsyncCallback == nullptr) {
+ if (mContext->getAsyncCallback() == nullptr) {
usleep(3000); // Simulate blocking transfer delay.
}
- actualFrameCount = byteCount / mFrameSize;
+ actualFrameCount = byteCount / frameSize;
}
- const size_t actualByteCount = actualFrameCount * mFrameSize;
+ const size_t actualByteCount = actualFrameCount * frameSize;
// Frames are consumed and counted regardless of the connection status.
reply->fmqByteCount += actualByteCount;
- mFrameCount += actualFrameCount;
+ mContext->advanceFrameCount(actualFrameCount);
populateReply(reply, isConnected);
} else {
LOG(WARNING) << __func__ << ": reading of " << readByteCount
@@ -567,8 +613,7 @@
return !fatal;
}
-template <class Metadata>
-StreamCommonImpl<Metadata>::~StreamCommonImpl() {
+StreamCommonImpl::~StreamCommonImpl() {
if (!isClosed()) {
LOG(ERROR) << __func__ << ": stream was not closed prior to destruction, resource leak";
stopWorker();
@@ -576,52 +621,65 @@
}
}
-template <class Metadata>
-void StreamCommonImpl<Metadata>::createStreamCommon(
+ndk::ScopedAStatus StreamCommonImpl::initInstance(
const std::shared_ptr<StreamCommonInterface>& delegate) {
- if (mCommon != nullptr) {
- LOG(FATAL) << __func__ << ": attempting to create the common interface twice";
+ mCommon = ndk::SharedRefBase::make<StreamCommonDelegator>(delegate);
+ if (!mWorker->start()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
}
- mCommon = ndk::SharedRefBase::make<StreamCommon>(delegate);
- mCommonBinder = mCommon->asBinder();
- AIBinder_setMinSchedulerPolicy(mCommonBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
+ if (auto flags = getContext().getFlags();
+ (flags.getTag() == AudioIoFlags::Tag::input &&
+ isBitPositionFlagSet(flags.template get<AudioIoFlags::Tag::input>(),
+ AudioInputFlags::FAST)) ||
+ (flags.getTag() == AudioIoFlags::Tag::output &&
+ isBitPositionFlagSet(flags.template get<AudioIoFlags::Tag::output>(),
+ AudioOutputFlags::FAST))) {
+ // FAST workers should be run with a SCHED_FIFO scheduler, however the host process
+ // might be lacking the capability to request it, thus a failure to set is not an error.
+ pid_t workerTid = mWorker->getTid();
+ if (workerTid > 0) {
+ struct sched_param param;
+ param.sched_priority = 3; // Must match SchedulingPolicyService.PRIORITY_MAX (Java).
+ if (sched_setscheduler(workerTid, SCHED_FIFO | SCHED_RESET_ON_FORK, ¶m) != 0) {
+ PLOG(WARNING) << __func__ << ": failed to set FIFO scheduler for a fast thread";
+ }
+ } else {
+ LOG(WARNING) << __func__ << ": invalid worker tid: " << workerTid;
+ }
+ }
+ return ndk::ScopedAStatus::ok();
}
-template <class Metadata>
-ndk::ScopedAStatus StreamCommonImpl<Metadata>::getStreamCommon(
+ndk::ScopedAStatus StreamCommonImpl::getStreamCommonCommon(
std::shared_ptr<IStreamCommon>* _aidl_return) {
- if (mCommon == nullptr) {
+ if (!mCommon) {
LOG(FATAL) << __func__ << ": the common interface was not created";
}
- *_aidl_return = mCommon;
+ *_aidl_return = mCommon.getInstance();
LOG(DEBUG) << __func__ << ": returning " << _aidl_return->get()->asBinder().get();
return ndk::ScopedAStatus::ok();
}
-template <class Metadata>
-ndk::ScopedAStatus StreamCommonImpl<Metadata>::updateHwAvSyncId(int32_t in_hwAvSyncId) {
+ndk::ScopedAStatus StreamCommonImpl::updateHwAvSyncId(int32_t in_hwAvSyncId) {
LOG(DEBUG) << __func__ << ": id " << in_hwAvSyncId;
return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
-template <class Metadata>
-ndk::ScopedAStatus StreamCommonImpl<Metadata>::getVendorParameters(
+ndk::ScopedAStatus StreamCommonImpl::getVendorParameters(
const std::vector<std::string>& in_ids, std::vector<VendorParameter>* _aidl_return) {
LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
(void)_aidl_return;
return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
-template <class Metadata>
-ndk::ScopedAStatus StreamCommonImpl<Metadata>::setVendorParameters(
+ndk::ScopedAStatus StreamCommonImpl::setVendorParameters(
const std::vector<VendorParameter>& in_parameters, bool in_async) {
LOG(DEBUG) << __func__ << ": parameters count " << in_parameters.size()
<< ", async: " << in_async;
return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
-template <class Metadata>
-ndk::ScopedAStatus StreamCommonImpl<Metadata>::addEffect(
+ndk::ScopedAStatus StreamCommonImpl::addEffect(
const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
if (in_effect == nullptr) {
LOG(DEBUG) << __func__ << ": null effect";
@@ -631,8 +689,7 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
-template <class Metadata>
-ndk::ScopedAStatus StreamCommonImpl<Metadata>::removeEffect(
+ndk::ScopedAStatus StreamCommonImpl::removeEffect(
const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
if (in_effect == nullptr) {
LOG(DEBUG) << __func__ << ": null effect";
@@ -642,16 +699,14 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
-template <class Metadata>
-ndk::ScopedAStatus StreamCommonImpl<Metadata>::close() {
+ndk::ScopedAStatus StreamCommonImpl::close() {
LOG(DEBUG) << __func__;
if (!isClosed()) {
stopWorker();
LOG(DEBUG) << __func__ << ": joining the worker thread...";
mWorker->stop();
LOG(DEBUG) << __func__ << ": worker thread joined";
- mContext.reset();
- mWorker->setClosed();
+ onClose(mWorker->setClosed());
return ndk::ScopedAStatus::ok();
} else {
LOG(ERROR) << __func__ << ": stream was already closed";
@@ -659,8 +714,7 @@
}
}
-template <class Metadata>
-ndk::ScopedAStatus StreamCommonImpl<Metadata>::prepareToClose() {
+ndk::ScopedAStatus StreamCommonImpl::prepareToClose() {
LOG(DEBUG) << __func__;
if (!isClosed()) {
return ndk::ScopedAStatus::ok();
@@ -669,12 +723,11 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
}
-template <class Metadata>
-void StreamCommonImpl<Metadata>::stopWorker() {
+void StreamCommonImpl::stopWorker() {
if (auto commandMQ = mContext.getCommandMQ(); commandMQ != nullptr) {
LOG(DEBUG) << __func__ << ": asking the worker to exit...";
auto cmd = StreamDescriptor::Command::make<StreamDescriptor::Command::Tag::halReservedExit>(
- mContext.getInternalCommandCookie());
+ mContext.getInternalCommandCookie() ^ mWorker->getTid());
// Note: never call 'pause' and 'resume' methods of StreamWorker
// in the HAL implementation. These methods are to be used by
// the client side only. Preventing the worker loop from running
@@ -686,10 +739,12 @@
}
}
-template <class Metadata>
-ndk::ScopedAStatus StreamCommonImpl<Metadata>::updateMetadata(const Metadata& metadata) {
+ndk::ScopedAStatus StreamCommonImpl::updateMetadataCommon(const Metadata& metadata) {
LOG(DEBUG) << __func__;
if (!isClosed()) {
+ if (metadata.index() != mMetadata.index()) {
+ LOG(FATAL) << __func__ << ": changing metadata variant is not allowed";
+ }
mMetadata = metadata;
return ndk::ScopedAStatus::ok();
}
@@ -697,15 +752,18 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
}
-// static
-ndk::ScopedAStatus StreamIn::initInstance(const std::shared_ptr<StreamIn>& stream) {
- if (auto status = stream->init(); !status.isOk()) {
- return status;
- }
- stream->createStreamCommon(stream);
+ndk::ScopedAStatus StreamCommonImpl::setConnectedDevices(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
+ mWorker->setIsConnected(!devices.empty());
+ mConnectedDevices = devices;
return ndk::ScopedAStatus::ok();
}
+ndk::ScopedAStatus StreamCommonImpl::bluetoothParametersUpdated() {
+ LOG(DEBUG) << __func__;
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
namespace {
static std::map<AudioDevice, std::string> transformMicrophones(
const std::vector<MicrophoneInfo>& microphones) {
@@ -716,22 +774,22 @@
}
} // namespace
-StreamIn::StreamIn(const SinkMetadata& sinkMetadata, StreamContext&& context,
- const DriverInterface::CreateInstance& createDriver,
- const StreamWorkerInterface::CreateInstance& createWorker,
- const std::vector<MicrophoneInfo>& microphones)
- : StreamCommonImpl<SinkMetadata>(sinkMetadata, std::move(context), createDriver, createWorker),
- mMicrophones(transformMicrophones(microphones)) {
+StreamIn::StreamIn(StreamContext&& context, const std::vector<MicrophoneInfo>& microphones)
+ : mContextInstance(std::move(context)), mMicrophones(transformMicrophones(microphones)) {
LOG(DEBUG) << __func__;
}
+void StreamIn::defaultOnClose() {
+ mContextInstance.reset();
+}
+
ndk::ScopedAStatus StreamIn::getActiveMicrophones(
std::vector<MicrophoneDynamicInfo>* _aidl_return) {
std::vector<MicrophoneDynamicInfo> result;
std::vector<MicrophoneDynamicInfo::ChannelMapping> channelMapping{
- getChannelCount(mContext.getChannelLayout()),
+ getChannelCount(getContext().getChannelLayout()),
MicrophoneDynamicInfo::ChannelMapping::DIRECT};
- for (auto it = mConnectedDevices.begin(); it != mConnectedDevices.end(); ++it) {
+ for (auto it = getConnectedDevices().begin(); it != getConnectedDevices().end(); ++it) {
if (auto micIt = mMicrophones.find(*it); micIt != mMicrophones.end()) {
MicrophoneDynamicInfo dynMic;
dynMic.id = micIt->second;
@@ -777,25 +835,41 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
-// static
-ndk::ScopedAStatus StreamOut::initInstance(const std::shared_ptr<StreamOut>& stream) {
- if (auto status = stream->init(); !status.isOk()) {
- return status;
- }
- stream->createStreamCommon(stream);
+StreamInHwGainHelper::StreamInHwGainHelper(const StreamContext* context)
+ : mChannelCount(getChannelCount(context->getChannelLayout())) {}
+
+ndk::ScopedAStatus StreamInHwGainHelper::getHwGainImpl(std::vector<float>* _aidl_return) {
+ *_aidl_return = mHwGains;
+ LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
return ndk::ScopedAStatus::ok();
}
-StreamOut::StreamOut(const SourceMetadata& sourceMetadata, StreamContext&& context,
- const DriverInterface::CreateInstance& createDriver,
- const StreamWorkerInterface::CreateInstance& createWorker,
- const std::optional<AudioOffloadInfo>& offloadInfo)
- : StreamCommonImpl<SourceMetadata>(sourceMetadata, std::move(context), createDriver,
- createWorker),
- mOffloadInfo(offloadInfo) {
+ndk::ScopedAStatus StreamInHwGainHelper::setHwGainImpl(const std::vector<float>& in_channelGains) {
+ LOG(DEBUG) << __func__ << ": gains " << ::android::internal::ToString(in_channelGains);
+ if (in_channelGains.size() != mChannelCount) {
+ LOG(ERROR) << __func__
+ << ": channel count does not match stream channel count: " << mChannelCount;
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ for (float gain : in_channelGains) {
+ if (gain < StreamIn::HW_GAIN_MIN || gain > StreamIn::HW_GAIN_MAX) {
+ LOG(ERROR) << __func__ << ": gain value out of range: " << gain;
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ }
+ mHwGains = in_channelGains;
+ return ndk::ScopedAStatus::ok();
+}
+
+StreamOut::StreamOut(StreamContext&& context, const std::optional<AudioOffloadInfo>& offloadInfo)
+ : mContextInstance(std::move(context)), mOffloadInfo(offloadInfo) {
LOG(DEBUG) << __func__;
}
+void StreamOut::defaultOnClose() {
+ mContextInstance.reset();
+}
+
ndk::ScopedAStatus StreamOut::updateOffloadMetadata(
const AudioOffloadMetadata& in_offloadMetadata) {
LOG(DEBUG) << __func__;
@@ -892,4 +966,31 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
+StreamOutHwVolumeHelper::StreamOutHwVolumeHelper(const StreamContext* context)
+ : mChannelCount(getChannelCount(context->getChannelLayout())) {}
+
+ndk::ScopedAStatus StreamOutHwVolumeHelper::getHwVolumeImpl(std::vector<float>* _aidl_return) {
+ *_aidl_return = mHwVolumes;
+ LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamOutHwVolumeHelper::setHwVolumeImpl(
+ const std::vector<float>& in_channelVolumes) {
+ LOG(DEBUG) << __func__ << ": volumes " << ::android::internal::ToString(in_channelVolumes);
+ if (in_channelVolumes.size() != mChannelCount) {
+ LOG(ERROR) << __func__
+ << ": channel count does not match stream channel count: " << mChannelCount;
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ for (float volume : in_channelVolumes) {
+ if (volume < StreamOut::HW_VOLUME_MIN || volume > StreamOut::HW_VOLUME_MAX) {
+ LOG(ERROR) << __func__ << ": volume value out of range: " << volume;
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ }
+ mHwVolumes = in_channelVolumes;
+ return ndk::ScopedAStatus::ok();
+}
+
} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/StreamStub.cpp b/audio/aidl/default/StreamStub.cpp
deleted file mode 100644
index 2467320..0000000
--- a/audio/aidl/default/StreamStub.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2023 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 <cmath>
-
-#define LOG_TAG "AHAL_Stream"
-#include <android-base/logging.h>
-#include <audio_utils/clock.h>
-
-#include "core-impl/Module.h"
-#include "core-impl/StreamStub.h"
-
-using aidl::android::hardware::audio::common::SinkMetadata;
-using aidl::android::hardware::audio::common::SourceMetadata;
-using aidl::android::media::audio::common::AudioDevice;
-using aidl::android::media::audio::common::AudioOffloadInfo;
-using aidl::android::media::audio::common::MicrophoneInfo;
-
-namespace aidl::android::hardware::audio::core {
-
-DriverStub::DriverStub(const StreamContext& context, bool isInput)
- : mFrameSizeBytes(context.getFrameSize()),
- mSampleRate(context.getSampleRate()),
- mIsAsynchronous(!!context.getAsyncCallback()),
- mIsInput(isInput) {}
-
-::android::status_t DriverStub::init() {
- usleep(500);
- return ::android::OK;
-}
-
-::android::status_t DriverStub::drain(StreamDescriptor::DrainMode) {
- usleep(500);
- return ::android::OK;
-}
-
-::android::status_t DriverStub::flush() {
- usleep(500);
- return ::android::OK;
-}
-
-::android::status_t DriverStub::pause() {
- usleep(500);
- return ::android::OK;
-}
-
-::android::status_t DriverStub::transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
- int32_t* latencyMs) {
- static constexpr float kMicrosPerSecond = MICROS_PER_SECOND;
- static constexpr float kScaleFactor = .8f;
- if (mIsAsynchronous) {
- usleep(500);
- } else {
- const size_t delayUs = static_cast<size_t>(
- std::roundf(kScaleFactor * frameCount * kMicrosPerSecond / mSampleRate));
- usleep(delayUs);
- }
- if (mIsInput) {
- uint8_t* byteBuffer = static_cast<uint8_t*>(buffer);
- for (size_t i = 0; i < frameCount * mFrameSizeBytes; ++i) {
- byteBuffer[i] = std::rand() % 255;
- }
- }
- *actualFrameCount = frameCount;
- *latencyMs = Module::kLatencyMs;
- return ::android::OK;
-}
-
-::android::status_t DriverStub::standby() {
- usleep(500);
- return ::android::OK;
-}
-
-::android::status_t DriverStub::setConnectedDevices(
- const std::vector<AudioDevice>& connectedDevices __unused) {
- usleep(500);
- return ::android::OK;
-}
-
-// static
-ndk::ScopedAStatus StreamInStub::createInstance(const SinkMetadata& sinkMetadata,
- StreamContext&& context,
- const std::vector<MicrophoneInfo>& microphones,
- std::shared_ptr<StreamIn>* result) {
- std::shared_ptr<StreamIn> stream =
- ndk::SharedRefBase::make<StreamInStub>(sinkMetadata, std::move(context), microphones);
- if (auto status = initInstance(stream); !status.isOk()) {
- return status;
- }
- *result = std::move(stream);
- return ndk::ScopedAStatus::ok();
-}
-
-StreamInStub::StreamInStub(const SinkMetadata& sinkMetadata, StreamContext&& context,
- const std::vector<MicrophoneInfo>& microphones)
- : StreamIn(
- sinkMetadata, std::move(context),
- [](const StreamContext& ctx) -> DriverInterface* {
- return new DriverStub(ctx, true /*isInput*/);
- },
- [](const StreamContext& ctx, DriverInterface* driver) -> StreamWorkerInterface* {
- // The default worker implementation is used.
- return new StreamInWorker(ctx, driver);
- },
- microphones) {}
-
-// static
-ndk::ScopedAStatus StreamOutStub::createInstance(const SourceMetadata& sourceMetadata,
- StreamContext&& context,
- const std::optional<AudioOffloadInfo>& offloadInfo,
- std::shared_ptr<StreamOut>* result) {
- std::shared_ptr<StreamOut> stream = ndk::SharedRefBase::make<StreamOutStub>(
- sourceMetadata, std::move(context), offloadInfo);
- if (auto status = initInstance(stream); !status.isOk()) {
- return status;
- }
- *result = std::move(stream);
- return ndk::ScopedAStatus::ok();
-}
-
-StreamOutStub::StreamOutStub(const SourceMetadata& sourceMetadata, StreamContext&& context,
- const std::optional<AudioOffloadInfo>& offloadInfo)
- : StreamOut(
- sourceMetadata, std::move(context),
- [](const StreamContext& ctx) -> DriverInterface* {
- return new DriverStub(ctx, false /*isInput*/);
- },
- [](const StreamContext& ctx, DriverInterface* driver) -> StreamWorkerInterface* {
- // The default worker implementation is used.
- return new StreamOutWorker(ctx, driver);
- },
- offloadInfo) {}
-
-} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/StreamSwitcher.cpp b/audio/aidl/default/StreamSwitcher.cpp
new file mode 100644
index 0000000..8ba15a8
--- /dev/null
+++ b/audio/aidl/default/StreamSwitcher.cpp
@@ -0,0 +1,263 @@
+/*
+ * Copyright (C) 2023 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 <limits>
+
+#define LOG_TAG "AHAL_StreamSwitcher"
+
+#include <Utils.h>
+#include <android-base/logging.h>
+#include <error/expected_utils.h>
+
+#include "core-impl/StreamStub.h"
+#include "core-impl/StreamSwitcher.h"
+
+using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::media::audio::common::AudioDevice;
+
+namespace aidl::android::hardware::audio::core {
+
+StreamSwitcher::StreamSwitcher(StreamContext* context, const Metadata& metadata)
+ : mContext(context),
+ mMetadata(metadata),
+ mStream(new InnerStreamWrapper<StreamStub>(context, mMetadata)) {}
+
+ndk::ScopedAStatus StreamSwitcher::closeCurrentStream(bool validateStreamState) {
+ if (!mStream) return ndk::ScopedAStatus::ok();
+ RETURN_STATUS_IF_ERROR(mStream->prepareToClose());
+ RETURN_STATUS_IF_ERROR(mStream->close());
+ if (validateStreamState && !isValidClosingStreamState(mStream->getStatePriorToClosing())) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ mStream.reset();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamSwitcher::close() {
+ if (mStream != nullptr) {
+ auto status = closeCurrentStream(false /*validateStreamState*/);
+ // The actual state is irrelevant since only StreamSwitcher cares about it.
+ onClose(StreamDescriptor::State::STANDBY);
+ return status;
+ }
+ LOG(ERROR) << __func__ << ": stream was already closed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+}
+
+ndk::ScopedAStatus StreamSwitcher::prepareToClose() {
+ if (mStream != nullptr) {
+ return mStream->prepareToClose();
+ }
+ LOG(ERROR) << __func__ << ": stream was closed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+}
+
+ndk::ScopedAStatus StreamSwitcher::updateHwAvSyncId(int32_t in_hwAvSyncId) {
+ if (mStream == nullptr) {
+ LOG(ERROR) << __func__ << ": stream was closed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ RETURN_STATUS_IF_ERROR(mStream->updateHwAvSyncId(in_hwAvSyncId));
+ mHwAvSyncId = in_hwAvSyncId;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamSwitcher::getVendorParameters(const std::vector<std::string>& in_ids,
+ std::vector<VendorParameter>* _aidl_return) {
+ if (mStream == nullptr) {
+ LOG(ERROR) << __func__ << ": stream was closed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ if (mIsStubStream) {
+ LOG(ERROR) << __func__ << ": the stream is not connected";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ return mStream->getVendorParameters(in_ids, _aidl_return);
+}
+
+ndk::ScopedAStatus StreamSwitcher::setVendorParameters(
+ const std::vector<VendorParameter>& in_parameters, bool in_async) {
+ if (mStream == nullptr) {
+ LOG(ERROR) << __func__ << ": stream was closed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ if (mIsStubStream) {
+ mMissedParameters.emplace_back(in_parameters, in_async);
+ return ndk::ScopedAStatus::ok();
+ }
+ return mStream->setVendorParameters(in_parameters, in_async);
+}
+
+ndk::ScopedAStatus StreamSwitcher::addEffect(const std::shared_ptr<IEffect>& in_effect) {
+ if (in_effect == nullptr) {
+ LOG(DEBUG) << __func__ << ": null effect";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ if (mStream == nullptr) {
+ LOG(ERROR) << __func__ << ": stream was closed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ if (!mIsStubStream) {
+ RETURN_STATUS_IF_ERROR(mStream->addEffect(in_effect));
+ }
+ mEffects.push_back(in_effect);
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamSwitcher::removeEffect(const std::shared_ptr<IEffect>& in_effect) {
+ if (in_effect == nullptr) {
+ LOG(DEBUG) << __func__ << ": null effect";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ if (mStream == nullptr) {
+ LOG(ERROR) << __func__ << ": stream was closed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ for (auto it = mEffects.begin(); it != mEffects.end(); ++it) {
+ if ((*it)->asBinder() == in_effect->asBinder()) {
+ mEffects.erase(it);
+ break;
+ }
+ }
+ return !mIsStubStream ? mStream->removeEffect(in_effect) : ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamSwitcher::getStreamCommonCommon(
+ std::shared_ptr<IStreamCommon>* _aidl_return) {
+ if (!mCommon) {
+ LOG(FATAL) << __func__ << ": the common interface was not created";
+ }
+ *_aidl_return = mCommon.getInstance();
+ LOG(DEBUG) << __func__ << ": returning " << _aidl_return->get()->asBinder().get();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamSwitcher::updateMetadataCommon(const Metadata& metadata) {
+ if (mStream == nullptr) {
+ LOG(ERROR) << __func__ << ": stream was closed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ mMetadata = metadata;
+ return !mIsStubStream ? mStream->updateMetadataCommon(metadata) : ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamSwitcher::initInstance(
+ const std::shared_ptr<StreamCommonInterface>& delegate) {
+ mCommon = ndk::SharedRefBase::make<StreamCommonDelegator>(delegate);
+ // The delegate is null because StreamSwitcher handles IStreamCommon methods by itself.
+ return mStream->initInstance(nullptr);
+}
+
+const StreamContext& StreamSwitcher::getContext() const {
+ return *mContext;
+}
+
+bool StreamSwitcher::isClosed() const {
+ return mStream == nullptr || mStream->isClosed();
+}
+
+const StreamCommonInterface::ConnectedDevices& StreamSwitcher::getConnectedDevices() const {
+ return mStream->getConnectedDevices();
+}
+
+ndk::ScopedAStatus StreamSwitcher::setConnectedDevices(const std::vector<AudioDevice>& devices) {
+ LOG(DEBUG) << __func__ << ": " << ::android::internal::ToString(devices);
+ if (mStream->getConnectedDevices() == devices) return ndk::ScopedAStatus::ok();
+ const DeviceSwitchBehavior behavior = switchCurrentStream(devices);
+ if (behavior == DeviceSwitchBehavior::UNSUPPORTED_DEVICES) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ } else if (behavior == DeviceSwitchBehavior::SWITCH_TO_STUB_STREAM && !devices.empty()) {
+ // This is an error in the extending class.
+ LOG(FATAL) << __func__
+ << ": switching to stub stream with connected devices is not allowed";
+ }
+ if (behavior == USE_CURRENT_STREAM) {
+ mIsStubStream = false;
+ } else {
+ LOG(DEBUG) << __func__ << ": connected devices changed, switching stream";
+ // Two streams can't be opened for the same context, thus we always need to close
+ // the current one before creating a new one.
+ RETURN_STATUS_IF_ERROR(closeCurrentStream(true /*validateStreamState*/));
+ if (behavior == CREATE_NEW_STREAM) {
+ mStream = createNewStream(devices, mContext, mMetadata);
+ mIsStubStream = false;
+ } else { // SWITCH_TO_STUB_STREAM
+ mStream.reset(new InnerStreamWrapper<StreamStub>(mContext, mMetadata));
+ mIsStubStream = true;
+ }
+ // The delegate is null because StreamSwitcher handles IStreamCommon methods by itself.
+ if (ndk::ScopedAStatus status = mStream->initInstance(nullptr); !status.isOk()) {
+ if (mIsStubStream) {
+ LOG(FATAL) << __func__
+ << ": failed to initialize stub stream: " << status.getDescription();
+ }
+ // Need to close the current failed stream, and report an error.
+ // Since we can't operate without a stream implementation, put a stub in.
+ RETURN_STATUS_IF_ERROR(closeCurrentStream(false /*validateStreamState*/));
+ mStream.reset(new InnerStreamWrapper<StreamStub>(mContext, mMetadata));
+ (void)mStream->initInstance(nullptr);
+ (void)mStream->setConnectedDevices(devices);
+ return status;
+ }
+ }
+ RETURN_STATUS_IF_ERROR(mStream->setConnectedDevices(devices));
+ if (behavior == CREATE_NEW_STREAM) {
+ // These updates are less critical, only log warning on failure.
+ if (mHwAvSyncId.has_value()) {
+ if (auto status = mStream->updateHwAvSyncId(*mHwAvSyncId); !status.isOk()) {
+ LOG(WARNING) << __func__ << ": could not update HW AV Sync for a new stream: "
+ << status.getDescription();
+ }
+ }
+ for (const auto& vndParam : mMissedParameters) {
+ if (auto status = mStream->setVendorParameters(vndParam.first, vndParam.second);
+ !status.isOk()) {
+ LOG(WARNING) << __func__ << ": error while setting parameters for a new stream: "
+ << status.getDescription();
+ }
+ }
+ mMissedParameters.clear();
+ for (const auto& effect : mEffects) {
+ if (auto status = mStream->addEffect(effect); !status.isOk()) {
+ LOG(WARNING) << __func__ << ": error while adding effect for a new stream: "
+ << status.getDescription();
+ }
+ }
+ if (mBluetoothParametersUpdated) {
+ if (auto status = mStream->bluetoothParametersUpdated(); !status.isOk()) {
+ LOG(WARNING) << __func__
+ << ": error while updating BT parameters for a new stream: "
+ << status.getDescription();
+ }
+ }
+ mBluetoothParametersUpdated = false;
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamSwitcher::bluetoothParametersUpdated() {
+ if (mStream == nullptr) {
+ LOG(ERROR) << __func__ << ": stream was closed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ if (mIsStubStream) {
+ mBluetoothParametersUpdated = true;
+ return ndk::ScopedAStatus::ok();
+ }
+ return mStream->bluetoothParametersUpdated();
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/alsa/Mixer.cpp b/audio/aidl/default/alsa/Mixer.cpp
new file mode 100644
index 0000000..126c033
--- /dev/null
+++ b/audio/aidl/default/alsa/Mixer.cpp
@@ -0,0 +1,199 @@
+/*
+ * Copyright (C) 2023 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 <algorithm>
+#include <cmath>
+
+#define LOG_TAG "AHAL_AlsaMixer"
+#include <android-base/logging.h>
+#include <android/binder_status.h>
+
+#include "Mixer.h"
+
+namespace aidl::android::hardware::audio::core::alsa {
+
+// static
+const std::map<Mixer::Control, std::vector<Mixer::ControlNamesAndExpectedCtlType>>
+ Mixer::kPossibleControls = {
+ {Mixer::MASTER_SWITCH, {{"Master Playback Switch", MIXER_CTL_TYPE_BOOL}}},
+ {Mixer::MASTER_VOLUME, {{"Master Playback Volume", MIXER_CTL_TYPE_INT}}},
+ {Mixer::HW_VOLUME,
+ {{"Headphone Playback Volume", MIXER_CTL_TYPE_INT},
+ {"Headset Playback Volume", MIXER_CTL_TYPE_INT},
+ {"PCM Playback Volume", MIXER_CTL_TYPE_INT}}},
+ {Mixer::MIC_SWITCH, {{"Capture Switch", MIXER_CTL_TYPE_BOOL}}},
+ {Mixer::MIC_GAIN, {{"Capture Volume", MIXER_CTL_TYPE_INT}}}};
+
+// static
+Mixer::Controls Mixer::initializeMixerControls(struct mixer* mixer) {
+ if (mixer == nullptr) return {};
+ Controls mixerControls;
+ std::string mixerCtlNames;
+ for (const auto& [control, possibleCtls] : kPossibleControls) {
+ for (const auto& [ctlName, expectedCtlType] : possibleCtls) {
+ struct mixer_ctl* ctl = mixer_get_ctl_by_name(mixer, ctlName.c_str());
+ if (ctl != nullptr && mixer_ctl_get_type(ctl) == expectedCtlType) {
+ mixerControls.emplace(control, ctl);
+ if (!mixerCtlNames.empty()) {
+ mixerCtlNames += ",";
+ }
+ mixerCtlNames += ctlName;
+ break;
+ }
+ }
+ }
+ LOG(DEBUG) << __func__ << ": available mixer control names=[" << mixerCtlNames << "]";
+ return mixerControls;
+}
+
+std::ostream& operator<<(std::ostream& s, Mixer::Control c) {
+ switch (c) {
+ case Mixer::Control::MASTER_SWITCH:
+ s << "master mute";
+ break;
+ case Mixer::Control::MASTER_VOLUME:
+ s << "master volume";
+ break;
+ case Mixer::Control::HW_VOLUME:
+ s << "volume";
+ break;
+ case Mixer::Control::MIC_SWITCH:
+ s << "mic mute";
+ break;
+ case Mixer::Control::MIC_GAIN:
+ s << "mic gain";
+ break;
+ }
+ return s;
+}
+
+Mixer::Mixer(int card) : mMixer(mixer_open(card)), mMixerControls(initializeMixerControls(mMixer)) {
+ if (!isValid()) {
+ PLOG(ERROR) << __func__ << ": failed to open mixer for card=" << card;
+ }
+}
+
+Mixer::~Mixer() {
+ if (isValid()) {
+ std::lock_guard l(mMixerAccess);
+ mixer_close(mMixer);
+ }
+}
+
+ndk::ScopedAStatus Mixer::setMasterMute(bool muted) {
+ return setMixerControlMute(MASTER_SWITCH, muted);
+}
+
+ndk::ScopedAStatus Mixer::setMasterVolume(float volume) {
+ return setMixerControlVolume(MASTER_VOLUME, volume);
+}
+
+ndk::ScopedAStatus Mixer::setMicGain(float gain) {
+ return setMixerControlVolume(MIC_GAIN, gain);
+}
+
+ndk::ScopedAStatus Mixer::setMicMute(bool muted) {
+ return setMixerControlMute(MIC_SWITCH, muted);
+}
+
+ndk::ScopedAStatus Mixer::setVolumes(const std::vector<float>& volumes) {
+ if (!isValid()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ auto it = mMixerControls.find(Mixer::HW_VOLUME);
+ if (it == mMixerControls.end()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ std::vector<int> percents;
+ std::transform(
+ volumes.begin(), volumes.end(), std::back_inserter(percents),
+ [](float volume) -> int { return std::floor(std::clamp(volume, 0.0f, 1.0f) * 100); });
+ std::lock_guard l(mMixerAccess);
+ if (int err = setMixerControlPercent(it->second, percents); err != 0) {
+ LOG(ERROR) << __func__ << ": failed to set volume, err=" << err;
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus Mixer::setMixerControlMute(Mixer::Control ctl, bool muted) {
+ if (!isValid()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ auto it = mMixerControls.find(ctl);
+ if (it == mMixerControls.end()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ std::lock_guard l(mMixerAccess);
+ if (int err = setMixerControlValue(it->second, muted ? 0 : 1); err != 0) {
+ LOG(ERROR) << __func__ << ": failed to set " << ctl << " to " << muted << ", err=" << err;
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus Mixer::setMixerControlVolume(Control ctl, float volume) {
+ if (!isValid()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ auto it = mMixerControls.find(ctl);
+ if (it == mMixerControls.end()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ volume = std::clamp(volume, 0.0f, 1.0f);
+ std::lock_guard l(mMixerAccess);
+ if (int err = setMixerControlPercent(it->second, std::floor(volume * 100)); err != 0) {
+ LOG(ERROR) << __func__ << ": failed to set " << ctl << " to " << volume << ", err=" << err;
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+int Mixer::setMixerControlPercent(struct mixer_ctl* ctl, int percent) {
+ int ret = 0;
+ const unsigned int n = mixer_ctl_get_num_values(ctl);
+ for (unsigned int id = 0; id < n; id++) {
+ if (int error = mixer_ctl_set_percent(ctl, id, percent); error != 0) {
+ ret = error;
+ }
+ }
+ return ret;
+}
+
+int Mixer::setMixerControlPercent(struct mixer_ctl* ctl, const std::vector<int>& percents) {
+ int ret = 0;
+ const unsigned int n = mixer_ctl_get_num_values(ctl);
+ for (unsigned int id = 0; id < n; id++) {
+ if (int error = mixer_ctl_set_percent(ctl, id, id < percents.size() ? percents[id] : 0);
+ error != 0) {
+ ret = error;
+ }
+ }
+ return ret;
+}
+
+int Mixer::setMixerControlValue(struct mixer_ctl* ctl, int value) {
+ int ret = 0;
+ const unsigned int n = mixer_ctl_get_num_values(ctl);
+ for (unsigned int id = 0; id < n; id++) {
+ if (int error = mixer_ctl_set_value(ctl, id, value); error != 0) {
+ ret = error;
+ }
+ }
+ return ret;
+}
+
+} // namespace aidl::android::hardware::audio::core::alsa
diff --git a/audio/aidl/default/alsa/Mixer.h b/audio/aidl/default/alsa/Mixer.h
new file mode 100644
index 0000000..8fba1e0
--- /dev/null
+++ b/audio/aidl/default/alsa/Mixer.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2023 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 <iostream>
+#include <map>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+
+#include <android-base/thread_annotations.h>
+#include <android/binder_auto_utils.h>
+
+extern "C" {
+#include <tinyalsa/mixer.h>
+}
+
+namespace aidl::android::hardware::audio::core::alsa {
+
+class Mixer {
+ public:
+ explicit Mixer(int card);
+ ~Mixer();
+
+ bool isValid() const { return mMixer != nullptr; }
+
+ ndk::ScopedAStatus setMasterMute(bool muted);
+ ndk::ScopedAStatus setMasterVolume(float volume);
+ ndk::ScopedAStatus setMicGain(float gain);
+ ndk::ScopedAStatus setMicMute(bool muted);
+ ndk::ScopedAStatus setVolumes(const std::vector<float>& volumes);
+
+ private:
+ enum Control {
+ MASTER_SWITCH,
+ MASTER_VOLUME,
+ HW_VOLUME,
+ MIC_SWITCH,
+ MIC_GAIN,
+ };
+ using ControlNamesAndExpectedCtlType = std::pair<std::string, enum mixer_ctl_type>;
+ using Controls = std::map<Control, struct mixer_ctl*>;
+
+ friend std::ostream& operator<<(std::ostream&, Control);
+ static const std::map<Control, std::vector<ControlNamesAndExpectedCtlType>> kPossibleControls;
+ static Controls initializeMixerControls(struct mixer* mixer);
+
+ ndk::ScopedAStatus setMixerControlMute(Control ctl, bool muted);
+ ndk::ScopedAStatus setMixerControlVolume(Control ctl, float volume);
+
+ int setMixerControlPercent(struct mixer_ctl* ctl, int percent) REQUIRES(mMixerAccess);
+ int setMixerControlPercent(struct mixer_ctl* ctl, const std::vector<int>& percents)
+ REQUIRES(mMixerAccess);
+ int setMixerControlValue(struct mixer_ctl* ctl, int value) REQUIRES(mMixerAccess);
+
+ // Since ALSA functions do not use internal locking, enforce thread safety at our level.
+ std::mutex mMixerAccess;
+ // The mixer object is owned by ALSA and will be released when the mixer is closed.
+ struct mixer* const mMixer;
+ // `mMixerControls` will only be initialized in constructor. After that, it will only be
+ // read but not be modified. Each mixer_ctl object is owned by ALSA, it's life span is
+ // the same as of the mixer itself.
+ const Controls mMixerControls;
+};
+
+} // namespace aidl::android::hardware::audio::core::alsa
diff --git a/audio/aidl/default/alsa/ModuleAlsa.cpp b/audio/aidl/default/alsa/ModuleAlsa.cpp
new file mode 100644
index 0000000..8e75d56
--- /dev/null
+++ b/audio/aidl/default/alsa/ModuleAlsa.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2023 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 "AHAL_ModuleAlsa"
+
+#include <vector>
+
+#include <android-base/logging.h>
+
+#include "Utils.h"
+#include "core-impl/ModuleAlsa.h"
+
+extern "C" {
+#include "alsa_device_profile.h"
+}
+
+using aidl::android::media::audio::common::AudioChannelLayout;
+using aidl::android::media::audio::common::AudioFormatType;
+using aidl::android::media::audio::common::AudioPort;
+using aidl::android::media::audio::common::AudioProfile;
+
+namespace aidl::android::hardware::audio::core {
+
+ndk::ScopedAStatus ModuleAlsa::populateConnectedDevicePort(AudioPort* audioPort) {
+ auto deviceProfile = alsa::getDeviceProfile(*audioPort);
+ if (!deviceProfile.has_value()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ auto profile = alsa::readAlsaDeviceInfo(*deviceProfile);
+ if (!profile.has_value()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+
+ std::vector<AudioChannelLayout> channels = alsa::getChannelMasksFromProfile(&profile.value());
+ std::vector<int> sampleRates = alsa::getSampleRatesFromProfile(&profile.value());
+
+ for (size_t i = 0; i < std::min(MAX_PROFILE_FORMATS, AUDIO_PORT_MAX_AUDIO_PROFILES) &&
+ profile->formats[i] != PCM_FORMAT_INVALID;
+ ++i) {
+ auto audioFormatDescription =
+ alsa::c2aidl_pcm_format_AudioFormatDescription(profile->formats[i]);
+ if (audioFormatDescription.type == AudioFormatType::DEFAULT) {
+ LOG(WARNING) << __func__ << ": unknown pcm type=" << profile->formats[i];
+ continue;
+ }
+ AudioProfile audioProfile = {.format = audioFormatDescription,
+ .channelMasks = channels,
+ .sampleRates = sampleRates};
+ audioPort->profiles.push_back(std::move(audioProfile));
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/alsa/StreamAlsa.cpp b/audio/aidl/default/alsa/StreamAlsa.cpp
new file mode 100644
index 0000000..0605d6f
--- /dev/null
+++ b/audio/aidl/default/alsa/StreamAlsa.cpp
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2023 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 <cmath>
+#include <limits>
+
+#define LOG_TAG "AHAL_StreamAlsa"
+#include <android-base/logging.h>
+
+#include <Utils.h>
+#include <audio_utils/clock.h>
+#include <error/expected_utils.h>
+
+#include "core-impl/StreamAlsa.h"
+
+namespace aidl::android::hardware::audio::core {
+
+StreamAlsa::StreamAlsa(StreamContext* context, const Metadata& metadata, int readWriteRetries)
+ : StreamCommonImpl(context, metadata),
+ mBufferSizeFrames(getContext().getBufferSizeInFrames()),
+ mFrameSizeBytes(getContext().getFrameSize()),
+ mSampleRate(getContext().getSampleRate()),
+ mIsInput(isInput(metadata)),
+ mConfig(alsa::getPcmConfig(getContext(), mIsInput)),
+ mReadWriteRetries(readWriteRetries) {}
+
+::android::status_t StreamAlsa::init() {
+ return mConfig.has_value() ? ::android::OK : ::android::NO_INIT;
+}
+
+::android::status_t StreamAlsa::drain(StreamDescriptor::DrainMode) {
+ if (!mIsInput) {
+ static constexpr float kMicrosPerSecond = MICROS_PER_SECOND;
+ const size_t delayUs = static_cast<size_t>(
+ std::roundf(mBufferSizeFrames * kMicrosPerSecond / mSampleRate));
+ usleep(delayUs);
+ }
+ return ::android::OK;
+}
+
+::android::status_t StreamAlsa::flush() {
+ return ::android::OK;
+}
+
+::android::status_t StreamAlsa::pause() {
+ return ::android::OK;
+}
+
+::android::status_t StreamAlsa::standby() {
+ mAlsaDeviceProxies.clear();
+ return ::android::OK;
+}
+
+::android::status_t StreamAlsa::start() {
+ if (!mAlsaDeviceProxies.empty()) {
+ // This is a resume after a pause.
+ return ::android::OK;
+ }
+ decltype(mAlsaDeviceProxies) alsaDeviceProxies;
+ for (const auto& device : getDeviceProfiles()) {
+ alsa::DeviceProxy proxy;
+ if (device.isExternal) {
+ // Always ask alsa configure as required since the configuration should be supported
+ // by the connected device. That is guaranteed by `setAudioPortConfig` and
+ // `setAudioPatch`.
+ proxy = alsa::openProxyForExternalDevice(
+ device, const_cast<struct pcm_config*>(&mConfig.value()),
+ true /*require_exact_match*/);
+ } else {
+ proxy = alsa::openProxyForAttachedDevice(
+ device, const_cast<struct pcm_config*>(&mConfig.value()), mBufferSizeFrames);
+ }
+ if (!proxy) {
+ return ::android::NO_INIT;
+ }
+ alsaDeviceProxies.push_back(std::move(proxy));
+ }
+ mAlsaDeviceProxies = std::move(alsaDeviceProxies);
+ return ::android::OK;
+}
+
+::android::status_t StreamAlsa::transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
+ int32_t* latencyMs) {
+ if (mAlsaDeviceProxies.empty()) {
+ LOG(FATAL) << __func__ << ": no opened devices";
+ return ::android::NO_INIT;
+ }
+ const size_t bytesToTransfer = frameCount * mFrameSizeBytes;
+ unsigned maxLatency = 0;
+ if (mIsInput) {
+ // For input case, only support single device.
+ proxy_read_with_retries(mAlsaDeviceProxies[0].get(), buffer, bytesToTransfer,
+ mReadWriteRetries);
+ maxLatency = proxy_get_latency(mAlsaDeviceProxies[0].get());
+ } else {
+ for (auto& proxy : mAlsaDeviceProxies) {
+ proxy_write_with_retries(proxy.get(), buffer, bytesToTransfer, mReadWriteRetries);
+ maxLatency = std::max(maxLatency, proxy_get_latency(proxy.get()));
+ }
+ }
+ *actualFrameCount = frameCount;
+ maxLatency = std::min(maxLatency, static_cast<unsigned>(std::numeric_limits<int32_t>::max()));
+ *latencyMs = maxLatency;
+ return ::android::OK;
+}
+
+::android::status_t StreamAlsa::refinePosition(StreamDescriptor::Position* position) {
+ if (mAlsaDeviceProxies.empty()) {
+ LOG(FATAL) << __func__ << ": no opened devices";
+ return ::android::NO_INIT;
+ }
+ // Since the proxy can only count transferred frames since its creation,
+ // we override its counter value with ours and let it to correct for buffered frames.
+ alsa::resetTransferredFrames(mAlsaDeviceProxies[0], position->frames);
+ if (mIsInput) {
+ if (int ret = proxy_get_capture_position(mAlsaDeviceProxies[0].get(), &position->frames,
+ &position->timeNs);
+ ret != 0) {
+ LOG(WARNING) << __func__ << ": failed to retrieve capture position: " << ret;
+ return ::android::INVALID_OPERATION;
+ }
+ } else {
+ uint64_t hwFrames;
+ struct timespec timestamp;
+ if (int ret = proxy_get_presentation_position(mAlsaDeviceProxies[0].get(), &hwFrames,
+ ×tamp);
+ ret == 0) {
+ if (hwFrames > std::numeric_limits<int64_t>::max()) {
+ hwFrames -= std::numeric_limits<int64_t>::max();
+ }
+ position->frames = static_cast<int64_t>(hwFrames);
+ position->timeNs = audio_utils_ns_from_timespec(×tamp);
+ } else {
+ LOG(WARNING) << __func__ << ": failed to retrieve presentation position: " << ret;
+ return ::android::INVALID_OPERATION;
+ }
+ }
+ return ::android::OK;
+}
+
+void StreamAlsa::shutdown() {
+ mAlsaDeviceProxies.clear();
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/alsa/Utils.cpp b/audio/aidl/default/alsa/Utils.cpp
new file mode 100644
index 0000000..9dcd024
--- /dev/null
+++ b/audio/aidl/default/alsa/Utils.cpp
@@ -0,0 +1,353 @@
+/*
+ * Copyright (C) 2023 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 <map>
+#include <set>
+
+#define LOG_TAG "AHAL_AlsaUtils"
+#include <Utils.h>
+#include <aidl/android/media/audio/common/AudioFormatType.h>
+#include <aidl/android/media/audio/common/PcmType.h>
+#include <android-base/logging.h>
+
+#include "Utils.h"
+#include "core-impl/utils.h"
+
+using aidl::android::hardware::audio::common::getChannelCount;
+using aidl::android::media::audio::common::AudioChannelLayout;
+using aidl::android::media::audio::common::AudioDeviceAddress;
+using aidl::android::media::audio::common::AudioFormatDescription;
+using aidl::android::media::audio::common::AudioFormatType;
+using aidl::android::media::audio::common::AudioIoFlags;
+using aidl::android::media::audio::common::AudioPortExt;
+using aidl::android::media::audio::common::PcmType;
+
+namespace aidl::android::hardware::audio::core::alsa {
+
+namespace {
+
+using AudioChannelCountToMaskMap = std::map<unsigned int, AudioChannelLayout>;
+using AudioFormatDescToPcmFormatMap = std::map<AudioFormatDescription, enum pcm_format>;
+using PcmFormatToAudioFormatDescMap = std::map<enum pcm_format, AudioFormatDescription>;
+
+AudioChannelLayout getInvalidChannelLayout() {
+ static const AudioChannelLayout invalidChannelLayout =
+ AudioChannelLayout::make<AudioChannelLayout::Tag::invalid>(0);
+ return invalidChannelLayout;
+}
+
+static AudioChannelCountToMaskMap make_ChannelCountToMaskMap(
+ const std::set<AudioChannelLayout>& channelMasks) {
+ AudioChannelCountToMaskMap channelMaskToCountMap;
+ for (const auto& channelMask : channelMasks) {
+ channelMaskToCountMap.emplace(getChannelCount(channelMask), channelMask);
+ }
+ return channelMaskToCountMap;
+}
+
+#define DEFINE_CHANNEL_LAYOUT_MASK(n) \
+ AudioChannelLayout::make<AudioChannelLayout::Tag::layoutMask>(AudioChannelLayout::LAYOUT_##n)
+
+const AudioChannelCountToMaskMap& getSupportedChannelOutLayoutMap() {
+ static const std::set<AudioChannelLayout> supportedOutChannelLayouts = {
+ DEFINE_CHANNEL_LAYOUT_MASK(MONO), DEFINE_CHANNEL_LAYOUT_MASK(STEREO),
+ DEFINE_CHANNEL_LAYOUT_MASK(2POINT1), DEFINE_CHANNEL_LAYOUT_MASK(QUAD),
+ DEFINE_CHANNEL_LAYOUT_MASK(PENTA), DEFINE_CHANNEL_LAYOUT_MASK(5POINT1),
+ DEFINE_CHANNEL_LAYOUT_MASK(6POINT1), DEFINE_CHANNEL_LAYOUT_MASK(7POINT1),
+ DEFINE_CHANNEL_LAYOUT_MASK(7POINT1POINT4), DEFINE_CHANNEL_LAYOUT_MASK(22POINT2),
+ };
+ static const AudioChannelCountToMaskMap outLayouts =
+ make_ChannelCountToMaskMap(supportedOutChannelLayouts);
+ return outLayouts;
+}
+
+const AudioChannelCountToMaskMap& getSupportedChannelInLayoutMap() {
+ static const std::set<AudioChannelLayout> supportedInChannelLayouts = {
+ DEFINE_CHANNEL_LAYOUT_MASK(MONO),
+ DEFINE_CHANNEL_LAYOUT_MASK(STEREO),
+ };
+ static const AudioChannelCountToMaskMap inLayouts =
+ make_ChannelCountToMaskMap(supportedInChannelLayouts);
+ return inLayouts;
+}
+
+#undef DEFINE_CHANNEL_LAYOUT_MASK
+#define DEFINE_CHANNEL_INDEX_MASK(n) \
+ AudioChannelLayout::make<AudioChannelLayout::Tag::indexMask>(AudioChannelLayout::INDEX_MASK_##n)
+
+const AudioChannelCountToMaskMap& getSupportedChannelIndexLayoutMap() {
+ static const std::set<AudioChannelLayout> supportedIndexChannelLayouts = {
+ DEFINE_CHANNEL_INDEX_MASK(1), DEFINE_CHANNEL_INDEX_MASK(2),
+ DEFINE_CHANNEL_INDEX_MASK(3), DEFINE_CHANNEL_INDEX_MASK(4),
+ DEFINE_CHANNEL_INDEX_MASK(5), DEFINE_CHANNEL_INDEX_MASK(6),
+ DEFINE_CHANNEL_INDEX_MASK(7), DEFINE_CHANNEL_INDEX_MASK(8),
+ DEFINE_CHANNEL_INDEX_MASK(9), DEFINE_CHANNEL_INDEX_MASK(10),
+ DEFINE_CHANNEL_INDEX_MASK(11), DEFINE_CHANNEL_INDEX_MASK(12),
+ DEFINE_CHANNEL_INDEX_MASK(13), DEFINE_CHANNEL_INDEX_MASK(14),
+ DEFINE_CHANNEL_INDEX_MASK(15), DEFINE_CHANNEL_INDEX_MASK(16),
+ DEFINE_CHANNEL_INDEX_MASK(17), DEFINE_CHANNEL_INDEX_MASK(18),
+ DEFINE_CHANNEL_INDEX_MASK(19), DEFINE_CHANNEL_INDEX_MASK(20),
+ DEFINE_CHANNEL_INDEX_MASK(21), DEFINE_CHANNEL_INDEX_MASK(22),
+ DEFINE_CHANNEL_INDEX_MASK(23), DEFINE_CHANNEL_INDEX_MASK(24),
+ };
+ static const AudioChannelCountToMaskMap indexLayouts =
+ make_ChannelCountToMaskMap(supportedIndexChannelLayouts);
+ return indexLayouts;
+}
+
+#undef DEFINE_CHANNEL_INDEX_MASK
+
+AudioFormatDescription make_AudioFormatDescription(AudioFormatType type) {
+ AudioFormatDescription result;
+ result.type = type;
+ return result;
+}
+
+AudioFormatDescription make_AudioFormatDescription(PcmType pcm) {
+ auto result = make_AudioFormatDescription(AudioFormatType::PCM);
+ result.pcm = pcm;
+ return result;
+}
+
+const AudioFormatDescToPcmFormatMap& getAudioFormatDescriptorToPcmFormatMap() {
+ static const AudioFormatDescToPcmFormatMap formatDescToPcmFormatMap = {
+ {make_AudioFormatDescription(PcmType::UINT_8_BIT), PCM_FORMAT_S8},
+ {make_AudioFormatDescription(PcmType::INT_16_BIT), PCM_FORMAT_S16_LE},
+ {make_AudioFormatDescription(PcmType::FIXED_Q_8_24), PCM_FORMAT_S24_LE},
+ {make_AudioFormatDescription(PcmType::INT_24_BIT), PCM_FORMAT_S24_3LE},
+ {make_AudioFormatDescription(PcmType::INT_32_BIT), PCM_FORMAT_S32_LE},
+ {make_AudioFormatDescription(PcmType::FLOAT_32_BIT), PCM_FORMAT_FLOAT_LE},
+ };
+ return formatDescToPcmFormatMap;
+}
+
+static PcmFormatToAudioFormatDescMap make_PcmFormatToAudioFormatDescMap(
+ const AudioFormatDescToPcmFormatMap& formatDescToPcmFormatMap) {
+ PcmFormatToAudioFormatDescMap result;
+ for (const auto& formatPair : formatDescToPcmFormatMap) {
+ result.emplace(formatPair.second, formatPair.first);
+ }
+ return result;
+}
+
+const PcmFormatToAudioFormatDescMap& getPcmFormatToAudioFormatDescMap() {
+ static const PcmFormatToAudioFormatDescMap pcmFormatToFormatDescMap =
+ make_PcmFormatToAudioFormatDescMap(getAudioFormatDescriptorToPcmFormatMap());
+ return pcmFormatToFormatDescMap;
+}
+
+} // namespace
+
+std::ostream& operator<<(std::ostream& os, const DeviceProfile& device) {
+ return os << "<" << device.card << "," << device.device << ">";
+}
+
+AudioChannelLayout getChannelLayoutMaskFromChannelCount(unsigned int channelCount, int isInput) {
+ return findValueOrDefault(
+ isInput ? getSupportedChannelInLayoutMap() : getSupportedChannelOutLayoutMap(),
+ channelCount, getInvalidChannelLayout());
+}
+
+AudioChannelLayout getChannelIndexMaskFromChannelCount(unsigned int channelCount) {
+ return findValueOrDefault(getSupportedChannelIndexLayoutMap(), channelCount,
+ getInvalidChannelLayout());
+}
+
+unsigned int getChannelCountFromChannelMask(const AudioChannelLayout& channelMask, bool isInput) {
+ switch (channelMask.getTag()) {
+ case AudioChannelLayout::Tag::layoutMask: {
+ return findKeyOrDefault(
+ isInput ? getSupportedChannelInLayoutMap() : getSupportedChannelOutLayoutMap(),
+ static_cast<unsigned>(getChannelCount(channelMask)), 0u /*defaultValue*/);
+ }
+ case AudioChannelLayout::Tag::indexMask: {
+ return findKeyOrDefault(getSupportedChannelIndexLayoutMap(),
+ static_cast<unsigned>(getChannelCount(channelMask)),
+ 0u /*defaultValue*/);
+ }
+ case AudioChannelLayout::Tag::none:
+ case AudioChannelLayout::Tag::invalid:
+ case AudioChannelLayout::Tag::voiceMask:
+ default:
+ return 0;
+ }
+}
+
+std::vector<AudioChannelLayout> getChannelMasksFromProfile(const alsa_device_profile* profile) {
+ const bool isInput = profile->direction == PCM_IN;
+ std::vector<AudioChannelLayout> channels;
+ for (size_t i = 0; i < AUDIO_PORT_MAX_CHANNEL_MASKS && profile->channel_counts[i] != 0; ++i) {
+ auto layoutMask =
+ alsa::getChannelLayoutMaskFromChannelCount(profile->channel_counts[i], isInput);
+ if (layoutMask.getTag() == AudioChannelLayout::Tag::layoutMask) {
+ channels.push_back(layoutMask);
+ }
+ auto indexMask = alsa::getChannelIndexMaskFromChannelCount(profile->channel_counts[i]);
+ if (indexMask.getTag() == AudioChannelLayout::Tag::indexMask) {
+ channels.push_back(indexMask);
+ }
+ }
+ return channels;
+}
+
+std::optional<DeviceProfile> getDeviceProfile(
+ const ::aidl::android::media::audio::common::AudioDevice& audioDevice, bool isInput) {
+ if (audioDevice.address.getTag() != AudioDeviceAddress::Tag::alsa) {
+ LOG(ERROR) << __func__ << ": not alsa address: " << audioDevice.toString();
+ return std::nullopt;
+ }
+ auto& alsaAddress = audioDevice.address.get<AudioDeviceAddress::Tag::alsa>();
+ if (alsaAddress.size() != 2 || alsaAddress[0] < 0 || alsaAddress[1] < 0) {
+ LOG(ERROR) << __func__
+ << ": malformed alsa address: " << ::android::internal::ToString(alsaAddress);
+ return std::nullopt;
+ }
+ return DeviceProfile{.card = alsaAddress[0],
+ .device = alsaAddress[1],
+ .direction = isInput ? PCM_IN : PCM_OUT,
+ .isExternal = !audioDevice.type.connection.empty()};
+}
+
+std::optional<DeviceProfile> getDeviceProfile(
+ const ::aidl::android::media::audio::common::AudioPort& audioPort) {
+ if (audioPort.ext.getTag() != AudioPortExt::Tag::device) {
+ LOG(ERROR) << __func__ << ": port id " << audioPort.id << " is not a device port";
+ return std::nullopt;
+ }
+ auto& devicePort = audioPort.ext.get<AudioPortExt::Tag::device>();
+ return getDeviceProfile(devicePort.device, audioPort.flags.getTag() == AudioIoFlags::input);
+}
+
+std::optional<struct pcm_config> getPcmConfig(const StreamContext& context, bool isInput) {
+ struct pcm_config config;
+ config.channels = alsa::getChannelCountFromChannelMask(context.getChannelLayout(), isInput);
+ if (config.channels == 0) {
+ LOG(ERROR) << __func__ << ": invalid channel=" << context.getChannelLayout().toString();
+ return std::nullopt;
+ }
+ config.format = alsa::aidl2c_AudioFormatDescription_pcm_format(context.getFormat());
+ if (config.format == PCM_FORMAT_INVALID) {
+ LOG(ERROR) << __func__ << ": invalid format=" << context.getFormat().toString();
+ return std::nullopt;
+ }
+ config.rate = context.getSampleRate();
+ if (config.rate == 0) {
+ LOG(ERROR) << __func__ << ": invalid sample rate=" << config.rate;
+ return std::nullopt;
+ }
+ return config;
+}
+
+std::vector<int> getSampleRatesFromProfile(const alsa_device_profile* profile) {
+ std::vector<int> sampleRates;
+ for (int i = 0; i < std::min(MAX_PROFILE_SAMPLE_RATES, AUDIO_PORT_MAX_SAMPLING_RATES) &&
+ profile->sample_rates[i] != 0;
+ i++) {
+ sampleRates.push_back(profile->sample_rates[i]);
+ }
+ return sampleRates;
+}
+
+DeviceProxy makeDeviceProxy() {
+ DeviceProxy proxy(new alsa_device_proxy, [](alsa_device_proxy* proxy) {
+ if (proxy != nullptr) {
+ proxy_close(proxy);
+ delete proxy;
+ }
+ });
+ memset(proxy.get(), 0, sizeof(alsa_device_proxy));
+ return proxy;
+}
+
+DeviceProxy openProxyForAttachedDevice(const DeviceProfile& deviceProfile,
+ struct pcm_config* pcmConfig, size_t bufferFrameCount) {
+ if (deviceProfile.isExternal) {
+ LOG(FATAL) << __func__ << ": called for an external device, address=" << deviceProfile;
+ }
+ alsa_device_profile profile;
+ profile_init(&profile, deviceProfile.direction);
+ profile.card = deviceProfile.card;
+ profile.device = deviceProfile.device;
+ if (!profile_fill_builtin_device_info(&profile, pcmConfig, bufferFrameCount)) {
+ LOG(FATAL) << __func__ << ": failed to init for built-in device, address=" << deviceProfile;
+ }
+ auto proxy = makeDeviceProxy();
+ if (int err = proxy_prepare_from_default_config(proxy.get(), &profile); err != 0) {
+ LOG(FATAL) << __func__ << ": fail to prepare for device address=" << deviceProfile
+ << " error=" << err;
+ return nullptr;
+ }
+ if (int err = proxy_open(proxy.get()); err != 0) {
+ LOG(ERROR) << __func__ << ": failed to open device, address=" << deviceProfile
+ << " error=" << err;
+ return nullptr;
+ }
+ return proxy;
+}
+
+DeviceProxy openProxyForExternalDevice(const DeviceProfile& deviceProfile,
+ struct pcm_config* pcmConfig, bool requireExactMatch) {
+ if (!deviceProfile.isExternal) {
+ LOG(FATAL) << __func__ << ": called for an attached device, address=" << deviceProfile;
+ }
+ auto profile = readAlsaDeviceInfo(deviceProfile);
+ if (!profile.has_value()) {
+ LOG(ERROR) << __func__ << ": unable to read device info, device address=" << deviceProfile;
+ return nullptr;
+ }
+ auto proxy = makeDeviceProxy();
+ if (int err = proxy_prepare(proxy.get(), &profile.value(), pcmConfig, requireExactMatch);
+ err != 0) {
+ LOG(ERROR) << __func__ << ": fail to prepare for device address=" << deviceProfile
+ << " error=" << err;
+ return nullptr;
+ }
+ if (int err = proxy_open(proxy.get()); err != 0) {
+ LOG(ERROR) << __func__ << ": failed to open device, address=" << deviceProfile
+ << " error=" << err;
+ return nullptr;
+ }
+ return proxy;
+}
+
+std::optional<alsa_device_profile> readAlsaDeviceInfo(const DeviceProfile& deviceProfile) {
+ alsa_device_profile profile;
+ profile_init(&profile, deviceProfile.direction);
+ profile.card = deviceProfile.card;
+ profile.device = deviceProfile.device;
+ if (!profile_read_device_info(&profile)) {
+ LOG(ERROR) << __func__ << ": failed to read device info, card=" << profile.card
+ << ", device=" << profile.device;
+ return std::nullopt;
+ }
+ return profile;
+}
+
+void resetTransferredFrames(DeviceProxy& proxy, uint64_t frames) {
+ if (proxy != nullptr) {
+ proxy->transferred = frames;
+ }
+}
+
+AudioFormatDescription c2aidl_pcm_format_AudioFormatDescription(enum pcm_format legacy) {
+ return findValueOrDefault(getPcmFormatToAudioFormatDescMap(), legacy, AudioFormatDescription());
+}
+
+pcm_format aidl2c_AudioFormatDescription_pcm_format(const AudioFormatDescription& aidl) {
+ return findValueOrDefault(getAudioFormatDescriptorToPcmFormatMap(), aidl, PCM_FORMAT_INVALID);
+}
+
+} // namespace aidl::android::hardware::audio::core::alsa
diff --git a/audio/aidl/default/alsa/Utils.h b/audio/aidl/default/alsa/Utils.h
new file mode 100644
index 0000000..37414b3
--- /dev/null
+++ b/audio/aidl/default/alsa/Utils.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2023 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 <functional>
+#include <iostream>
+#include <memory>
+#include <optional>
+#include <vector>
+
+#include <aidl/android/media/audio/common/AudioChannelLayout.h>
+#include <aidl/android/media/audio/common/AudioFormatDescription.h>
+#include <aidl/android/media/audio/common/AudioPort.h>
+
+#include "core-impl/Stream.h"
+
+extern "C" {
+#include <tinyalsa/pcm.h>
+#include "alsa_device_profile.h"
+#include "alsa_device_proxy.h"
+}
+
+namespace aidl::android::hardware::audio::core::alsa {
+
+struct DeviceProfile {
+ int card;
+ int device;
+ int direction; /* PCM_OUT or PCM_IN */
+ bool isExternal;
+};
+std::ostream& operator<<(std::ostream& os, const DeviceProfile& device);
+using DeviceProxyDeleter = std::function<void(alsa_device_proxy*)>;
+using DeviceProxy = std::unique_ptr<alsa_device_proxy, DeviceProxyDeleter>;
+
+::aidl::android::media::audio::common::AudioChannelLayout getChannelLayoutMaskFromChannelCount(
+ unsigned int channelCount, int isInput);
+::aidl::android::media::audio::common::AudioChannelLayout getChannelIndexMaskFromChannelCount(
+ unsigned int channelCount);
+unsigned int getChannelCountFromChannelMask(
+ const ::aidl::android::media::audio::common::AudioChannelLayout& channelMask, bool isInput);
+std::vector<::aidl::android::media::audio::common::AudioChannelLayout> getChannelMasksFromProfile(
+ const alsa_device_profile* profile);
+std::optional<DeviceProfile> getDeviceProfile(
+ const ::aidl::android::media::audio::common::AudioDevice& audioDevice, bool isInput);
+std::optional<DeviceProfile> getDeviceProfile(
+ const ::aidl::android::media::audio::common::AudioPort& audioPort);
+std::optional<struct pcm_config> getPcmConfig(const StreamContext& context, bool isInput);
+std::vector<int> getSampleRatesFromProfile(const alsa_device_profile* profile);
+DeviceProxy makeDeviceProxy();
+DeviceProxy openProxyForAttachedDevice(const DeviceProfile& deviceProfile,
+ struct pcm_config* pcmConfig, size_t bufferFrameCount);
+DeviceProxy openProxyForExternalDevice(const DeviceProfile& deviceProfile,
+ struct pcm_config* pcmConfig, bool requireExactMatch);
+std::optional<alsa_device_profile> readAlsaDeviceInfo(const DeviceProfile& deviceProfile);
+void resetTransferredFrames(DeviceProxy& proxy, uint64_t frames);
+
+::aidl::android::media::audio::common::AudioFormatDescription
+c2aidl_pcm_format_AudioFormatDescription(enum pcm_format legacy);
+pcm_format aidl2c_AudioFormatDescription_pcm_format(
+ const ::aidl::android::media::audio::common::AudioFormatDescription& aidl);
+
+} // namespace aidl::android::hardware::audio::core::alsa
diff --git a/audio/aidl/default/android.hardware.audio.service-aidl.example.rc b/audio/aidl/default/android.hardware.audio.service-aidl.example.rc
index 2068735..757976f 100644
--- a/audio/aidl/default/android.hardware.audio.service-aidl.example.rc
+++ b/audio/aidl/default/android.hardware.audio.service-aidl.example.rc
@@ -3,7 +3,7 @@
user audioserver
# media gid needed for /dev/fm (radio) and for /data/misc/media (tee)
group audio camera drmrpc inet media mediadrm net_bt net_bt_admin net_bw_acct wakelock context_hub
- capabilities BLOCK_SUSPEND
+ capabilities BLOCK_SUSPEND SYS_NICE
# setting RLIMIT_RTPRIO allows binder RT priority inheritance
rlimit rtprio 10 10
ioprio rt 4
diff --git a/audio/aidl/default/android.hardware.audio.service-aidl.xml b/audio/aidl/default/android.hardware.audio.service-aidl.xml
index 9636a58..9db6061 100644
--- a/audio/aidl/default/android.hardware.audio.service-aidl.xml
+++ b/audio/aidl/default/android.hardware.audio.service-aidl.xml
@@ -12,11 +12,21 @@
<hal format="aidl">
<name>android.hardware.audio.core</name>
<version>1</version>
+ <fqname>IModule/stub</fqname>
+ </hal>
+ <hal format="aidl">
+ <name>android.hardware.audio.core</name>
+ <version>1</version>
<fqname>IModule/usb</fqname>
</hal>
<hal format="aidl">
<name>android.hardware.audio.core</name>
<version>1</version>
+ <fqname>IModule/bluetooth</fqname>
+ </hal>
+ <hal format="aidl">
+ <name>android.hardware.audio.core</name>
+ <version>1</version>
<fqname>IConfig/default</fqname>
</hal>
</manifest>
diff --git a/audio/aidl/default/audio_effects_config.xml b/audio/aidl/default/audio_effects_config.xml
index 6627ae7..00de797 100644
--- a/audio/aidl/default/audio_effects_config.xml
+++ b/audio/aidl/default/audio_effects_config.xml
@@ -50,7 +50,8 @@
</libraries>
<!-- list of effects to load.
- Each "effect" element must contain a "name", "library" and a "uuid" attribute.
+ Each "effect" element must contain a "name", "library" and a "uuid" attribute, an optional
+ "type" attribute can be used to add any customized effect type.
The value of the "library" attribute must correspond to the name of one library element in
the "libraries" element.
The "name" attribute used to specific effect type, and should be mapping to a key of
@@ -62,8 +63,8 @@
result of IFactory.queryEffects() to decide which effect implementation should be part of
proxy and which not.
- Only "name", "library", and "uuid" attributes in "effects" element are meaningful and
- parsed out by EffectConfig class, all other attributes are ignored.
+ Only "name", "library", "uuid", and "type" attributes in "effects" element are meaningful
+ and parsed out by EffectConfig class, all other attributes are ignored.
Only "name" and "uuid" attributes in "effectProxy" element are meaningful and parsed out
by EffectConfig class, all other attributes are ignored.
-->
@@ -94,7 +95,7 @@
<libsw library="equalizersw" uuid="0bed4300-847d-11df-bb17-0002a5d5c51b"/>
<libsw library="bundle" uuid="ce772f20-847d-11df-bb17-0002a5d5c51b"/>
</effectProxy>
- <effect name="extensioneffect" library="extensioneffect" uuid="fa81dd00-588b-11ed-9b6a-0242ac120002"/>
+ <effect name="extension_effect" library="extensioneffect" uuid="fa81dd00-588b-11ed-9b6a-0242ac120002" type="fa81de0e-588b-11ed-9b6a-0242ac120002"/>
<effect name="acoustic_echo_canceler" library="aecsw" uuid="bb392ec0-8d4d-11e0-a896-0002a5d5c51b"/>
<effect name="noise_suppression" library="nssw" uuid="c06c8400-8e06-11e0-9cb6-0002a5d5c51b"/>
</effects>
diff --git a/audio/aidl/default/bluetooth/DevicePortProxy.cpp b/audio/aidl/default/bluetooth/DevicePortProxy.cpp
new file mode 100644
index 0000000..12e204a
--- /dev/null
+++ b/audio/aidl/default/bluetooth/DevicePortProxy.cpp
@@ -0,0 +1,577 @@
+/*
+ * Copyright 2023 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 "AHAL_BluetoothPortProxy"
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <audio_utils/primitives.h>
+#include <inttypes.h>
+#include <log/log.h>
+
+#include "core-impl/DevicePortProxy.h"
+
+namespace android::bluetooth::audio::aidl {
+
+namespace {
+
+// The maximum time to wait in std::condition_variable::wait_for()
+constexpr unsigned int kMaxWaitingTimeMs = 4500;
+
+} // namespace
+
+using ::aidl::android::hardware::audio::common::SinkMetadata;
+using ::aidl::android::hardware::audio::common::SourceMetadata;
+using ::aidl::android::hardware::bluetooth::audio::AudioConfiguration;
+using ::aidl::android::hardware::bluetooth::audio::BluetoothAudioSessionControl;
+using ::aidl::android::hardware::bluetooth::audio::BluetoothAudioStatus;
+using ::aidl::android::hardware::bluetooth::audio::ChannelMode;
+using ::aidl::android::hardware::bluetooth::audio::PcmConfiguration;
+using ::aidl::android::hardware::bluetooth::audio::PortStatusCallbacks;
+using ::aidl::android::hardware::bluetooth::audio::PresentationPosition;
+using ::aidl::android::hardware::bluetooth::audio::SessionType;
+using ::aidl::android::media::audio::common::AudioDeviceDescription;
+using ::aidl::android::media::audio::common::AudioDeviceType;
+using ::android::base::StringPrintf;
+
+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 << android::base::StringPrintf("%#hhx", state);
+ }
+}
+
+BluetoothAudioPortAidl::BluetoothAudioPortAidl()
+ : mCookie(::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined),
+ mState(BluetoothStreamState::DISABLED),
+ mSessionType(SessionType::UNKNOWN) {}
+
+BluetoothAudioPortAidl::~BluetoothAudioPortAidl() {
+ unregisterPort();
+}
+
+bool BluetoothAudioPortAidl::registerPort(const AudioDeviceDescription& description) {
+ if (inUse()) {
+ LOG(ERROR) << __func__ << debugMessage() << " already in use";
+ return false;
+ }
+
+ if (!initSessionType(description)) return false;
+
+ auto control_result_cb = [port = this](uint16_t cookie, bool start_resp,
+ const BluetoothAudioStatus& status) {
+ (void)start_resp;
+ port->controlResultHandler(cookie, status);
+ };
+ auto session_changed_cb = [port = this](uint16_t cookie) {
+ port->sessionChangedHandler(cookie);
+ };
+ // TODO: Add audio_config_changed_cb
+ PortStatusCallbacks cbacks = {
+ .control_result_cb_ = control_result_cb,
+ .session_changed_cb_ = session_changed_cb,
+ };
+ mCookie = BluetoothAudioSessionControl::RegisterControlResultCback(mSessionType, cbacks);
+ auto isOk = (mCookie != ::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined);
+ if (isOk) {
+ std::lock_guard guard(mCvMutex);
+ mState = BluetoothStreamState::STANDBY;
+ }
+ LOG(DEBUG) << __func__ << debugMessage();
+ return isOk;
+}
+
+bool BluetoothAudioPortAidl::initSessionType(const AudioDeviceDescription& description) {
+ if (description.connection == AudioDeviceDescription::CONNECTION_BT_A2DP &&
+ (description.type == AudioDeviceType::OUT_DEVICE ||
+ description.type == AudioDeviceType::OUT_HEADPHONE ||
+ description.type == AudioDeviceType::OUT_SPEAKER)) {
+ LOG(VERBOSE) << __func__
+ << ": device=AUDIO_DEVICE_OUT_BLUETOOTH_A2DP (HEADPHONES/SPEAKER) ("
+ << description.toString() << ")";
+ mSessionType = SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH;
+ } else if (description.connection == AudioDeviceDescription::CONNECTION_WIRELESS &&
+ description.type == AudioDeviceType::OUT_HEARING_AID) {
+ LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_HEARING_AID (MEDIA/VOICE) ("
+ << description.toString() << ")";
+ mSessionType = SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH;
+ } else if (description.connection == AudioDeviceDescription::CONNECTION_BT_LE &&
+ description.type == AudioDeviceType::OUT_HEADSET) {
+ LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLE_HEADSET (MEDIA/VOICE) ("
+ << description.toString() << ")";
+ mSessionType = SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH;
+ } else if (description.connection == AudioDeviceDescription::CONNECTION_BT_LE &&
+ description.type == AudioDeviceType::OUT_SPEAKER) {
+ LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLE_SPEAKER (MEDIA) ("
+ << description.toString() << ")";
+ mSessionType = SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH;
+ } else if (description.connection == AudioDeviceDescription::CONNECTION_BT_LE &&
+ description.type == AudioDeviceType::IN_HEADSET) {
+ LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_IN_BLE_HEADSET (VOICE) ("
+ << description.toString() << ")";
+ mSessionType = SessionType::LE_AUDIO_SOFTWARE_DECODING_DATAPATH;
+ } else if (description.connection == AudioDeviceDescription::CONNECTION_BT_LE &&
+ description.type == AudioDeviceType::OUT_BROADCAST) {
+ LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLE_BROADCAST (MEDIA) ("
+ << description.toString() << ")";
+ mSessionType = SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH;
+ } else {
+ LOG(ERROR) << __func__ << ": unknown device=" << description.toString();
+ return false;
+ }
+
+ if (!BluetoothAudioSessionControl::IsSessionReady(mSessionType)) {
+ LOG(ERROR) << __func__ << ": device=" << description.toString()
+ << ", session_type=" << toString(mSessionType) << " is not ready";
+ return false;
+ }
+ return true;
+}
+
+void BluetoothAudioPortAidl::unregisterPort() {
+ if (!inUse()) {
+ LOG(WARNING) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return;
+ }
+ BluetoothAudioSessionControl::UnregisterControlResultCback(mSessionType, mCookie);
+ mCookie = ::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined;
+ LOG(VERBOSE) << __func__ << debugMessage() << " port unregistered";
+}
+
+void BluetoothAudioPortAidl::controlResultHandler(uint16_t cookie,
+ const BluetoothAudioStatus& status) {
+ std::lock_guard guard(mCvMutex);
+ if (!inUse()) {
+ LOG(ERROR) << "control_result_cb: BluetoothAudioPortAidl is not in use";
+ return;
+ }
+ if (mCookie != cookie) {
+ LOG(ERROR) << "control_result_cb: proxy of device port (cookie="
+ << StringPrintf("%#hx", cookie) << ") is corrupted";
+ return;
+ }
+ BluetoothStreamState previous_state = mState;
+ LOG(INFO) << "control_result_cb:" << debugMessage() << ", previous_state=" << previous_state
+ << ", status=" << toString(status);
+
+ switch (previous_state) {
+ case BluetoothStreamState::STARTED:
+ /* Only Suspend signal can be send in STARTED state*/
+ if (status == BluetoothAudioStatus::RECONFIGURATION ||
+ status == BluetoothAudioStatus::SUCCESS) {
+ mState = BluetoothStreamState::STANDBY;
+ } else {
+ LOG(WARNING) << StringPrintf(
+ "control_result_cb: status=%s failure for session_type= %s, cookie=%#hx, "
+ "previous_state=%#hhx",
+ toString(status).c_str(), toString(mSessionType).c_str(), mCookie,
+ previous_state);
+ }
+ break;
+ case BluetoothStreamState::STARTING:
+ if (status == BluetoothAudioStatus::SUCCESS) {
+ mState = BluetoothStreamState::STARTED;
+ } else {
+ // Set to standby since the stack may be busy switching between outputs
+ LOG(WARNING) << StringPrintf(
+ "control_result_cb: status=%s failure for session_type= %s, cookie=%#hx, "
+ "previous_state=%#hhx",
+ toString(status).c_str(), toString(mSessionType).c_str(), mCookie,
+ previous_state);
+ mState = BluetoothStreamState::STANDBY;
+ }
+ break;
+ case BluetoothStreamState::SUSPENDING:
+ if (status == BluetoothAudioStatus::SUCCESS) {
+ mState = BluetoothStreamState::STANDBY;
+ } else {
+ // It will be failed if the headset is disconnecting, and set to disable
+ // to wait for re-init again
+ LOG(WARNING) << StringPrintf(
+ "control_result_cb: status=%s failure for session_type= %s, cookie=%#hx, "
+ "previous_state=%#hhx",
+ toString(status).c_str(), toString(mSessionType).c_str(), mCookie,
+ previous_state);
+ mState = BluetoothStreamState::DISABLED;
+ }
+ break;
+ default:
+ LOG(ERROR) << "control_result_cb: unexpected previous_state="
+ << StringPrintf(
+ "control_result_cb: status=%s failure for session_type= %s, "
+ "cookie=%#hx, previous_state=%#hhx",
+ toString(status).c_str(), toString(mSessionType).c_str(), mCookie,
+ previous_state);
+ return;
+ }
+ mInternalCv.notify_all();
+}
+
+void BluetoothAudioPortAidl::sessionChangedHandler(uint16_t cookie) {
+ std::lock_guard guard(mCvMutex);
+ if (!inUse()) {
+ LOG(ERROR) << "session_changed_cb: BluetoothAudioPortAidl is not in use";
+ return;
+ }
+ if (mCookie != cookie) {
+ LOG(ERROR) << "session_changed_cb: proxy of device port (cookie="
+ << StringPrintf("%#hx", cookie) << ") is corrupted";
+ return;
+ }
+ BluetoothStreamState previous_state = mState;
+ LOG(VERBOSE) << "session_changed_cb:" << debugMessage()
+ << ", previous_state=" << previous_state;
+ mState = BluetoothStreamState::DISABLED;
+ mInternalCv.notify_all();
+}
+
+bool BluetoothAudioPortAidl::inUse() const {
+ return (mCookie != ::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined);
+}
+
+bool BluetoothAudioPortAidl::getPreferredDataIntervalUs(size_t* interval_us) const {
+ if (!interval_us) {
+ LOG(ERROR) << __func__ << ": bad input arg";
+ return false;
+ }
+
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return false;
+ }
+
+ const AudioConfiguration& hal_audio_cfg =
+ BluetoothAudioSessionControl::GetAudioConfig(mSessionType);
+ if (hal_audio_cfg.getTag() != AudioConfiguration::pcmConfig) {
+ LOG(ERROR) << __func__ << ": unsupported audio cfg tag";
+ return false;
+ }
+
+ *interval_us = hal_audio_cfg.get<AudioConfiguration::pcmConfig>().dataIntervalUs;
+ return true;
+}
+
+bool BluetoothAudioPortAidl::loadAudioConfig(PcmConfiguration* audio_cfg) const {
+ if (!audio_cfg) {
+ LOG(ERROR) << __func__ << ": bad input arg";
+ return false;
+ }
+
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return false;
+ }
+
+ const AudioConfiguration& hal_audio_cfg =
+ BluetoothAudioSessionControl::GetAudioConfig(mSessionType);
+ if (hal_audio_cfg.getTag() != AudioConfiguration::pcmConfig) {
+ LOG(ERROR) << __func__ << ": unsupported audio cfg tag";
+ return false;
+ }
+ *audio_cfg = hal_audio_cfg.get<AudioConfiguration::pcmConfig>();
+ LOG(VERBOSE) << __func__ << debugMessage() << ", state*=" << getState() << ", PcmConfig=["
+ << audio_cfg->toString() << "]";
+ if (audio_cfg->channelMode == ChannelMode::UNKNOWN) {
+ return false;
+ }
+ return true;
+}
+
+bool BluetoothAudioPortAidl::standby() {
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return false;
+ }
+ std::lock_guard guard(mCvMutex);
+ LOG(VERBOSE) << __func__ << debugMessage() << ", state=" << getState() << " request";
+ if (mState == BluetoothStreamState::DISABLED) {
+ mState = BluetoothStreamState::STANDBY;
+ LOG(VERBOSE) << __func__ << debugMessage() << ", state=" << getState() << " done";
+ return true;
+ }
+ return false;
+}
+
+bool BluetoothAudioPortAidl::condWaitState(BluetoothStreamState state) {
+ const auto waitTime = std::chrono::milliseconds(kMaxWaitingTimeMs);
+ std::unique_lock lock(mCvMutex);
+ base::ScopedLockAssertion lock_assertion(mCvMutex);
+ switch (state) {
+ case BluetoothStreamState::STARTING: {
+ LOG(VERBOSE) << __func__ << debugMessage() << " waiting for STARTED";
+ mInternalCv.wait_for(lock, waitTime, [this] {
+ base::ScopedLockAssertion lock_assertion(mCvMutex);
+ return mState != BluetoothStreamState::STARTING;
+ });
+ return mState == BluetoothStreamState::STARTED;
+ }
+ case BluetoothStreamState::SUSPENDING: {
+ LOG(VERBOSE) << __func__ << debugMessage() << " waiting for SUSPENDED";
+ mInternalCv.wait_for(lock, waitTime, [this] {
+ base::ScopedLockAssertion lock_assertion(mCvMutex);
+ return mState != BluetoothStreamState::SUSPENDING;
+ });
+ return mState == BluetoothStreamState::STANDBY;
+ }
+ default:
+ LOG(WARNING) << __func__ << debugMessage() << " waiting for KNOWN";
+ return false;
+ }
+ return false;
+}
+
+bool BluetoothAudioPortAidl::start() {
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return false;
+ }
+ LOG(VERBOSE) << __func__ << debugMessage() << ", state=" << getState()
+ << ", mono=" << (mIsStereoToMono ? "true" : "false") << " request";
+
+ {
+ std::unique_lock lock(mCvMutex);
+ base::ScopedLockAssertion lock_assertion(mCvMutex);
+ if (mState == BluetoothStreamState::STARTED) {
+ return true; // nop, return
+ } else if (mState == BluetoothStreamState::SUSPENDING ||
+ mState == BluetoothStreamState::STARTING) {
+ /* If port is in transient state, give some time to respond */
+ auto state_ = mState;
+ lock.unlock();
+ if (!condWaitState(state_)) {
+ LOG(ERROR) << __func__ << debugMessage() << ", state=" << getState() << " failure";
+ return false;
+ }
+ }
+ }
+
+ bool retval = false;
+ {
+ std::unique_lock lock(mCvMutex);
+ base::ScopedLockAssertion lock_assertion(mCvMutex);
+ if (mState == BluetoothStreamState::STARTED) {
+ retval = true;
+ } else if (mState == BluetoothStreamState::STANDBY) {
+ mState = BluetoothStreamState::STARTING;
+ lock.unlock();
+ if (BluetoothAudioSessionControl::StartStream(mSessionType)) {
+ retval = condWaitState(BluetoothStreamState::STARTING);
+ } else {
+ LOG(ERROR) << __func__ << debugMessage() << ", state=" << getState()
+ << " Hal fails";
+ }
+ }
+ }
+
+ if (retval) {
+ LOG(INFO) << __func__ << debugMessage() << ", state=" << getState()
+ << ", mono=" << (mIsStereoToMono ? "true" : "false") << " done";
+ } else {
+ LOG(ERROR) << __func__ << debugMessage() << ", state=" << getState() << " failure";
+ }
+
+ return retval; // false if any failure like timeout
+}
+
+bool BluetoothAudioPortAidl::suspend() {
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return false;
+ }
+ LOG(VERBOSE) << __func__ << debugMessage() << ", state=" << getState() << " request";
+
+ {
+ std::unique_lock lock(mCvMutex);
+ base::ScopedLockAssertion lock_assertion(mCvMutex);
+ if (mState == BluetoothStreamState::STANDBY) {
+ return true; // nop, return
+ } else if (mState == BluetoothStreamState::SUSPENDING ||
+ mState == BluetoothStreamState::STARTING) {
+ /* If port is in transient state, give some time to respond */
+ auto state_ = mState;
+ lock.unlock();
+ if (!condWaitState(state_)) {
+ LOG(ERROR) << __func__ << debugMessage() << ", state=" << getState() << " failure";
+ return false;
+ }
+ }
+ }
+
+ bool retval = false;
+ {
+ std::unique_lock lock(mCvMutex);
+ base::ScopedLockAssertion lock_assertion(mCvMutex);
+ if (mState == BluetoothStreamState::STANDBY) {
+ retval = true;
+ } else if (mState == BluetoothStreamState::STARTED) {
+ mState = BluetoothStreamState::SUSPENDING;
+ lock.unlock();
+ if (BluetoothAudioSessionControl::SuspendStream(mSessionType)) {
+ retval = condWaitState(BluetoothStreamState::SUSPENDING);
+ } else {
+ LOG(ERROR) << __func__ << debugMessage() << ", state=" << getState()
+ << " Hal fails";
+ }
+ }
+ }
+
+ if (retval) {
+ LOG(INFO) << __func__ << debugMessage() << ", state=" << getState() << " done";
+ } else {
+ LOG(ERROR) << __func__ << debugMessage() << ", state=" << getState() << " failure";
+ }
+
+ return retval; // false if any failure like timeout
+}
+
+void BluetoothAudioPortAidl::stop() {
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return;
+ }
+ std::lock_guard guard(mCvMutex);
+ LOG(VERBOSE) << __func__ << debugMessage() << ", state=" << getState() << " request";
+ if (mState != BluetoothStreamState::DISABLED) {
+ BluetoothAudioSessionControl::StopStream(mSessionType);
+ mState = BluetoothStreamState::DISABLED;
+ }
+ LOG(VERBOSE) << __func__ << debugMessage() << ", state=" << getState() << " done";
+}
+
+size_t BluetoothAudioPortAidlOut::writeData(const void* buffer, size_t bytes) const {
+ if (!buffer) {
+ LOG(ERROR) << __func__ << ": bad input arg";
+ return 0;
+ }
+
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return 0;
+ }
+
+ if (!mIsStereoToMono) {
+ return BluetoothAudioSessionControl::OutWritePcmData(mSessionType, buffer, bytes);
+ }
+
+ // WAR to mix the stereo into Mono (16 bits per sample)
+ const size_t write_frames = bytes >> 2;
+ if (write_frames == 0) return 0;
+ auto src = static_cast<const int16_t*>(buffer);
+ std::unique_ptr<int16_t[]> dst{new int16_t[write_frames]};
+ downmix_to_mono_i16_from_stereo_i16(dst.get(), src, write_frames);
+ // a frame is 16 bits, and the size of a mono frame is equal to half a stereo.
+ auto totalWrite = BluetoothAudioSessionControl::OutWritePcmData(mSessionType, dst.get(),
+ write_frames * 2);
+ return totalWrite * 2;
+}
+
+size_t BluetoothAudioPortAidlIn::readData(void* buffer, size_t bytes) const {
+ if (!buffer) {
+ LOG(ERROR) << __func__ << ": bad input arg";
+ return 0;
+ }
+
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return 0;
+ }
+
+ return BluetoothAudioSessionControl::InReadPcmData(mSessionType, buffer, bytes);
+}
+
+bool BluetoothAudioPortAidl::getPresentationPosition(
+ PresentationPosition& presentation_position) const {
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return false;
+ }
+ bool retval = BluetoothAudioSessionControl::GetPresentationPosition(mSessionType,
+ presentation_position);
+ LOG(VERBOSE) << __func__ << debugMessage() << ", state=" << getState()
+ << presentation_position.toString();
+
+ return retval;
+}
+
+bool BluetoothAudioPortAidl::updateSourceMetadata(const SourceMetadata& source_metadata) const {
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return false;
+ }
+ LOG(DEBUG) << __func__ << debugMessage() << ", state=" << getState() << ", "
+ << source_metadata.tracks.size() << " track(s)";
+ if (source_metadata.tracks.size() == 0) return true;
+ return BluetoothAudioSessionControl::UpdateSourceMetadata(mSessionType, source_metadata);
+}
+
+bool BluetoothAudioPortAidl::updateSinkMetadata(const SinkMetadata& sink_metadata) const {
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return false;
+ }
+ LOG(DEBUG) << __func__ << debugMessage() << ", state=" << getState() << ", "
+ << sink_metadata.tracks.size() << " track(s)";
+ if (sink_metadata.tracks.size() == 0) return true;
+ return BluetoothAudioSessionControl::UpdateSinkMetadata(mSessionType, sink_metadata);
+}
+
+BluetoothStreamState BluetoothAudioPortAidl::getState() const {
+ return mState;
+}
+
+bool BluetoothAudioPortAidl::setState(BluetoothStreamState state) {
+ if (!inUse()) {
+ LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use";
+ return false;
+ }
+ std::lock_guard guard(mCvMutex);
+ LOG(DEBUG) << __func__ << ": BluetoothAudioPortAidl old state = " << mState
+ << " new state = " << state;
+ mState = state;
+ return true;
+}
+
+bool BluetoothAudioPortAidl::isA2dp() const {
+ return mSessionType == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH ||
+ mSessionType == SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH;
+}
+
+bool BluetoothAudioPortAidl::isLeAudio() const {
+ return mSessionType == SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH ||
+ mSessionType == SessionType::LE_AUDIO_SOFTWARE_DECODING_DATAPATH ||
+ mSessionType == SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH ||
+ mSessionType == SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH ||
+ mSessionType == SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH ||
+ mSessionType == SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH;
+}
+
+std::string BluetoothAudioPortAidl::debugMessage() const {
+ return StringPrintf(": session_type=%s, cookie=%#hx", toString(mSessionType).c_str(), mCookie);
+}
+
+} // namespace android::bluetooth::audio::aidl
diff --git a/audio/aidl/default/bluetooth/ModuleBluetooth.cpp b/audio/aidl/default/bluetooth/ModuleBluetooth.cpp
new file mode 100644
index 0000000..bfe7ca0
--- /dev/null
+++ b/audio/aidl/default/bluetooth/ModuleBluetooth.cpp
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2023 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 "AHAL_ModuleBluetooth"
+
+#include <android-base/logging.h>
+
+#include "core-impl/ModuleBluetooth.h"
+#include "core-impl/StreamBluetooth.h"
+
+namespace aidl::android::hardware::audio::core {
+
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
+using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::MicrophoneInfo;
+
+ndk::ScopedAStatus ModuleBluetooth::getBluetoothA2dp(
+ std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
+ if (!mBluetoothA2dp) {
+ auto handle = ndk::SharedRefBase::make<BluetoothA2dp>();
+ handle->registerHandler(std::bind(&ModuleBluetooth::bluetoothParametersUpdated, this));
+ mBluetoothA2dp = handle;
+ }
+ *_aidl_return = mBluetoothA2dp.getInstance();
+ LOG(DEBUG) << __func__ << ": returning instance of IBluetoothA2dp: " << _aidl_return->get();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleBluetooth::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
+ if (!mBluetoothLe) {
+ auto handle = ndk::SharedRefBase::make<BluetoothLe>();
+ handle->registerHandler(std::bind(&ModuleBluetooth::bluetoothParametersUpdated, this));
+ mBluetoothLe = handle;
+ }
+ *_aidl_return = mBluetoothLe.getInstance();
+ LOG(DEBUG) << __func__ << ": returning instance of IBluetoothLe: " << _aidl_return->get();
+ return ndk::ScopedAStatus::ok();
+}
+
+Module::BtProfileHandles ModuleBluetooth::getBtProfileManagerHandles() {
+ return std::make_tuple(std::weak_ptr<IBluetooth>(), mBluetoothA2dp.getInstance(),
+ mBluetoothLe.getInstance());
+}
+
+ndk::ScopedAStatus ModuleBluetooth::getMicMute(bool* _aidl_return __unused) {
+ LOG(DEBUG) << __func__ << ": is not supported";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus ModuleBluetooth::setMicMute(bool in_mute __unused) {
+ LOG(DEBUG) << __func__ << ": is not supported";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus ModuleBluetooth::createInputStream(
+ StreamContext&& context, const SinkMetadata& sinkMetadata,
+ const std::vector<MicrophoneInfo>& microphones, std::shared_ptr<StreamIn>* result) {
+ return createStreamInstance<StreamInBluetooth>(result, std::move(context), sinkMetadata,
+ microphones, getBtProfileManagerHandles());
+}
+
+ndk::ScopedAStatus ModuleBluetooth::createOutputStream(
+ StreamContext&& context, const SourceMetadata& sourceMetadata,
+ const std::optional<AudioOffloadInfo>& offloadInfo, std::shared_ptr<StreamOut>* result) {
+ return createStreamInstance<StreamOutBluetooth>(result, std::move(context), sourceMetadata,
+ offloadInfo, getBtProfileManagerHandles());
+}
+
+ndk::ScopedAStatus ModuleBluetooth::onMasterMuteChanged(bool) {
+ LOG(DEBUG) << __func__ << ": is not supported";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus ModuleBluetooth::onMasterVolumeChanged(float) {
+ LOG(DEBUG) << __func__ << ": is not supported";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/bluetooth/StreamBluetooth.cpp b/audio/aidl/default/bluetooth/StreamBluetooth.cpp
new file mode 100644
index 0000000..91a33c2
--- /dev/null
+++ b/audio/aidl/default/bluetooth/StreamBluetooth.cpp
@@ -0,0 +1,338 @@
+/*
+ * Copyright (C) 2023 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 "AHAL_StreamBluetooth"
+
+#include <Utils.h>
+#include <android-base/logging.h>
+#include <audio_utils/clock.h>
+
+#include "BluetoothAudioSessionControl.h"
+#include "core-impl/StreamBluetooth.h"
+
+namespace aidl::android::hardware::audio::core {
+
+using ::aidl::android::hardware::audio::common::SinkMetadata;
+using ::aidl::android::hardware::audio::common::SourceMetadata;
+using ::aidl::android::hardware::audio::core::VendorParameter;
+using ::aidl::android::hardware::bluetooth::audio::ChannelMode;
+using ::aidl::android::hardware::bluetooth::audio::PcmConfiguration;
+using ::aidl::android::hardware::bluetooth::audio::PresentationPosition;
+using ::aidl::android::media::audio::common::AudioChannelLayout;
+using ::aidl::android::media::audio::common::AudioDevice;
+using ::aidl::android::media::audio::common::AudioDeviceAddress;
+using ::aidl::android::media::audio::common::AudioFormatDescription;
+using ::aidl::android::media::audio::common::AudioFormatType;
+using ::aidl::android::media::audio::common::AudioOffloadInfo;
+using ::aidl::android::media::audio::common::MicrophoneDynamicInfo;
+using ::aidl::android::media::audio::common::MicrophoneInfo;
+using ::android::bluetooth::audio::aidl::BluetoothAudioPortAidl;
+using ::android::bluetooth::audio::aidl::BluetoothAudioPortAidlIn;
+using ::android::bluetooth::audio::aidl::BluetoothAudioPortAidlOut;
+using ::android::bluetooth::audio::aidl::BluetoothStreamState;
+
+constexpr int kBluetoothDefaultInputBufferMs = 20;
+constexpr int kBluetoothDefaultOutputBufferMs = 10;
+// constexpr int kBluetoothSpatializerOutputBufferMs = 10;
+
+size_t getFrameCount(uint64_t durationUs, uint32_t sampleRate) {
+ return (durationUs * sampleRate) / 1000000;
+}
+
+// pcm configuration params are not really used by the module
+StreamBluetooth::StreamBluetooth(StreamContext* context, const Metadata& metadata,
+ Module::BtProfileHandles&& btHandles)
+ : StreamCommonImpl(context, metadata),
+ mSampleRate(getContext().getSampleRate()),
+ mChannelLayout(getContext().getChannelLayout()),
+ mFormat(getContext().getFormat()),
+ mFrameSizeBytes(getContext().getFrameSize()),
+ mIsInput(isInput(metadata)),
+ mBluetoothA2dp(std::move(std::get<Module::BtInterface::BTA2DP>(btHandles))),
+ mBluetoothLe(std::move(std::get<Module::BtInterface::BTLE>(btHandles))) {
+ mPreferredDataIntervalUs =
+ mIsInput ? kBluetoothDefaultInputBufferMs : kBluetoothDefaultOutputBufferMs;
+ mPreferredFrameCount = getFrameCount(mPreferredDataIntervalUs, mSampleRate);
+ mIsInitialized = false;
+ mIsReadyToClose = false;
+}
+
+::android::status_t StreamBluetooth::init() {
+ return ::android::OK; // defering this till we get AudioDeviceDescription
+}
+
+const StreamCommonInterface::ConnectedDevices& StreamBluetooth::getConnectedDevices() const {
+ std::lock_guard guard(mLock);
+ return StreamCommonImpl::getConnectedDevices();
+}
+
+ndk::ScopedAStatus StreamBluetooth::setConnectedDevices(
+ const std::vector<AudioDevice>& connectedDevices) {
+ if (mIsInput && connectedDevices.size() > 1) {
+ LOG(ERROR) << __func__ << ": wrong device size(" << connectedDevices.size()
+ << ") for input stream";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ for (const auto& connectedDevice : connectedDevices) {
+ if (connectedDevice.address.getTag() != AudioDeviceAddress::mac) {
+ LOG(ERROR) << __func__ << ": bad device address" << connectedDevice.address.toString();
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ }
+ std::lock_guard guard(mLock);
+ RETURN_STATUS_IF_ERROR(StreamCommonImpl::setConnectedDevices(connectedDevices));
+ mIsInitialized = false; // updated connected device list, need initialization
+ return ndk::ScopedAStatus::ok();
+}
+
+::android::status_t StreamBluetooth::drain(StreamDescriptor::DrainMode) {
+ usleep(1000);
+ return ::android::OK;
+}
+
+::android::status_t StreamBluetooth::flush() {
+ usleep(1000);
+ return ::android::OK;
+}
+
+::android::status_t StreamBluetooth::pause() {
+ return standby();
+}
+
+::android::status_t StreamBluetooth::transfer(void* buffer, size_t frameCount,
+ size_t* actualFrameCount, int32_t* latencyMs) {
+ std::lock_guard guard(mLock);
+ if (!mIsInitialized || mIsReadyToClose) {
+ // 'setConnectedDevices' has been called or stream is ready to close, so no transfers
+ *actualFrameCount = 0;
+ *latencyMs = StreamDescriptor::LATENCY_UNKNOWN;
+ return ::android::OK;
+ }
+ *actualFrameCount = 0;
+ *latencyMs = 0;
+ for (auto proxy : mBtDeviceProxies) {
+ if (!proxy->start()) {
+ LOG(ERROR) << __func__ << ": state = " << proxy->getState() << " failed to start ";
+ return -EIO;
+ }
+ const size_t fc = std::min(frameCount, mPreferredFrameCount);
+ const size_t bytesToTransfer = fc * mFrameSizeBytes;
+ if (mIsInput) {
+ const size_t totalRead = proxy->readData(buffer, bytesToTransfer);
+ *actualFrameCount = std::max(*actualFrameCount, totalRead / mFrameSizeBytes);
+ } else {
+ const size_t totalWrite = proxy->writeData(buffer, bytesToTransfer);
+ *actualFrameCount = std::max(*actualFrameCount, totalWrite / mFrameSizeBytes);
+ }
+ PresentationPosition presentation_position;
+ if (!proxy->getPresentationPosition(presentation_position)) {
+ LOG(ERROR) << __func__ << ": getPresentationPosition returned error ";
+ return ::android::UNKNOWN_ERROR;
+ }
+ *latencyMs =
+ std::max(*latencyMs, (int32_t)(presentation_position.remoteDeviceAudioDelayNanos /
+ NANOS_PER_MILLISECOND));
+ }
+ return ::android::OK;
+}
+
+::android::status_t StreamBluetooth::initialize() {
+ if (!::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession::IsAidlAvailable()) {
+ LOG(ERROR) << __func__ << ": IBluetoothAudioProviderFactory service not available";
+ return ::android::UNKNOWN_ERROR;
+ }
+ if (StreamCommonImpl::getConnectedDevices().empty()) {
+ LOG(ERROR) << __func__ << ", has no connected devices";
+ return ::android::NO_INIT;
+ }
+ // unregister older proxies (if any)
+ for (auto proxy : mBtDeviceProxies) {
+ proxy->stop();
+ proxy->unregisterPort();
+ }
+ mBtDeviceProxies.clear();
+ for (auto it = StreamCommonImpl::getConnectedDevices().begin();
+ it != StreamCommonImpl::getConnectedDevices().end(); ++it) {
+ std::shared_ptr<BluetoothAudioPortAidl> proxy =
+ mIsInput ? std::shared_ptr<BluetoothAudioPortAidl>(
+ std::make_shared<BluetoothAudioPortAidlIn>())
+ : std::shared_ptr<BluetoothAudioPortAidl>(
+ std::make_shared<BluetoothAudioPortAidlOut>());
+ if (proxy->registerPort(it->type)) {
+ LOG(ERROR) << __func__ << ": cannot init HAL";
+ return ::android::UNKNOWN_ERROR;
+ }
+ PcmConfiguration config;
+ if (!proxy->loadAudioConfig(&config)) {
+ LOG(ERROR) << __func__ << ": state=" << proxy->getState()
+ << " failed to get audio config";
+ return ::android::UNKNOWN_ERROR;
+ }
+ // TODO: Ensure minimum duration for spatialized output?
+ // WAR to support Mono / 16 bits per sample as the Bluetooth stack required
+ if (!mIsInput && config.channelMode == ChannelMode::MONO && config.bitsPerSample == 16) {
+ proxy->forcePcmStereoToMono(true);
+ config.channelMode = ChannelMode::STEREO;
+ LOG(INFO) << __func__ << ": force channels = to be AUDIO_CHANNEL_OUT_STEREO";
+ }
+ if (!checkConfigParams(config)) {
+ LOG(ERROR) << __func__ << " checkConfigParams failed";
+ return ::android::UNKNOWN_ERROR;
+ }
+ mBtDeviceProxies.push_back(std::move(proxy));
+ }
+ mIsInitialized = true;
+ return ::android::OK;
+}
+
+bool StreamBluetooth::checkConfigParams(
+ ::aidl::android::hardware::bluetooth::audio::PcmConfiguration& config) {
+ if ((int)mSampleRate != config.sampleRateHz) {
+ LOG(ERROR) << __func__ << ": Sample Rate mismatch, stream val = " << mSampleRate
+ << " hal val = " << config.sampleRateHz;
+ return false;
+ }
+ auto channelCount = aidl::android::hardware::audio::common::getChannelCount(mChannelLayout);
+ if ((config.channelMode == ChannelMode::MONO && channelCount != 1) ||
+ (config.channelMode == ChannelMode::STEREO && channelCount != 2)) {
+ LOG(ERROR) << __func__ << ": Channel count mismatch, stream val = " << channelCount
+ << " hal val = " << toString(config.channelMode);
+ return false;
+ }
+ if (mFormat.type != AudioFormatType::PCM) {
+ LOG(ERROR) << __func__ << ": unexpected format type "
+ << aidl::android::media::audio::common::toString(mFormat.type);
+ return false;
+ }
+ int8_t bps = aidl::android::hardware::audio::common::getPcmSampleSizeInBytes(mFormat.pcm) * 8;
+ if (bps != config.bitsPerSample) {
+ LOG(ERROR) << __func__ << ": bits per sample mismatch, stream val = " << bps
+ << " hal val = " << config.bitsPerSample;
+ return false;
+ }
+ if (config.dataIntervalUs > 0) {
+ mPreferredDataIntervalUs =
+ std::min((int32_t)mPreferredDataIntervalUs, config.dataIntervalUs);
+ mPreferredFrameCount = getFrameCount(mPreferredDataIntervalUs, mSampleRate);
+ }
+ return true;
+}
+
+ndk::ScopedAStatus StreamBluetooth::prepareToClose() {
+ std::lock_guard guard(mLock);
+ mIsReadyToClose = true;
+ return ndk::ScopedAStatus::ok();
+}
+
+::android::status_t StreamBluetooth::standby() {
+ std::lock_guard guard(mLock);
+ if (!mIsInitialized) {
+ if (auto status = initialize(); status != ::android::OK) return status;
+ }
+ for (auto proxy : mBtDeviceProxies) {
+ if (!proxy->suspend()) {
+ LOG(ERROR) << __func__ << ": state = " << proxy->getState() << " failed to stand by ";
+ return -EIO;
+ }
+ }
+ return ::android::OK;
+}
+
+::android::status_t StreamBluetooth::start() {
+ std::lock_guard guard(mLock);
+ if (!mIsInitialized) return initialize();
+ return ::android::OK;
+}
+
+void StreamBluetooth::shutdown() {
+ std::lock_guard guard(mLock);
+ for (auto proxy : mBtDeviceProxies) {
+ proxy->stop();
+ proxy->unregisterPort();
+ }
+ mBtDeviceProxies.clear();
+}
+
+ndk::ScopedAStatus StreamBluetooth::updateMetadataCommon(const Metadata& metadata) {
+ std::lock_guard guard(mLock);
+ if (!mIsInitialized) return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ bool isOk = true;
+ if (isInput(metadata)) {
+ isOk = mBtDeviceProxies[0]->updateSinkMetadata(std::get<SinkMetadata>(metadata));
+ } else {
+ for (auto proxy : mBtDeviceProxies) {
+ if (!proxy->updateSourceMetadata(std::get<SourceMetadata>(metadata))) isOk = false;
+ }
+ }
+ return isOk ? ndk::ScopedAStatus::ok()
+ : ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus StreamBluetooth::bluetoothParametersUpdated() {
+ if (mIsInput) {
+ LOG(WARNING) << __func__ << ": not handled";
+ return ndk::ScopedAStatus::ok();
+ }
+ auto applyParam = [](const std::shared_ptr<BluetoothAudioPortAidl>& proxy,
+ bool isEnabled) -> bool {
+ if (!isEnabled) {
+ if (proxy->suspend()) return proxy->setState(BluetoothStreamState::DISABLED);
+ return false;
+ }
+ return proxy->standby();
+ };
+ bool hasA2dpParam, enableA2dp;
+ auto btA2dp = mBluetoothA2dp.lock();
+ hasA2dpParam = btA2dp != nullptr && btA2dp->isEnabled(&enableA2dp).isOk();
+ bool hasLeParam, enableLe;
+ auto btLe = mBluetoothLe.lock();
+ hasLeParam = btLe != nullptr && btLe->isEnabled(&enableLe).isOk();
+ std::unique_lock lock(mLock);
+ ::android::base::ScopedLockAssertion lock_assertion(mLock);
+ if (!mIsInitialized) {
+ LOG(WARNING) << __func__ << ": init not done";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ for (auto proxy : mBtDeviceProxies) {
+ if ((hasA2dpParam && proxy->isA2dp() && !applyParam(proxy, enableA2dp)) ||
+ (hasLeParam && proxy->isLeAudio() && !applyParam(proxy, enableLe))) {
+ LOG(DEBUG) << __func__ << ": applyParam failed";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+StreamInBluetooth::StreamInBluetooth(StreamContext&& context, const SinkMetadata& sinkMetadata,
+ const std::vector<MicrophoneInfo>& microphones,
+ Module::BtProfileHandles&& btProfileHandles)
+ : StreamIn(std::move(context), microphones),
+ StreamBluetooth(&mContextInstance, sinkMetadata, std::move(btProfileHandles)) {}
+
+ndk::ScopedAStatus StreamInBluetooth::getActiveMicrophones(
+ std::vector<MicrophoneDynamicInfo>* _aidl_return __unused) {
+ LOG(DEBUG) << __func__ << ": not supported";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+StreamOutBluetooth::StreamOutBluetooth(StreamContext&& context,
+ const SourceMetadata& sourceMetadata,
+ const std::optional<AudioOffloadInfo>& offloadInfo,
+ Module::BtProfileHandles&& btProfileHandles)
+ : StreamOut(std::move(context), offloadInfo),
+ StreamBluetooth(&mContextInstance, sourceMetadata, std::move(btProfileHandles)) {}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/config/audioPolicy/api/current.txt b/audio/aidl/default/config/audioPolicy/api/current.txt
index fabb93b..e2bc833 100644
--- a/audio/aidl/default/config/audioPolicy/api/current.txt
+++ b/audio/aidl/default/config/audioPolicy/api/current.txt
@@ -33,14 +33,19 @@
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_INDEX_MASK_8;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_INDEX_MASK_9;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_2POINT0POINT2;
+ enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_2POINT1;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_2POINT1POINT2;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_3POINT0POINT2;
+ enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_3POINT1;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_3POINT1POINT2;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_5POINT1;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_6;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_FRONT_BACK;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_MONO;
+ enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_PENTA;
+ enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_QUAD;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_STEREO;
+ enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_TRI;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_VOICE_CALL_MONO;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_VOICE_DNLINK_MONO;
enum_constant public static final android.audio.policy.configuration.AudioChannelMask AUDIO_CHANNEL_IN_VOICE_UPLINK_MONO;
diff --git a/audio/aidl/default/config/audioPolicy/audio_policy_configuration.xsd b/audio/aidl/default/config/audioPolicy/audio_policy_configuration.xsd
index d57790a..9a3a447 100644
--- a/audio/aidl/default/config/audioPolicy/audio_policy_configuration.xsd
+++ b/audio/aidl/default/config/audioPolicy/audio_policy_configuration.xsd
@@ -535,12 +535,17 @@
<xs:enumeration value="AUDIO_CHANNEL_OUT_STEREO_HAPTIC_AB"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_MONO"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_STEREO"/>
+ <xs:enumeration value="AUDIO_CHANNEL_IN_2POINT1"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_FRONT_BACK"/>
+ <xs:enumeration value="AUDIO_CHANNEL_IN_TRI"/>
+ <xs:enumeration value="AUDIO_CHANNEL_IN_3POINT1"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_6"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_2POINT0POINT2"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_2POINT1POINT2"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_3POINT0POINT2"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_3POINT1POINT2"/>
+ <xs:enumeration value="AUDIO_CHANNEL_IN_QUAD"/>
+ <xs:enumeration value="AUDIO_CHANNEL_IN_PENTA"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_5POINT1"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_VOICE_UPLINK_MONO"/>
<xs:enumeration value="AUDIO_CHANNEL_IN_VOICE_DNLINK_MONO"/>
diff --git a/audio/aidl/default/extension/ExtensionEffect.cpp b/audio/aidl/default/extension/ExtensionEffect.cpp
index c4eebc0..4a4d71b6 100644
--- a/audio/aidl/default/extension/ExtensionEffect.cpp
+++ b/audio/aidl/default/extension/ExtensionEffect.cpp
@@ -30,8 +30,8 @@
using aidl::android::hardware::audio::effect::DefaultExtension;
using aidl::android::hardware::audio::effect::Descriptor;
using aidl::android::hardware::audio::effect::ExtensionEffect;
-using aidl::android::hardware::audio::effect::getEffectUuidExtensionImpl;
-using aidl::android::hardware::audio::effect::getEffectUuidExtensionType;
+using aidl::android::hardware::audio::effect::getEffectImplUuidExtension;
+using aidl::android::hardware::audio::effect::getEffectTypeUuidExtension;
using aidl::android::hardware::audio::effect::IEffect;
using aidl::android::hardware::audio::effect::Range;
using aidl::android::hardware::audio::effect::VendorExtension;
@@ -39,7 +39,7 @@
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != getEffectUuidExtensionImpl()) {
+ if (!in_impl_uuid || *in_impl_uuid != getEffectImplUuidExtension()) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
@@ -54,7 +54,7 @@
}
extern "C" binder_exception_t queryEffect(const AudioUuid* in_impl_uuid, Descriptor* _aidl_return) {
- if (!in_impl_uuid || *in_impl_uuid != getEffectUuidExtensionImpl()) {
+ if (!in_impl_uuid || *in_impl_uuid != getEffectImplUuidExtension()) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
@@ -67,8 +67,8 @@
const std::string ExtensionEffect::kEffectName = "ExtensionEffectExample";
const Descriptor ExtensionEffect::kDescriptor = {
- .common = {.id = {.type = getEffectUuidExtensionType(),
- .uuid = getEffectUuidExtensionImpl(),
+ .common = {.id = {.type = getEffectTypeUuidExtension(),
+ .uuid = getEffectImplUuidExtension(),
.proxy = std::nullopt},
.name = ExtensionEffect::kEffectName,
.implementor = "The Android Open Source Project"}};
diff --git a/audio/aidl/default/include/core-impl/AidlConversionXsdc.h b/audio/aidl/default/include/core-impl/AidlConversionXsdc.h
new file mode 100644
index 0000000..c9aefc7
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/AidlConversionXsdc.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2023 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 <aidl/android/hardware/audio/core/SurroundSoundConfig.h>
+#include <aidl/android/media/audio/common/AudioFormatDescription.h>
+#include <android_audio_policy_configuration.h>
+#include <media/AidlConversionUtil.h>
+
+namespace aidl::android::hardware::audio::core::internal {
+
+ConversionResult<::aidl::android::media::audio::common::AudioFormatDescription>
+xsdc2aidl_AudioFormatDescription(const std::string& xsdc);
+
+ConversionResult<SurroundSoundConfig> xsdc2aidl_SurroundSoundConfig(
+ const ::android::audio::policy::configuration::SurroundSound& xsdc);
+
+} // namespace aidl::android::hardware::audio::core::internal
diff --git a/audio/aidl/default/include/core-impl/AudioPolicyConfigXmlConverter.h b/audio/aidl/default/include/core-impl/AudioPolicyConfigXmlConverter.h
index 47918f0..090d585 100644
--- a/audio/aidl/default/include/core-impl/AudioPolicyConfigXmlConverter.h
+++ b/audio/aidl/default/include/core-impl/AudioPolicyConfigXmlConverter.h
@@ -18,6 +18,7 @@
#include <string>
+#include <aidl/android/hardware/audio/core/SurroundSoundConfig.h>
#include <aidl/android/media/audio/common/AudioHalEngineConfig.h>
#include <android_audio_policy_configuration.h>
#include <android_audio_policy_configuration_enums.h>
@@ -35,6 +36,10 @@
::android::status_t getStatus() const { return mConverter.getStatus(); }
const ::aidl::android::media::audio::common::AudioHalEngineConfig& getAidlEngineConfig();
+ const SurroundSoundConfig& getSurroundSoundConfig();
+
+ // Public for testing purposes.
+ static const SurroundSoundConfig& getDefaultSurroundSoundConfig();
private:
const std::optional<::android::audio::policy::configuration::AudioPolicyConfiguration>&
@@ -48,7 +53,6 @@
void parseVolumes();
::aidl::android::media::audio::common::AudioHalVolumeCurve::CurvePoint convertCurvePointToAidl(
const std::string& xsdcCurvePoint);
-
::aidl::android::media::audio::common::AudioHalVolumeCurve convertVolumeCurveToAidl(
const ::android::audio::policy::configuration::Volume& xsdcVolumeCurve);
diff --git a/audio/aidl/default/include/core-impl/Bluetooth.h b/audio/aidl/default/include/core-impl/Bluetooth.h
index 10e9045..44899bc 100644
--- a/audio/aidl/default/include/core-impl/Bluetooth.h
+++ b/audio/aidl/default/include/core-impl/Bluetooth.h
@@ -22,6 +22,15 @@
namespace aidl::android::hardware::audio::core {
+class ParamChangeHandler {
+ public:
+ ParamChangeHandler() = default;
+ void registerHandler(std::function<ndk::ScopedAStatus()> handler) { mHandler = handler; }
+
+ protected:
+ std::function<ndk::ScopedAStatus()> mHandler = nullptr;
+};
+
class Bluetooth : public BnBluetooth {
public:
Bluetooth();
@@ -34,7 +43,7 @@
HfpConfig mHfpConfig;
};
-class BluetoothA2dp : public BnBluetoothA2dp {
+class BluetoothA2dp : public BnBluetoothA2dp, public ParamChangeHandler {
public:
BluetoothA2dp() = default;
@@ -49,7 +58,7 @@
bool mEnabled = false;
};
-class BluetoothLe : public BnBluetoothLe {
+class BluetoothLe : public BnBluetoothLe, public ParamChangeHandler {
public:
BluetoothLe() = default;
diff --git a/audio/aidl/default/include/core-impl/ChildInterface.h b/audio/aidl/default/include/core-impl/ChildInterface.h
new file mode 100644
index 0000000..2421b59
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/ChildInterface.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2023 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 <memory>
+#include <utility>
+
+#include <android/binder_auto_utils.h>
+#include <android/binder_ibinder_platform.h>
+#include <system/thread_defs.h>
+
+namespace aidl::android::hardware::audio::core {
+
+// Helper used for interfaces that require a persistent instance. We hold them via a strong
+// pointer. The binder token is retained for a call to 'setMinSchedulerPolicy'.
+template <class C>
+struct ChildInterface : private std::pair<std::shared_ptr<C>, ndk::SpAIBinder> {
+ ChildInterface() = default;
+ ChildInterface& operator=(const std::shared_ptr<C>& c) {
+ return operator=(std::shared_ptr<C>(c));
+ }
+ ChildInterface& operator=(std::shared_ptr<C>&& c) {
+ this->first = std::move(c);
+ return *this;
+ }
+ explicit operator bool() const { return !!this->first; }
+ C& operator*() const { return *(this->first); }
+ C* operator->() const { return this->first; }
+ // Use 'getInstance' when returning the interface instance.
+ std::shared_ptr<C> getInstance() {
+ if (this->second.get() == nullptr) {
+ this->second = this->first->asBinder();
+ AIBinder_setMinSchedulerPolicy(this->second.get(), SCHED_NORMAL,
+ ANDROID_PRIORITY_AUDIO);
+ }
+ return this->first;
+ }
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/Configuration.h b/audio/aidl/default/include/core-impl/Configuration.h
index 70320e4..6277c38 100644
--- a/audio/aidl/default/include/core-impl/Configuration.h
+++ b/audio/aidl/default/include/core-impl/Configuration.h
@@ -45,6 +45,8 @@
std::unique_ptr<Configuration> getPrimaryConfiguration();
std::unique_ptr<Configuration> getRSubmixConfiguration();
+std::unique_ptr<Configuration> getStubConfiguration();
std::unique_ptr<Configuration> getUsbConfiguration();
+std::unique_ptr<Configuration> getBluetoothConfiguration();
} // namespace aidl::android::hardware::audio::core::internal
diff --git a/audio/aidl/default/include/core-impl/DevicePortProxy.h b/audio/aidl/default/include/core-impl/DevicePortProxy.h
new file mode 100644
index 0000000..13b8c91
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/DevicePortProxy.h
@@ -0,0 +1,242 @@
+/*
+ * Copyright 2023 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 <condition_variable>
+#include <mutex>
+
+#include <android-base/thread_annotations.h>
+
+#include <aidl/android/hardware/audio/common/SinkMetadata.h>
+#include <aidl/android/hardware/audio/common/SourceMetadata.h>
+#include <aidl/android/hardware/bluetooth/audio/BluetoothAudioStatus.h>
+#include <aidl/android/hardware/bluetooth/audio/PcmConfiguration.h>
+#include <aidl/android/hardware/bluetooth/audio/SessionType.h>
+#include <aidl/android/media/audio/common/AudioDeviceDescription.h>
+
+#include "BluetoothAudioSessionControl.h"
+
+namespace android::bluetooth::audio::aidl {
+
+enum class BluetoothStreamState : uint8_t {
+ DISABLED = 0, // This stream is closing or Bluetooth profiles (A2DP/LE) is disabled
+ STANDBY,
+ STARTING,
+ STARTED,
+ SUSPENDING,
+ UNKNOWN,
+};
+
+std::ostream& operator<<(std::ostream& os, const BluetoothStreamState& state);
+
+/**
+ * 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, getState() of DevicePortProxy is only used for
+ * verbose logging, it is not locked, so the state may not be synchronized.
+ */
+class BluetoothAudioPort {
+ public:
+ BluetoothAudioPort() = default;
+ virtual ~BluetoothAudioPort() = default;
+
+ /**
+ * Fetch output control / data path of BluetoothAudioPort and setup
+ * callbacks into BluetoothAudioProvider. If registerPort() returns false, the audio
+ * HAL must delete this BluetoothAudioPort and return EINVAL to caller
+ */
+ virtual bool registerPort(
+ const ::aidl::android::media::audio::common::AudioDeviceDescription&) = 0;
+
+ /**
+ * Unregister this BluetoothAudioPort from BluetoothAudioSessionControl.
+ * Audio HAL must delete this BluetoothAudioPort after calling this.
+ */
+ virtual void unregisterPort() = 0;
+
+ /**
+ * 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
+ */
+ virtual bool loadAudioConfig(
+ ::aidl::android::hardware::bluetooth::audio::PcmConfiguration*) const = 0;
+
+ /**
+ * WAR to support Mono mode / 16 bits per sample
+ */
+ virtual void forcePcmStereoToMono(bool) = 0;
+
+ /**
+ * When the Audio framework / HAL wants to change the stream state, it invokes
+ * these 4 functions to control the Bluetooth stack (Audio Control Path).
+ * Note: standby(), start() and suspend() will return true when there are no errors.
+
+ * Called by Audio framework / HAL to change the state to stand by. When A2DP/LE profile is
+ * disabled, the port is first set to STANDBY by calling suspend and then mState is set to
+ * DISABLED. To reset the state back to STANDBY this method is called.
+ */
+ virtual bool standby() = 0;
+
+ /**
+ * Called by Audio framework / HAL to start the stream
+ */
+ virtual bool start() = 0;
+
+ /**
+ * Called by Audio framework / HAL to suspend the stream
+ */
+ virtual bool suspend() = 0;
+
+ /**
+ * Called by Audio framework / HAL to stop the stream
+ */
+ virtual void stop() = 0;
+
+ /**
+ * Called by the Audio framework / HAL to fetch information about audio frames
+ * presented to an external sink, or frames presented fror an internal sink
+ */
+ virtual bool getPresentationPosition(
+ ::aidl::android::hardware::bluetooth::audio::PresentationPosition&) const = 0;
+
+ /**
+ * Called by the Audio framework / HAL when the metadata of the stream's
+ * source has been changed.
+ */
+ virtual bool updateSourceMetadata(
+ const ::aidl::android::hardware::audio::common::SourceMetadata&) const {
+ return false;
+ }
+
+ /**
+ * Called by the Audio framework / HAL when the metadata of the stream's
+ * sink has been changed.
+ */
+ virtual bool updateSinkMetadata(
+ const ::aidl::android::hardware::audio::common::SinkMetadata&) const {
+ return false;
+ }
+
+ /**
+ * Return the current BluetoothStreamState
+ */
+ virtual BluetoothStreamState getState() const = 0;
+
+ /**
+ * Set the current BluetoothStreamState
+ */
+ virtual bool setState(BluetoothStreamState) = 0;
+
+ virtual bool isA2dp() const = 0;
+
+ virtual bool isLeAudio() const = 0;
+
+ virtual bool getPreferredDataIntervalUs(size_t*) const = 0;
+
+ virtual size_t writeData(const void*, size_t) const { return 0; }
+
+ virtual size_t readData(void*, size_t) const { return 0; }
+};
+
+class BluetoothAudioPortAidl : public BluetoothAudioPort {
+ public:
+ BluetoothAudioPortAidl();
+ virtual ~BluetoothAudioPortAidl();
+
+ bool registerPort(const ::aidl::android::media::audio::common::AudioDeviceDescription&
+ description) override;
+
+ void unregisterPort() override;
+
+ bool loadAudioConfig(::aidl::android::hardware::bluetooth::audio::PcmConfiguration* audio_cfg)
+ const override;
+
+ void forcePcmStereoToMono(bool force) override { mIsStereoToMono = force; }
+
+ bool standby() override;
+ bool start() override;
+ bool suspend() override;
+ void stop() override;
+
+ bool getPresentationPosition(::aidl::android::hardware::bluetooth::audio::PresentationPosition&
+ presentation_position) const override;
+
+ bool updateSourceMetadata(const ::aidl::android::hardware::audio::common::SourceMetadata&
+ sourceMetadata) const override;
+
+ bool updateSinkMetadata(const ::aidl::android::hardware::audio::common::SinkMetadata&
+ sinkMetadata) const override;
+
+ /**
+ * Return the current BluetoothStreamState
+ * Note: This method is used for logging, does not lock, so value returned may not be latest
+ */
+ BluetoothStreamState getState() const override NO_THREAD_SAFETY_ANALYSIS;
+
+ bool setState(BluetoothStreamState state) override;
+
+ bool isA2dp() const override;
+
+ bool isLeAudio() const override;
+
+ bool getPreferredDataIntervalUs(size_t* interval_us) const override;
+
+ protected:
+ uint16_t mCookie;
+ BluetoothStreamState mState GUARDED_BY(mCvMutex);
+ ::aidl::android::hardware::bluetooth::audio::SessionType mSessionType;
+ // WR to support Mono: True if fetching Stereo and mixing into Mono
+ bool mIsStereoToMono = false;
+
+ bool inUse() const;
+
+ std::string debugMessage() const;
+
+ private:
+ // start()/suspend() report state change status via callback. Wait until kMaxWaitingTimeMs or a
+ // state change after a call to start()/suspend() and analyse the returned status. Below mutex,
+ // conditional variable serves this purpose.
+ mutable std::mutex mCvMutex;
+ std::condition_variable mInternalCv GUARDED_BY(mCvMutex);
+
+ // Check and initialize session type for |devices| If failed, this
+ // BluetoothAudioPortAidl is not initialized and must be deleted.
+ bool initSessionType(
+ const ::aidl::android::media::audio::common::AudioDeviceDescription& description);
+
+ bool condWaitState(BluetoothStreamState state);
+
+ void controlResultHandler(
+ uint16_t cookie,
+ const ::aidl::android::hardware::bluetooth::audio::BluetoothAudioStatus& status);
+ void sessionChangedHandler(uint16_t cookie);
+};
+
+class BluetoothAudioPortAidlOut : public BluetoothAudioPortAidl {
+ public:
+ // The audio data path to the Bluetooth stack (Software encoding)
+ size_t writeData(const void* buffer, size_t bytes) const override;
+};
+
+class BluetoothAudioPortAidlIn : public BluetoothAudioPortAidl {
+ public:
+ // The audio data path from the Bluetooth stack (Software decoded)
+ size_t readData(void* buffer, size_t bytes) const override;
+};
+
+} // namespace android::bluetooth::audio::aidl
\ No newline at end of file
diff --git a/audio/aidl/default/include/core-impl/Module.h b/audio/aidl/default/include/core-impl/Module.h
index 83ecfaa..fb3eef2 100644
--- a/audio/aidl/default/include/core-impl/Module.h
+++ b/audio/aidl/default/include/core-impl/Module.h
@@ -16,12 +16,14 @@
#pragma once
+#include <iostream>
#include <map>
#include <memory>
#include <set>
#include <aidl/android/hardware/audio/core/BnModule.h>
+#include "core-impl/ChildInterface.h"
#include "core-impl/Configuration.h"
#include "core-impl/Stream.h"
@@ -31,41 +33,20 @@
public:
// This value is used for all AudioPatches and reported by all streams.
static constexpr int32_t kLatencyMs = 10;
- enum Type : int { DEFAULT, R_SUBMIX, USB };
+ enum Type : int { DEFAULT, R_SUBMIX, STUB, USB, BLUETOOTH };
+ enum BtInterface : int { BTCONF, BTA2DP, BTLE };
+
+ static std::shared_ptr<Module> createInstance(Type type);
explicit Module(Type type) : mType(type) {}
- static std::shared_ptr<Module> createInstance(Type type);
- static StreamIn::CreateInstance getStreamInCreator(Type type);
- static StreamOut::CreateInstance getStreamOutCreator(Type type);
+ typedef std::tuple<std::weak_ptr<IBluetooth>, std::weak_ptr<IBluetoothA2dp>,
+ std::weak_ptr<IBluetoothLe>>
+ BtProfileHandles;
- private:
- struct VendorDebug {
- static const std::string kForceTransientBurstName;
- static const std::string kForceSynchronousDrainName;
- bool forceTransientBurst = false;
- bool forceSynchronousDrain = false;
- };
- // Helper used for interfaces that require a persistent instance. We hold them via a strong
- // pointer. The binder token is retained for a call to 'setMinSchedulerPolicy'.
- template <class C>
- struct ChildInterface : private std::pair<std::shared_ptr<C>, ndk::SpAIBinder> {
- ChildInterface() {}
- ChildInterface& operator=(const std::shared_ptr<C>& c) {
- return operator=(std::shared_ptr<C>(c));
- }
- ChildInterface& operator=(std::shared_ptr<C>&& c) {
- this->first = std::move(c);
- this->second = this->first->asBinder();
- AIBinder_setMinSchedulerPolicy(this->second.get(), SCHED_NORMAL,
- ANDROID_PRIORITY_AUDIO);
- return *this;
- }
- explicit operator bool() const { return !!this->first; }
- C& operator*() const { return *(this->first); }
- C* operator->() const { return this->first; }
- std::shared_ptr<C> getPtr() const { return this->first; }
- };
+ protected:
+ // The vendor extension done via inheritance can override interface methods and augment
+ // a call to the base implementation.
ndk::ScopedAStatus setModuleDebug(
const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) override;
@@ -146,50 +127,53 @@
ndk::ScopedAStatus getAAudioMixerBurstCount(int32_t* _aidl_return) override;
ndk::ScopedAStatus getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) override;
- void cleanUpPatch(int32_t patchId);
- ndk::ScopedAStatus createStreamContext(
- int32_t in_portConfigId, int64_t in_bufferSizeFrames,
- std::shared_ptr<IStreamCallback> asyncCallback,
- std::shared_ptr<IStreamOutEventCallback> outEventCallback,
- ::aidl::android::hardware::audio::core::StreamContext* out_context);
- std::vector<::aidl::android::media::audio::common::AudioDevice> findConnectedDevices(
- int32_t portConfigId);
- std::set<int32_t> findConnectedPortConfigIds(int32_t portConfigId);
- ndk::ScopedAStatus findPortIdForNewStream(
- int32_t in_portConfigId, ::aidl::android::media::audio::common::AudioPort** port);
- internal::Configuration& getConfig();
- template <typename C>
- std::set<int32_t> portIdsFromPortConfigIds(C portConfigIds);
- void registerPatch(const AudioPatch& patch);
- void updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch);
- bool isMmapSupported();
-
// This value is used for all AudioPatches.
static constexpr int32_t kMinimumStreamBufferSizeFrames = 256;
// The maximum stream buffer size is 1 GiB = 2 ** 30 bytes;
static constexpr int32_t kMaximumStreamBufferSizeBytes = 1 << 30;
+ private:
+ struct VendorDebug {
+ static const std::string kForceTransientBurstName;
+ static const std::string kForceSynchronousDrainName;
+ bool forceTransientBurst = false;
+ bool forceSynchronousDrain = false;
+ };
+ // ids of device ports created at runtime via 'connectExternalDevice'.
+ // Also stores a list of ids of mix ports with dynamic profiles that were populated from
+ // the connected port. This list can be empty, thus an int->int multimap can't be used.
+ using ConnectedDevicePorts = std::map<int32_t, std::vector<int32_t>>;
+ // Maps port ids and port config ids to patch ids.
+ // Multimap because both ports and configs can be used by multiple patches.
+ using Patches = std::multimap<int32_t, int32_t>;
+
const Type mType;
std::unique_ptr<internal::Configuration> mConfig;
ModuleDebug mDebug;
VendorDebug mVendorDebug;
- ChildInterface<ITelephony> mTelephony;
- ChildInterface<IBluetooth> mBluetooth;
- ChildInterface<IBluetoothA2dp> mBluetoothA2dp;
- ChildInterface<IBluetoothLe> mBluetoothLe;
- // ids of device ports created at runtime via 'connectExternalDevice'.
- // Also stores ids of mix ports with dynamic profiles which got populated from the connected
- // port.
- std::map<int32_t, std::vector<int32_t>> mConnectedDevicePorts;
+ ConnectedDevicePorts mConnectedDevicePorts;
Streams mStreams;
- // Maps port ids and port config ids to patch ids.
- // Multimap because both ports and configs can be used by multiple patches.
- std::multimap<int32_t, int32_t> mPatches;
+ Patches mPatches;
bool mMicMute = false;
+ bool mMasterMute = false;
+ float mMasterVolume = 1.0f;
ChildInterface<sounddose::ISoundDose> mSoundDose;
std::optional<bool> mIsMmapSupported;
protected:
+ // The following virtual functions are intended for vendor extension via inheritance.
+
+ virtual ndk::ScopedAStatus createInputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
+ std::shared_ptr<StreamIn>* result) = 0;
+ virtual ndk::ScopedAStatus createOutputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+ offloadInfo,
+ std::shared_ptr<StreamOut>* result) = 0;
// If the module is unable to populate the connected device port correctly, the returned error
// code must correspond to the errors of `IModule.connectedExternalDevice` method.
virtual ndk::ScopedAStatus populateConnectedDevicePort(
@@ -203,9 +187,38 @@
const ::aidl::android::media::audio::common::AudioPort& audioPort, bool connected);
virtual ndk::ScopedAStatus onMasterMuteChanged(bool mute);
virtual ndk::ScopedAStatus onMasterVolumeChanged(float volume);
+ virtual std::unique_ptr<internal::Configuration> initializeConfig();
- bool mMasterMute = false;
- float mMasterVolume = 1.0f;
+ // Utility and helper functions accessible to subclasses.
+ ndk::ScopedAStatus bluetoothParametersUpdated();
+ void cleanUpPatch(int32_t patchId);
+ ndk::ScopedAStatus createStreamContext(
+ int32_t in_portConfigId, int64_t in_bufferSizeFrames,
+ std::shared_ptr<IStreamCallback> asyncCallback,
+ std::shared_ptr<IStreamOutEventCallback> outEventCallback,
+ ::aidl::android::hardware::audio::core::StreamContext* out_context);
+ std::vector<::aidl::android::media::audio::common::AudioDevice> findConnectedDevices(
+ int32_t portConfigId);
+ std::set<int32_t> findConnectedPortConfigIds(int32_t portConfigId);
+ ndk::ScopedAStatus findPortIdForNewStream(
+ int32_t in_portConfigId, ::aidl::android::media::audio::common::AudioPort** port);
+ virtual BtProfileHandles getBtProfileManagerHandles();
+ internal::Configuration& getConfig();
+ const ConnectedDevicePorts& getConnectedDevicePorts() const { return mConnectedDevicePorts; }
+ bool getMasterMute() const { return mMasterMute; }
+ bool getMasterVolume() const { return mMasterVolume; }
+ bool getMicMute() const { return mMicMute; }
+ const Patches& getPatches() const { return mPatches; }
+ const Streams& getStreams() const { return mStreams; }
+ Type getType() const { return mType; }
+ bool isMmapSupported();
+ template <typename C>
+ std::set<int32_t> portIdsFromPortConfigIds(C portConfigIds);
+ void registerPatch(const AudioPatch& patch);
+ ndk::ScopedAStatus updateStreamsConnectedState(const AudioPatch& oldPatch,
+ const AudioPatch& newPatch);
};
+std::ostream& operator<<(std::ostream& os, Module::Type t);
+
} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/ModuleAlsa.h b/audio/aidl/default/include/core-impl/ModuleAlsa.h
new file mode 100644
index 0000000..5815961
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/ModuleAlsa.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2023 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 "core-impl/Module.h"
+
+namespace aidl::android::hardware::audio::core {
+
+// This class is intended to be used as a base class for implementations
+// that use TinyAlsa. This can be either a primary module or a USB Audio
+// module. This class does not define a complete module implementation,
+// and should never be used on its own. Derived classes are expected to
+// provide necessary overrides for all interface methods omitted here.
+class ModuleAlsa : public Module {
+ public:
+ explicit ModuleAlsa(Module::Type type) : Module(type) {}
+
+ protected:
+ // Extension methods of 'Module'.
+ ndk::ScopedAStatus populateConnectedDevicePort(
+ ::aidl::android::media::audio::common::AudioPort* audioPort) override;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/ModuleBluetooth.h b/audio/aidl/default/include/core-impl/ModuleBluetooth.h
new file mode 100644
index 0000000..68b4e6b
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/ModuleBluetooth.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2023 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 "core-impl/Bluetooth.h"
+#include "core-impl/Module.h"
+
+namespace aidl::android::hardware::audio::core {
+
+class ModuleBluetooth final : public Module {
+ public:
+ ModuleBluetooth() : Module(Type::BLUETOOTH) {}
+
+ private:
+ BtProfileHandles getBtProfileManagerHandles() override;
+
+ ndk::ScopedAStatus getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) override;
+ ndk::ScopedAStatus getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) override;
+ ndk::ScopedAStatus getMicMute(bool* _aidl_return) override;
+ ndk::ScopedAStatus setMicMute(bool in_mute) override;
+
+ ndk::ScopedAStatus createInputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
+ std::shared_ptr<StreamIn>* result) override;
+ ndk::ScopedAStatus createOutputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+ offloadInfo,
+ std::shared_ptr<StreamOut>* result) override;
+ ndk::ScopedAStatus onMasterMuteChanged(bool mute) override;
+ ndk::ScopedAStatus onMasterVolumeChanged(float volume) override;
+
+ ChildInterface<IBluetoothA2dp> mBluetoothA2dp;
+ ChildInterface<IBluetoothLe> mBluetoothLe;
+};
+
+} // namespace aidl::android::hardware::audio::core
\ No newline at end of file
diff --git a/audio/aidl/default/include/core-impl/ModulePrimary.h b/audio/aidl/default/include/core-impl/ModulePrimary.h
new file mode 100644
index 0000000..6264237
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/ModulePrimary.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2023 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 "core-impl/Module.h"
+
+namespace aidl::android::hardware::audio::core {
+
+class ModulePrimary final : public Module {
+ public:
+ ModulePrimary() : Module(Type::DEFAULT) {}
+
+ protected:
+ ndk::ScopedAStatus getTelephony(std::shared_ptr<ITelephony>* _aidl_return) override;
+
+ ndk::ScopedAStatus createInputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
+ std::shared_ptr<StreamIn>* result) override;
+ ndk::ScopedAStatus createOutputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+ offloadInfo,
+ std::shared_ptr<StreamOut>* result) override;
+
+ private:
+ ChildInterface<ITelephony> mTelephony;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h b/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h
new file mode 100644
index 0000000..c4bf7b9
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/ModuleRemoteSubmix.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2023 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 "core-impl/Module.h"
+
+namespace aidl::android::hardware::audio::core {
+
+class ModuleRemoteSubmix : public Module {
+ public:
+ ModuleRemoteSubmix() : Module(Type::R_SUBMIX) {}
+
+ private:
+ // IModule interfaces
+ ndk::ScopedAStatus getMicMute(bool* _aidl_return) override;
+ ndk::ScopedAStatus setMicMute(bool in_mute) override;
+
+ // Module interfaces
+ ndk::ScopedAStatus createInputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
+ std::shared_ptr<StreamIn>* result) override;
+ ndk::ScopedAStatus createOutputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+ offloadInfo,
+ std::shared_ptr<StreamOut>* result) override;
+ ndk::ScopedAStatus populateConnectedDevicePort(
+ ::aidl::android::media::audio::common::AudioPort* audioPort) override;
+ ndk::ScopedAStatus checkAudioPatchEndpointsMatch(
+ const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sources,
+ const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sinks)
+ override;
+ ndk::ScopedAStatus onMasterMuteChanged(bool mute) override;
+ ndk::ScopedAStatus onMasterVolumeChanged(float volume) override;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/ModuleStub.h b/audio/aidl/default/include/core-impl/ModuleStub.h
new file mode 100644
index 0000000..4f77161
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/ModuleStub.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2023 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 "core-impl/Module.h"
+
+namespace aidl::android::hardware::audio::core {
+
+class ModuleStub final : public Module {
+ public:
+ ModuleStub() : Module(Type::STUB) {}
+
+ protected:
+ ndk::ScopedAStatus getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) override;
+ ndk::ScopedAStatus getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) override;
+ ndk::ScopedAStatus getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) override;
+
+ ndk::ScopedAStatus createInputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
+ std::shared_ptr<StreamIn>* result) override;
+ ndk::ScopedAStatus createOutputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+ offloadInfo,
+ std::shared_ptr<StreamOut>* result) override;
+
+ private:
+ ChildInterface<IBluetooth> mBluetooth;
+ ChildInterface<IBluetoothA2dp> mBluetoothA2dp;
+ ChildInterface<IBluetoothLe> mBluetoothLe;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/ModuleUsb.h b/audio/aidl/default/include/core-impl/ModuleUsb.h
index 1aa2244..a296b8c 100644
--- a/audio/aidl/default/include/core-impl/ModuleUsb.h
+++ b/audio/aidl/default/include/core-impl/ModuleUsb.h
@@ -16,13 +16,13 @@
#pragma once
-#include "core-impl/Module.h"
+#include "core-impl/ModuleAlsa.h"
namespace aidl::android::hardware::audio::core {
-class ModuleUsb : public Module {
+class ModuleUsb final : public ModuleAlsa {
public:
- explicit ModuleUsb(Module::Type type) : Module(type) {}
+ ModuleUsb() : ModuleAlsa(Type::USB) {}
private:
// IModule interfaces
@@ -32,6 +32,17 @@
ndk::ScopedAStatus setMicMute(bool in_mute) override;
// Module interfaces
+ ndk::ScopedAStatus createInputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
+ std::shared_ptr<StreamIn>* result) override;
+ ndk::ScopedAStatus createOutputStream(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+ offloadInfo,
+ std::shared_ptr<StreamOut>* result) override;
ndk::ScopedAStatus populateConnectedDevicePort(
::aidl::android::media::audio::common::AudioPort* audioPort) override;
ndk::ScopedAStatus checkAudioPatchEndpointsMatch(
diff --git a/audio/aidl/default/include/core-impl/Stream.h b/audio/aidl/default/include/core-impl/Stream.h
index 65680df..88fddec 100644
--- a/audio/aidl/default/include/core-impl/Stream.h
+++ b/audio/aidl/default/include/core-impl/Stream.h
@@ -25,6 +25,7 @@
#include <variant>
#include <StreamWorker.h>
+#include <Utils.h>
#include <aidl/android/hardware/audio/common/SinkMetadata.h>
#include <aidl/android/hardware/audio/common/SourceMetadata.h>
#include <aidl/android/hardware/audio/core/BnStreamCommon.h>
@@ -34,12 +35,15 @@
#include <aidl/android/hardware/audio/core/IStreamOutEventCallback.h>
#include <aidl/android/hardware/audio/core/StreamDescriptor.h>
#include <aidl/android/media/audio/common/AudioDevice.h>
+#include <aidl/android/media/audio/common/AudioIoFlags.h>
#include <aidl/android/media/audio/common/AudioOffloadInfo.h>
#include <aidl/android/media/audio/common/MicrophoneInfo.h>
+#include <error/expected_utils.h>
#include <fmq/AidlMessageQueue.h>
#include <system/thread_defs.h>
#include <utils/Errors.h>
+#include "core-impl/ChildInterface.h"
#include "core-impl/utils.h"
namespace aidl::android::hardware::audio::core {
@@ -62,7 +66,8 @@
DataMQ;
// Ensure that this value is not used by any of StreamDescriptor.State enums
- static constexpr int32_t STATE_CLOSED = -1;
+ static constexpr StreamDescriptor::State STATE_CLOSED =
+ static_cast<StreamDescriptor::State>(-1);
struct DebugParameters {
// An extra delay for transient states, in ms.
@@ -75,18 +80,23 @@
StreamContext() = default;
StreamContext(std::unique_ptr<CommandMQ> commandMQ, std::unique_ptr<ReplyMQ> replyMQ,
+ int portId,
const ::aidl::android::media::audio::common::AudioFormatDescription& format,
const ::aidl::android::media::audio::common::AudioChannelLayout& channelLayout,
- int sampleRate, std::unique_ptr<DataMQ> dataMQ,
+ int sampleRate, const ::aidl::android::media::audio::common::AudioIoFlags& flags,
+ int32_t mixPortHandle, std::unique_ptr<DataMQ> dataMQ,
std::shared_ptr<IStreamCallback> asyncCallback,
std::shared_ptr<IStreamOutEventCallback> outEventCallback,
DebugParameters debugParameters)
: mCommandMQ(std::move(commandMQ)),
mInternalCommandCookie(std::rand()),
mReplyMQ(std::move(replyMQ)),
+ mPortId(portId),
mFormat(format),
mChannelLayout(channelLayout),
mSampleRate(sampleRate),
+ mFlags(flags),
+ mMixPortHandle(mixPortHandle),
mDataMQ(std::move(dataMQ)),
mAsyncCallback(asyncCallback),
mOutEventCallback(outEventCallback),
@@ -95,29 +105,38 @@
: mCommandMQ(std::move(other.mCommandMQ)),
mInternalCommandCookie(other.mInternalCommandCookie),
mReplyMQ(std::move(other.mReplyMQ)),
+ mPortId(other.mPortId),
mFormat(other.mFormat),
mChannelLayout(other.mChannelLayout),
mSampleRate(other.mSampleRate),
+ mFlags(std::move(other.mFlags)),
+ mMixPortHandle(other.mMixPortHandle),
mDataMQ(std::move(other.mDataMQ)),
mAsyncCallback(std::move(other.mAsyncCallback)),
mOutEventCallback(std::move(other.mOutEventCallback)),
- mDebugParameters(std::move(other.mDebugParameters)) {}
+ mDebugParameters(std::move(other.mDebugParameters)),
+ mFrameCount(other.mFrameCount) {}
StreamContext& operator=(StreamContext&& other) {
mCommandMQ = std::move(other.mCommandMQ);
mInternalCommandCookie = other.mInternalCommandCookie;
mReplyMQ = std::move(other.mReplyMQ);
+ mPortId = std::move(other.mPortId);
mFormat = std::move(other.mFormat);
mChannelLayout = std::move(other.mChannelLayout);
mSampleRate = other.mSampleRate;
+ mFlags = std::move(other.mFlags);
+ mMixPortHandle = other.mMixPortHandle;
mDataMQ = std::move(other.mDataMQ);
mAsyncCallback = std::move(other.mAsyncCallback);
mOutEventCallback = std::move(other.mOutEventCallback);
mDebugParameters = std::move(other.mDebugParameters);
+ mFrameCount = other.mFrameCount;
return *this;
}
void fillDescriptor(StreamDescriptor* desc);
std::shared_ptr<IStreamCallback> getAsyncCallback() const { return mAsyncCallback; }
+ size_t getBufferSizeInFrames() const;
::aidl::android::media::audio::common::AudioChannelLayout getChannelLayout() const {
return mChannelLayout;
}
@@ -126,73 +145,85 @@
::aidl::android::media::audio::common::AudioFormatDescription getFormat() const {
return mFormat;
}
+ ::aidl::android::media::audio::common::AudioIoFlags getFlags() const { return mFlags; }
bool getForceTransientBurst() const { return mDebugParameters.forceTransientBurst; }
bool getForceSynchronousDrain() const { return mDebugParameters.forceSynchronousDrain; }
size_t getFrameSize() const;
int getInternalCommandCookie() const { return mInternalCommandCookie; }
+ int32_t getMixPortHandle() const { return mMixPortHandle; }
std::shared_ptr<IStreamOutEventCallback> getOutEventCallback() const {
return mOutEventCallback;
}
+ int getPortId() const { return mPortId; }
ReplyMQ* getReplyMQ() const { return mReplyMQ.get(); }
int getTransientStateDelayMs() const { return mDebugParameters.transientStateDelayMs; }
int getSampleRate() const { return mSampleRate; }
bool isValid() const;
+ // 'reset' is called on a Binder thread when closing the stream. Does not use
+ // locking because it only cleans MQ pointers which were also set on the Binder thread.
void reset();
+ // 'advanceFrameCount' and 'getFrameCount' are only called on the worker thread.
+ long advanceFrameCount(size_t increase) { return mFrameCount += increase; }
+ long getFrameCount() const { return mFrameCount; }
private:
std::unique_ptr<CommandMQ> mCommandMQ;
int mInternalCommandCookie; // The value used to confirm that the command was posted internally
std::unique_ptr<ReplyMQ> mReplyMQ;
+ int mPortId;
::aidl::android::media::audio::common::AudioFormatDescription mFormat;
::aidl::android::media::audio::common::AudioChannelLayout mChannelLayout;
int mSampleRate;
+ ::aidl::android::media::audio::common::AudioIoFlags mFlags;
+ int32_t mMixPortHandle;
std::unique_ptr<DataMQ> mDataMQ;
std::shared_ptr<IStreamCallback> mAsyncCallback;
std::shared_ptr<IStreamOutEventCallback> mOutEventCallback; // Only used by output streams
DebugParameters mDebugParameters;
+ long mFrameCount = 0;
};
+// This interface provides operations of the stream which are executed on the worker thread.
struct DriverInterface {
- using CreateInstance = std::function<DriverInterface*(const StreamContext&)>;
virtual ~DriverInterface() = default;
- // This function is called once, on the main thread, before starting the worker thread.
- virtual ::android::status_t init() = 0;
- // This function is called from Binder pool thread. It must be done in a thread-safe manner
- // if this method and other methods in this interface share data.
- virtual ::android::status_t setConnectedDevices(
- const std::vector<::aidl::android::media::audio::common::AudioDevice>&
- connectedDevices) = 0;
- // All the functions below are called on the worker thread.
+ // All the methods below are called on the worker thread.
+ virtual ::android::status_t init() = 0; // This function is only called once.
virtual ::android::status_t drain(StreamDescriptor::DrainMode mode) = 0;
virtual ::android::status_t flush() = 0;
virtual ::android::status_t pause() = 0;
+ virtual ::android::status_t standby() = 0;
+ virtual ::android::status_t start() = 0;
virtual ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
int32_t* latencyMs) = 0;
- virtual ::android::status_t standby() = 0;
+ // No need to implement 'refinePosition' unless the driver can provide more precise
+ // data than just total frame count. For example, the driver may correctly account
+ // for any intermediate buffers.
+ virtual ::android::status_t refinePosition(StreamDescriptor::Position* /*position*/) {
+ return ::android::OK;
+ }
+ virtual void shutdown() = 0; // This function is only called once.
};
class StreamWorkerCommonLogic : public ::android::hardware::audio::common::StreamLogic {
public:
- bool isClosed() const {
- return static_cast<int32_t>(mState.load()) == StreamContext::STATE_CLOSED;
+ bool isClosed() const { return mState == StreamContext::STATE_CLOSED; }
+ StreamDescriptor::State setClosed() {
+ auto prevState = mState.exchange(StreamContext::STATE_CLOSED);
+ if (prevState != StreamContext::STATE_CLOSED) {
+ mStatePriorToClosing = prevState;
+ }
+ return mStatePriorToClosing;
}
- void setClosed() { mState = static_cast<StreamDescriptor::State>(StreamContext::STATE_CLOSED); }
void setIsConnected(bool connected) { mIsConnected = connected; }
protected:
using DataBufferElement = int8_t;
- StreamWorkerCommonLogic(const StreamContext& context, DriverInterface* driver)
- : mDriver(driver),
- mInternalCommandCookie(context.getInternalCommandCookie()),
- mFrameSize(context.getFrameSize()),
- mCommandMQ(context.getCommandMQ()),
- mReplyMQ(context.getReplyMQ()),
- mDataMQ(context.getDataMQ()),
- mAsyncCallback(context.getAsyncCallback()),
- mTransientStateDelayMs(context.getTransientStateDelayMs()),
- mForceTransientBurst(context.getForceTransientBurst()),
- mForceSynchronousDrain(context.getForceSynchronousDrain()) {}
+ StreamWorkerCommonLogic(StreamContext* context, DriverInterface* driver)
+ : mContext(context),
+ mDriver(driver),
+ mTransientStateDelayMs(context->getTransientStateDelayMs()) {}
+ pid_t getTid() const;
std::string init() override;
void populateReply(StreamDescriptor::Reply* reply, bool isConnected) const;
void populateReplyWrongState(StreamDescriptor::Reply* reply,
@@ -202,39 +233,37 @@
mTransientStateStart = std::chrono::steady_clock::now();
}
+ // The context is only used for reading, except for updating the frame count,
+ // which happens on the worker thread only.
+ StreamContext* const mContext;
DriverInterface* const mDriver;
+ // This is the state the stream was in before being closed. It is retrieved by the main
+ // thread after joining the worker thread.
+ StreamDescriptor::State mStatePriorToClosing = StreamDescriptor::State::STANDBY;
// Atomic fields are used both by the main and worker threads.
std::atomic<bool> mIsConnected = false;
static_assert(std::atomic<StreamDescriptor::State>::is_always_lock_free);
std::atomic<StreamDescriptor::State> mState = StreamDescriptor::State::STANDBY;
- // All fields are used on the worker thread only.
- const int mInternalCommandCookie;
- const size_t mFrameSize;
- StreamContext::CommandMQ* const mCommandMQ;
- StreamContext::ReplyMQ* const mReplyMQ;
- StreamContext::DataMQ* const mDataMQ;
- std::shared_ptr<IStreamCallback> mAsyncCallback;
+ // All fields below are used on the worker thread only.
const std::chrono::duration<int, std::milli> mTransientStateDelayMs;
std::chrono::time_point<std::chrono::steady_clock> mTransientStateStart;
- const bool mForceTransientBurst;
- const bool mForceSynchronousDrain;
// We use an array and the "size" field instead of a vector to be able to detect
// memory allocation issues.
std::unique_ptr<DataBufferElement[]> mDataBuffer;
size_t mDataBufferSize;
- long mFrameCount = 0;
};
// This interface is used to decouple stream implementations from a concrete StreamWorker
// implementation.
struct StreamWorkerInterface {
- using CreateInstance = std::function<StreamWorkerInterface*(const StreamContext& context,
- DriverInterface* driver)>;
+ using CreateInstance =
+ std::function<StreamWorkerInterface*(StreamContext* context, DriverInterface* driver)>;
virtual ~StreamWorkerInterface() = default;
virtual bool isClosed() const = 0;
virtual void setIsConnected(bool isConnected) = 0;
- virtual void setClosed() = 0;
+ virtual StreamDescriptor::State setClosed() = 0;
virtual bool start() = 0;
+ virtual pid_t getTid() = 0;
virtual void stop() = 0;
};
@@ -244,21 +273,23 @@
using WorkerImpl = ::android::hardware::audio::common::StreamWorker<WorkerLogic>;
public:
- StreamWorkerImpl(const StreamContext& context, DriverInterface* driver)
+ StreamWorkerImpl(StreamContext* context, DriverInterface* driver)
: WorkerImpl(context, driver) {}
bool isClosed() const override { return WorkerImpl::isClosed(); }
void setIsConnected(bool isConnected) override { WorkerImpl::setIsConnected(isConnected); }
- void setClosed() override { WorkerImpl::setClosed(); }
+ StreamDescriptor::State setClosed() override { return WorkerImpl::setClosed(); }
bool start() override {
- return WorkerImpl::start(WorkerImpl::kThreadName, ANDROID_PRIORITY_AUDIO);
+ // This is an "audio service thread," must have elevated priority.
+ return WorkerImpl::start(WorkerImpl::kThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
}
+ pid_t getTid() override { return WorkerImpl::getTid(); }
void stop() override { return WorkerImpl::stop(); }
};
class StreamInWorkerLogic : public StreamWorkerCommonLogic {
public:
static const std::string kThreadName;
- StreamInWorkerLogic(const StreamContext& context, DriverInterface* driver)
+ StreamInWorkerLogic(StreamContext* context, DriverInterface* driver)
: StreamWorkerCommonLogic(context, driver) {}
protected:
@@ -272,8 +303,9 @@
class StreamOutWorkerLogic : public StreamWorkerCommonLogic {
public:
static const std::string kThreadName;
- StreamOutWorkerLogic(const StreamContext& context, DriverInterface* driver)
- : StreamWorkerCommonLogic(context, driver), mEventCallback(context.getOutEventCallback()) {}
+ StreamOutWorkerLogic(StreamContext* context, DriverInterface* driver)
+ : StreamWorkerCommonLogic(context, driver),
+ mEventCallback(context->getOutEventCallback()) {}
protected:
Status cycle() override;
@@ -285,14 +317,20 @@
};
using StreamOutWorker = StreamWorkerImpl<StreamOutWorkerLogic>;
-// This provides a C++ interface with methods of the IStreamCommon Binder interface,
-// but intentionally does not inherit from it. This is needed to avoid inheriting
-// StreamIn and StreamOut from two Binder interface classes, as these parts of the class
-// will be reference counted separately.
-//
-// The implementation of these common methods is in the StreamCommonImpl template class.
+// This interface provides operations of the stream which are executed on a Binder pool thread.
+// These methods originate both from the AIDL interface and its implementation.
struct StreamCommonInterface {
+ using ConnectedDevices = std::vector<::aidl::android::media::audio::common::AudioDevice>;
+ using Metadata =
+ std::variant<::aidl::android::hardware::audio::common::SinkMetadata /*IStreamIn*/,
+ ::aidl::android::hardware::audio::common::SourceMetadata /*IStreamOut*/>;
+
+ static constexpr bool isInput(const Metadata& metadata) { return metadata.index() == 0; }
+
virtual ~StreamCommonInterface() = default;
+ // Methods below originate from the 'IStreamCommon' interface.
+ // This is semantically equivalent to inheriting from 'IStreamCommon' with a benefit
+ // that concrete stream implementations can inherit both from this interface and IStreamIn/Out.
virtual ndk::ScopedAStatus close() = 0;
virtual ndk::ScopedAStatus prepareToClose() = 0;
virtual ndk::ScopedAStatus updateHwAvSyncId(int32_t in_hwAvSyncId) = 0;
@@ -306,11 +344,31 @@
virtual ndk::ScopedAStatus removeEffect(
const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>&
in_effect) = 0;
+ // Methods below are common for both 'IStreamIn' and 'IStreamOut'. Note that
+ // 'updateMetadata' in them uses an individual structure which is wrapped here.
+ // The 'Common' suffix is added to distinguish them from the methods from 'IStreamIn/Out'.
+ virtual ndk::ScopedAStatus getStreamCommonCommon(
+ std::shared_ptr<IStreamCommon>* _aidl_return) = 0;
+ virtual ndk::ScopedAStatus updateMetadataCommon(const Metadata& metadata) = 0;
+ // Methods below are called by implementation of 'IModule', 'IStreamIn' and 'IStreamOut'.
+ virtual ndk::ScopedAStatus initInstance(
+ const std::shared_ptr<StreamCommonInterface>& delegate) = 0;
+ virtual const StreamContext& getContext() const = 0;
+ virtual bool isClosed() const = 0;
+ virtual const ConnectedDevices& getConnectedDevices() const = 0;
+ virtual ndk::ScopedAStatus setConnectedDevices(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) = 0;
+ virtual ndk::ScopedAStatus bluetoothParametersUpdated() = 0;
};
-class StreamCommon : public BnStreamCommon {
+// This is equivalent to automatically generated 'IStreamCommonDelegator' but uses
+// a weak pointer to avoid creating a reference loop. The loop will occur because
+// 'IStreamIn/Out.getStreamCommon' must return the same instance every time, thus
+// the stream implementation must hold a strong pointer to an instance of 'IStreamCommon'.
+// Also, we use 'StreamCommonInterface' here instead of 'IStreamCommon'.
+class StreamCommonDelegator : public BnStreamCommon {
public:
- explicit StreamCommon(const std::shared_ptr<StreamCommonInterface>& delegate)
+ explicit StreamCommonDelegator(const std::shared_ptr<StreamCommonInterface>& delegate)
: mDelegate(delegate) {}
private:
@@ -361,9 +419,21 @@
std::weak_ptr<StreamCommonInterface> mDelegate;
};
-template <class Metadata>
-class StreamCommonImpl : public StreamCommonInterface {
+// The implementation of DriverInterface must be provided by each concrete stream implementation.
+// Note that StreamCommonImpl does not own the context. This is to support swapping on the fly
+// implementations of the stream while keeping the same IStreamIn/Out instance. It's that instance
+// who must be owner of the context.
+class StreamCommonImpl : virtual public StreamCommonInterface, virtual public DriverInterface {
public:
+ StreamCommonImpl(StreamContext* context, const Metadata& metadata,
+ const StreamWorkerInterface::CreateInstance& createWorker)
+ : mContext(*context), mMetadata(metadata), mWorker(createWorker(context, this)) {}
+ StreamCommonImpl(StreamContext* context, const Metadata& metadata)
+ : StreamCommonImpl(
+ context, metadata,
+ isInput(metadata) ? getDefaultInWorkerCreator() : getDefaultOutWorkerCreator()) {}
+ ~StreamCommonImpl();
+
ndk::ScopedAStatus close() override;
ndk::ScopedAStatus prepareToClose() override;
ndk::ScopedAStatus updateHwAvSyncId(int32_t in_hwAvSyncId) override;
@@ -378,46 +448,53 @@
const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect)
override;
- ndk::ScopedAStatus getStreamCommon(std::shared_ptr<IStreamCommon>* _aidl_return);
- ndk::ScopedAStatus init() {
- return mWorker->start() ? ndk::ScopedAStatus::ok()
- : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
- }
- bool isClosed() const { return mWorker->isClosed(); }
- void setIsConnected(
- const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
- mWorker->setIsConnected(!devices.empty());
- mConnectedDevices = devices;
- mDriver->setConnectedDevices(devices);
- }
- ndk::ScopedAStatus updateMetadata(const Metadata& metadata);
+ ndk::ScopedAStatus getStreamCommonCommon(std::shared_ptr<IStreamCommon>* _aidl_return) override;
+ ndk::ScopedAStatus updateMetadataCommon(const Metadata& metadata) override;
+
+ ndk::ScopedAStatus initInstance(
+ const std::shared_ptr<StreamCommonInterface>& delegate) override;
+ const StreamContext& getContext() const override { return mContext; }
+ bool isClosed() const override { return mWorker->isClosed(); }
+ const ConnectedDevices& getConnectedDevices() const override { return mConnectedDevices; }
+ ndk::ScopedAStatus setConnectedDevices(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices)
+ override;
+ ndk::ScopedAStatus bluetoothParametersUpdated() override;
protected:
- StreamCommonImpl(const Metadata& metadata, StreamContext&& context,
- const DriverInterface::CreateInstance& createDriver,
- const StreamWorkerInterface::CreateInstance& createWorker)
- : mMetadata(metadata),
- mContext(std::move(context)),
- mDriver(createDriver(mContext)),
- mWorker(createWorker(mContext, mDriver.get())) {}
- ~StreamCommonImpl();
- void stopWorker();
- void createStreamCommon(const std::shared_ptr<StreamCommonInterface>& delegate);
+ static StreamWorkerInterface::CreateInstance getDefaultInWorkerCreator() {
+ return [](StreamContext* ctx, DriverInterface* driver) -> StreamWorkerInterface* {
+ return new StreamInWorker(ctx, driver);
+ };
+ }
+ static StreamWorkerInterface::CreateInstance getDefaultOutWorkerCreator() {
+ return [](StreamContext* ctx, DriverInterface* driver) -> StreamWorkerInterface* {
+ return new StreamOutWorker(ctx, driver);
+ };
+ }
- std::shared_ptr<StreamCommon> mCommon;
- ndk::SpAIBinder mCommonBinder;
+ virtual void onClose(StreamDescriptor::State statePriorToClosing) = 0;
+ void stopWorker();
+
+ const StreamContext& mContext;
Metadata mMetadata;
- StreamContext mContext;
- std::unique_ptr<DriverInterface> mDriver;
std::unique_ptr<StreamWorkerInterface> mWorker;
- std::vector<::aidl::android::media::audio::common::AudioDevice> mConnectedDevices;
+ ChildInterface<StreamCommonDelegator> mCommon;
+ ConnectedDevices mConnectedDevices;
};
-class StreamIn : public StreamCommonImpl<::aidl::android::hardware::audio::common::SinkMetadata>,
- public BnStreamIn {
+// Note: 'StreamIn/Out' can not be used on their own. Instead, they must be used for defining
+// concrete input/output stream implementations.
+class StreamIn : virtual public StreamCommonInterface, public BnStreamIn {
+ protected:
+ void defaultOnClose();
+
ndk::ScopedAStatus getStreamCommon(std::shared_ptr<IStreamCommon>* _aidl_return) override {
- return StreamCommonImpl<::aidl::android::hardware::audio::common::SinkMetadata>::
- getStreamCommon(_aidl_return);
+ return getStreamCommonCommon(_aidl_return);
+ }
+ ndk::ScopedAStatus updateMetadata(const ::aidl::android::hardware::audio::common::SinkMetadata&
+ in_sinkMetadata) override {
+ return updateMetadataCommon(in_sinkMetadata);
}
ndk::ScopedAStatus getActiveMicrophones(
std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo>* _aidl_return)
@@ -426,49 +503,40 @@
ndk::ScopedAStatus setMicrophoneDirection(MicrophoneDirection in_direction) override;
ndk::ScopedAStatus getMicrophoneFieldDimension(float* _aidl_return) override;
ndk::ScopedAStatus setMicrophoneFieldDimension(float in_zoom) override;
- ndk::ScopedAStatus updateMetadata(const ::aidl::android::hardware::audio::common::SinkMetadata&
- in_sinkMetadata) override {
- return StreamCommonImpl<::aidl::android::hardware::audio::common::SinkMetadata>::
- updateMetadata(in_sinkMetadata);
- }
ndk::ScopedAStatus getHwGain(std::vector<float>* _aidl_return) override;
ndk::ScopedAStatus setHwGain(const std::vector<float>& in_channelGains) override;
- protected:
friend class ndk::SharedRefBase;
- static ndk::ScopedAStatus initInstance(const std::shared_ptr<StreamIn>& stream);
-
- StreamIn(const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
- StreamContext&& context, const DriverInterface::CreateInstance& createDriver,
- const StreamWorkerInterface::CreateInstance& createWorker,
+ StreamIn(StreamContext&& context,
const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones);
- void createStreamCommon(const std::shared_ptr<StreamIn>& myPtr) {
- StreamCommonImpl<
- ::aidl::android::hardware::audio::common::SinkMetadata>::createStreamCommon(myPtr);
- }
+ StreamContext mContextInstance;
const std::map<::aidl::android::media::audio::common::AudioDevice, std::string> mMicrophones;
-
- public:
- using CreateInstance = std::function<ndk::ScopedAStatus(
- const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
- StreamContext&& context,
- const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
- std::shared_ptr<StreamIn>* result)>;
};
-class StreamOut : public StreamCommonImpl<::aidl::android::hardware::audio::common::SourceMetadata>,
- public BnStreamOut {
+class StreamInHwGainHelper {
+ protected:
+ explicit StreamInHwGainHelper(const StreamContext* context);
+
+ ndk::ScopedAStatus getHwGainImpl(std::vector<float>* _aidl_return);
+ ndk::ScopedAStatus setHwGainImpl(const std::vector<float>& in_channelGains);
+
+ const size_t mChannelCount;
+ std::vector<float> mHwGains;
+};
+
+class StreamOut : virtual public StreamCommonInterface, public BnStreamOut {
+ protected:
+ void defaultOnClose();
+
ndk::ScopedAStatus getStreamCommon(std::shared_ptr<IStreamCommon>* _aidl_return) override {
- return StreamCommonImpl<::aidl::android::hardware::audio::common::SourceMetadata>::
- getStreamCommon(_aidl_return);
+ return getStreamCommonCommon(_aidl_return);
}
ndk::ScopedAStatus updateMetadata(
const ::aidl::android::hardware::audio::common::SourceMetadata& in_sourceMetadata)
override {
- return StreamCommonImpl<::aidl::android::hardware::audio::common::SourceMetadata>::
- updateMetadata(in_sourceMetadata);
+ return updateMetadataCommon(in_sourceMetadata);
}
ndk::ScopedAStatus updateOffloadMetadata(
const ::aidl::android::hardware::audio::common::AudioOffloadMetadata&
@@ -493,34 +561,40 @@
override;
ndk::ScopedAStatus selectPresentation(int32_t in_presentationId, int32_t in_programId) override;
- void createStreamCommon(const std::shared_ptr<StreamOut>& myPtr) {
- StreamCommonImpl<::aidl::android::hardware::audio::common::SourceMetadata>::
- createStreamCommon(myPtr);
- }
-
- protected:
friend class ndk::SharedRefBase;
- static ndk::ScopedAStatus initInstance(const std::shared_ptr<StreamOut>& stream);
-
- StreamOut(const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
- StreamContext&& context, const DriverInterface::CreateInstance& createDriver,
- const StreamWorkerInterface::CreateInstance& createWorker,
+ StreamOut(StreamContext&& context,
const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
offloadInfo);
- std::optional<::aidl::android::media::audio::common::AudioOffloadInfo> mOffloadInfo;
+ StreamContext mContextInstance;
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo> mOffloadInfo;
std::optional<::aidl::android::hardware::audio::common::AudioOffloadMetadata> mOffloadMetadata;
-
- public:
- using CreateInstance = std::function<ndk::ScopedAStatus(
- const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
- StreamContext&& context,
- const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
- offloadInfo,
- std::shared_ptr<StreamOut>* result)>;
};
+class StreamOutHwVolumeHelper {
+ protected:
+ explicit StreamOutHwVolumeHelper(const StreamContext* context);
+
+ ndk::ScopedAStatus getHwVolumeImpl(std::vector<float>* _aidl_return);
+ ndk::ScopedAStatus setHwVolumeImpl(const std::vector<float>& in_channelVolumes);
+
+ const size_t mChannelCount;
+ std::vector<float> mHwVolumes;
+};
+
+// The recommended way to create a stream instance.
+// 'StreamImpl' is the concrete stream implementation, 'StreamInOrOut' is either 'StreamIn' or
+// 'StreamOut', the rest are the arguments forwarded to the constructor of 'StreamImpl'.
+template <class StreamImpl, class StreamInOrOut, class... Args>
+ndk::ScopedAStatus createStreamInstance(std::shared_ptr<StreamInOrOut>* result, Args&&... args) {
+ std::shared_ptr<StreamInOrOut> stream =
+ ::ndk::SharedRefBase::make<StreamImpl>(std::forward<Args>(args)...);
+ RETURN_STATUS_IF_ERROR(stream->initInstance(stream));
+ *result = std::move(stream);
+ return ndk::ScopedAStatus::ok();
+}
+
class StreamWrapper {
public:
explicit StreamWrapper(const std::shared_ptr<StreamIn>& streamIn)
@@ -529,25 +603,23 @@
: mStream(streamOut), mStreamBinder(streamOut->asBinder()) {}
ndk::SpAIBinder getBinder() const { return mStreamBinder; }
bool isStreamOpen() const {
- return std::visit(
- [](auto&& ws) -> bool {
- auto s = ws.lock();
- return s && !s->isClosed();
- },
- mStream);
+ auto s = mStream.lock();
+ return s && !s->isClosed();
}
- void setStreamIsConnected(
+ ndk::ScopedAStatus setConnectedDevices(
const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
- std::visit(
- [&](auto&& ws) {
- auto s = ws.lock();
- if (s) s->setIsConnected(devices);
- },
- mStream);
+ auto s = mStream.lock();
+ if (s) return s->setConnectedDevices(devices);
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus bluetoothParametersUpdated() {
+ auto s = mStream.lock();
+ if (s) return s->bluetoothParametersUpdated();
+ return ndk::ScopedAStatus::ok();
}
private:
- std::variant<std::weak_ptr<StreamIn>, std::weak_ptr<StreamOut>> mStream;
+ std::weak_ptr<StreamCommonInterface> mStream;
ndk::SpAIBinder mStreamBinder;
};
@@ -565,12 +637,21 @@
mStreams.insert(std::pair{portConfigId, sw});
mStreams.insert(std::pair{portId, std::move(sw)});
}
- void setStreamIsConnected(
+ ndk::ScopedAStatus setStreamConnectedDevices(
int32_t portConfigId,
const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
if (auto it = mStreams.find(portConfigId); it != mStreams.end()) {
- it->second.setStreamIsConnected(devices);
+ return it->second.setConnectedDevices(devices);
}
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus bluetoothParametersUpdated() {
+ bool isOk = true;
+ for (auto& it : mStreams) {
+ if (!it.second.bluetoothParametersUpdated().isOk()) isOk = false;
+ }
+ return isOk ? ndk::ScopedAStatus::ok()
+ : ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
private:
diff --git a/audio/aidl/default/include/core-impl/StreamAlsa.h b/audio/aidl/default/include/core-impl/StreamAlsa.h
new file mode 100644
index 0000000..2c3b284
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/StreamAlsa.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2023 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 <optional>
+#include <vector>
+
+#include "Stream.h"
+#include "alsa/Utils.h"
+
+namespace aidl::android::hardware::audio::core {
+
+// This class is intended to be used as a base class for implementations
+// that use TinyAlsa.
+// This class does not define a complete stream implementation,
+// and should never be used on its own. Derived classes are expected to
+// provide necessary overrides for all interface methods omitted here.
+class StreamAlsa : public StreamCommonImpl {
+ public:
+ StreamAlsa(StreamContext* context, const Metadata& metadata, int readWriteRetries);
+ // Methods of 'DriverInterface'.
+ ::android::status_t init() override;
+ ::android::status_t drain(StreamDescriptor::DrainMode) override;
+ ::android::status_t flush() override;
+ ::android::status_t pause() override;
+ ::android::status_t standby() override;
+ ::android::status_t start() override;
+ ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
+ int32_t* latencyMs) override;
+ ::android::status_t refinePosition(StreamDescriptor::Position* position) override;
+ void shutdown() override;
+
+ protected:
+ // Called from 'start' to initialize 'mAlsaDeviceProxies', the vector must be non-empty.
+ virtual std::vector<alsa::DeviceProfile> getDeviceProfiles() = 0;
+
+ const size_t mBufferSizeFrames;
+ const size_t mFrameSizeBytes;
+ const int mSampleRate;
+ const bool mIsInput;
+ const std::optional<struct pcm_config> mConfig;
+ const int mReadWriteRetries;
+ // All fields below are only used on the worker thread.
+ std::vector<alsa::DeviceProxy> mAlsaDeviceProxies;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/StreamBluetooth.h b/audio/aidl/default/include/core-impl/StreamBluetooth.h
new file mode 100644
index 0000000..c2f8c1d
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/StreamBluetooth.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2023 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 <mutex>
+#include <vector>
+
+#include <aidl/android/hardware/audio/core/IBluetooth.h>
+#include <aidl/android/hardware/audio/core/IBluetoothA2dp.h>
+#include <aidl/android/hardware/audio/core/IBluetoothLe.h>
+
+#include "core-impl/DevicePortProxy.h"
+#include "core-impl/Module.h"
+#include "core-impl/Stream.h"
+
+namespace aidl::android::hardware::audio::core {
+
+class StreamBluetooth : public StreamCommonImpl {
+ public:
+ StreamBluetooth(StreamContext* context, const Metadata& metadata,
+ Module::BtProfileHandles&& btHandles);
+ // Methods of 'DriverInterface'.
+ ::android::status_t init() override;
+ ::android::status_t drain(StreamDescriptor::DrainMode) override;
+ ::android::status_t flush() override;
+ ::android::status_t pause() override;
+ ::android::status_t standby() override;
+ ::android::status_t start() override;
+ ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
+ int32_t* latencyMs) override;
+ void shutdown() override;
+
+ // Overridden methods of 'StreamCommonImpl', called on a Binder thread.
+ ndk::ScopedAStatus updateMetadataCommon(const Metadata& metadata) override;
+ ndk::ScopedAStatus prepareToClose() override;
+ const ConnectedDevices& getConnectedDevices() const override;
+ ndk::ScopedAStatus setConnectedDevices(const ConnectedDevices& devices) override;
+ ndk::ScopedAStatus bluetoothParametersUpdated() override;
+
+ private:
+ // Audio Pcm Config
+ const uint32_t mSampleRate;
+ const ::aidl::android::media::audio::common::AudioChannelLayout mChannelLayout;
+ const ::aidl::android::media::audio::common::AudioFormatDescription mFormat;
+ const size_t mFrameSizeBytes;
+ const bool mIsInput;
+ const std::weak_ptr<IBluetoothA2dp> mBluetoothA2dp;
+ const std::weak_ptr<IBluetoothLe> mBluetoothLe;
+ size_t mPreferredDataIntervalUs;
+ size_t mPreferredFrameCount;
+
+ mutable std::mutex mLock;
+ bool mIsInitialized GUARDED_BY(mLock);
+ bool mIsReadyToClose GUARDED_BY(mLock);
+ std::vector<std::shared_ptr<::android::bluetooth::audio::aidl::BluetoothAudioPortAidl>>
+ mBtDeviceProxies GUARDED_BY(mLock);
+
+ ::android::status_t initialize() REQUIRES(mLock);
+ bool checkConfigParams(::aidl::android::hardware::bluetooth::audio::PcmConfiguration& config);
+};
+
+class StreamInBluetooth final : public StreamIn, public StreamBluetooth {
+ public:
+ friend class ndk::SharedRefBase;
+ StreamInBluetooth(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
+ Module::BtProfileHandles&& btHandles);
+
+ private:
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
+ ndk::ScopedAStatus getActiveMicrophones(
+ std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo>* _aidl_return)
+ override;
+};
+
+class StreamOutBluetooth final : public StreamOut, public StreamBluetooth {
+ public:
+ friend class ndk::SharedRefBase;
+ StreamOutBluetooth(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+ offloadInfo,
+ Module::BtProfileHandles&& btHandles);
+
+ private:
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/StreamPrimary.h b/audio/aidl/default/include/core-impl/StreamPrimary.h
new file mode 100644
index 0000000..b3ddd0b
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/StreamPrimary.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2023 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 <vector>
+
+#include "StreamAlsa.h"
+#include "StreamSwitcher.h"
+
+namespace aidl::android::hardware::audio::core {
+
+class StreamPrimary : public StreamAlsa {
+ public:
+ StreamPrimary(StreamContext* context, const Metadata& metadata);
+
+ protected:
+ std::vector<alsa::DeviceProfile> getDeviceProfiles() override;
+
+ const bool mIsInput;
+};
+
+class StreamInPrimary final : public StreamIn, public StreamSwitcher, public StreamInHwGainHelper {
+ public:
+ friend class ndk::SharedRefBase;
+ StreamInPrimary(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones);
+
+ private:
+ static bool useStubStream(const ::aidl::android::media::audio::common::AudioDevice& device);
+
+ DeviceSwitchBehavior switchCurrentStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices)
+ override;
+ std::unique_ptr<StreamCommonInterfaceEx> createNewStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
+ StreamContext* context, const Metadata& metadata) override;
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
+
+ ndk::ScopedAStatus getHwGain(std::vector<float>* _aidl_return) override;
+ ndk::ScopedAStatus setHwGain(const std::vector<float>& in_channelGains) override;
+};
+
+class StreamOutPrimary final : public StreamOut,
+ public StreamSwitcher,
+ public StreamOutHwVolumeHelper {
+ public:
+ friend class ndk::SharedRefBase;
+ StreamOutPrimary(StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+ offloadInfo);
+
+ private:
+ static bool useStubStream(const ::aidl::android::media::audio::common::AudioDevice& device);
+
+ DeviceSwitchBehavior switchCurrentStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices)
+ override;
+ std::unique_ptr<StreamCommonInterfaceEx> createNewStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
+ StreamContext* context, const Metadata& metadata) override;
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
+
+ ndk::ScopedAStatus getHwVolume(std::vector<float>* _aidl_return) override;
+ ndk::ScopedAStatus setHwVolume(const std::vector<float>& in_channelVolumes) override;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h b/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h
new file mode 100644
index 0000000..94404a1
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/StreamRemoteSubmix.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2023 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 <mutex>
+#include <vector>
+
+#include "core-impl/Stream.h"
+#include "core-impl/StreamSwitcher.h"
+#include "r_submix/SubmixRoute.h"
+
+namespace aidl::android::hardware::audio::core {
+
+class StreamRemoteSubmix : public StreamCommonImpl {
+ public:
+ StreamRemoteSubmix(
+ StreamContext* context, const Metadata& metadata,
+ const ::aidl::android::media::audio::common::AudioDeviceAddress& deviceAddress);
+
+ ::android::status_t init() override;
+ ::android::status_t drain(StreamDescriptor::DrainMode) override;
+ ::android::status_t flush() override;
+ ::android::status_t pause() override;
+ ::android::status_t standby() override;
+ ::android::status_t start() override;
+ ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
+ int32_t* latencyMs) override;
+ ::android::status_t refinePosition(StreamDescriptor::Position* position) override;
+ void shutdown() override;
+
+ // Overridden methods of 'StreamCommonImpl', called on a Binder thread.
+ ndk::ScopedAStatus prepareToClose() override;
+
+ private:
+ size_t getPipeSizeInFrames();
+ size_t getStreamPipeSizeInFrames();
+ ::android::status_t outWrite(void* buffer, size_t frameCount, size_t* actualFrameCount);
+ ::android::status_t inRead(void* buffer, size_t frameCount, size_t* actualFrameCount);
+
+ const ::aidl::android::media::audio::common::AudioDeviceAddress mDeviceAddress;
+ const bool mIsInput;
+ r_submix::AudioConfig mStreamConfig;
+ std::shared_ptr<r_submix::SubmixRoute> mCurrentRoute = nullptr;
+
+ // Mutex lock to protect vector of submix routes, each of these submix routes have their mutex
+ // locks and none of the mutex locks should be taken together.
+ static std::mutex sSubmixRoutesLock;
+ static std::map<::aidl::android::media::audio::common::AudioDeviceAddress,
+ std::shared_ptr<r_submix::SubmixRoute>>
+ sSubmixRoutes GUARDED_BY(sSubmixRoutesLock);
+
+ // limit for number of read error log entries to avoid spamming the logs
+ static constexpr int kMaxReadErrorLogs = 5;
+ // The duration of kMaxReadFailureAttempts * READ_ATTEMPT_SLEEP_MS must be strictly inferior
+ // to the duration of a record buffer at the current record sample rate (of the device, not of
+ // the recording itself). Here we have: 3 * 5ms = 15ms < 1024 frames * 1000 / 48000 = 21.333ms
+ static constexpr int kMaxReadFailureAttempts = 3;
+ // 5ms between two read attempts when pipe is empty
+ static constexpr int kReadAttemptSleepUs = 5000;
+};
+
+class StreamInRemoteSubmix final : public StreamIn, public StreamSwitcher {
+ public:
+ friend class ndk::SharedRefBase;
+ StreamInRemoteSubmix(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones);
+
+ private:
+ DeviceSwitchBehavior switchCurrentStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices)
+ override;
+ std::unique_ptr<StreamCommonInterfaceEx> createNewStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
+ StreamContext* context, const Metadata& metadata) override;
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
+ ndk::ScopedAStatus getActiveMicrophones(
+ std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo>* _aidl_return)
+ override;
+};
+
+class StreamOutRemoteSubmix final : public StreamOut, public StreamSwitcher {
+ public:
+ friend class ndk::SharedRefBase;
+ StreamOutRemoteSubmix(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
+ const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
+ offloadInfo);
+
+ private:
+ DeviceSwitchBehavior switchCurrentStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices)
+ override;
+ std::unique_ptr<StreamCommonInterfaceEx> createNewStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
+ StreamContext* context, const Metadata& metadata) override;
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/StreamStub.h b/audio/aidl/default/include/core-impl/StreamStub.h
index df0182c..3857e0e 100644
--- a/audio/aidl/default/include/core-impl/StreamStub.h
+++ b/audio/aidl/default/include/core-impl/StreamStub.h
@@ -20,58 +20,52 @@
namespace aidl::android::hardware::audio::core {
-class DriverStub : public DriverInterface {
+class StreamStub : public StreamCommonImpl {
public:
- DriverStub(const StreamContext& context, bool isInput);
+ StreamStub(StreamContext* context, const Metadata& metadata);
+ // Methods of 'DriverInterface'.
::android::status_t init() override;
- ::android::status_t setConnectedDevices(
- const std::vector<::aidl::android::media::audio::common::AudioDevice>& connectedDevices)
- override;
::android::status_t drain(StreamDescriptor::DrainMode) override;
::android::status_t flush() override;
::android::status_t pause() override;
+ ::android::status_t standby() override;
+ ::android::status_t start() override;
::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
int32_t* latencyMs) override;
- ::android::status_t standby() override;
+ void shutdown() override;
private:
+ const size_t mBufferSizeFrames;
const size_t mFrameSizeBytes;
const int mSampleRate;
const bool mIsAsynchronous;
const bool mIsInput;
+ bool mIsInitialized = false; // Used for validating the state machine logic.
+ bool mIsStandby = true; // Used for validating the state machine logic.
};
-class StreamInStub final : public StreamIn {
+class StreamInStub final : public StreamIn, public StreamStub {
public:
- static ndk::ScopedAStatus createInstance(
- const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
- StreamContext&& context,
- const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
- std::shared_ptr<StreamIn>* result);
-
- private:
friend class ndk::SharedRefBase;
StreamInStub(
+ StreamContext&& context,
const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
- StreamContext&& context,
const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones);
-};
-
-class StreamOutStub final : public StreamOut {
- public:
- static ndk::ScopedAStatus createInstance(
- const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
- StreamContext&& context,
- const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
- offloadInfo,
- std::shared_ptr<StreamOut>* result);
private:
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
+};
+
+class StreamOutStub final : public StreamOut, public StreamStub {
+ public:
friend class ndk::SharedRefBase;
- StreamOutStub(const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
- StreamContext&& context,
+ StreamOutStub(StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
offloadInfo);
+
+ private:
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
};
} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/StreamSwitcher.h b/audio/aidl/default/include/core-impl/StreamSwitcher.h
new file mode 100644
index 0000000..5764ad6
--- /dev/null
+++ b/audio/aidl/default/include/core-impl/StreamSwitcher.h
@@ -0,0 +1,194 @@
+/*
+ * Copyright (C) 2023 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 "Stream.h"
+
+namespace aidl::android::hardware::audio::core {
+
+// 'StreamSwitcher' is an implementation of 'StreamCommonInterface' which allows
+// dynamically switching the underlying stream implementation based on currently
+// connected devices. This is achieved by replacing inheritance from
+// 'StreamCommonImpl' with owning an instance of it. StreamSwitcher must be
+// extended in order to supply the logic for choosing the stream
+// implementation. When there are no connected devices, for instance, upon the
+// creation, the StreamSwitcher engages an instance of a stub stream in order to
+// keep serving requests coming via 'StreamDescriptor'.
+//
+// StreamSwitcher implements the 'IStreamCommon' interface directly, with
+// necessary delegation to the current stream implementation. While the stub
+// stream is engaged, any requests made via 'IStreamCommon' (parameters, effects
+// setting, etc) are postponed and only delivered on device connection change
+// to the "real" stream implementation provided by the extending class. This is why
+// the behavior of StreamSwitcher in the "stub" state is not identical to behavior
+// of 'StreamStub'. It can become a full substitute for 'StreamStub' once
+// device connection change event occurs and the extending class returns
+// 'LEAVE_CURRENT_STREAM' from 'switchCurrentStream' method.
+//
+// There is a natural limitation that the current stream implementation may only
+// be switched when the stream is in the 'STANDBY' state. Thus, when the event
+// to switch the stream occurs, the current stream is stopped and joined, and
+// its last state is validated. Since the change of the set of connected devices
+// normally occurs on patch updates, if the stream was not in standby, this is
+// reported to the caller of 'IModule.setAudioPatch' as the 'EX_ILLEGAL_STATE'
+// error.
+//
+// The simplest use case, when the implementor just needs to emulate the legacy HAL API
+// behavior of receiving the connected devices upon stream creation, the implementation
+// of the extending class can look as follows. We assume that 'StreamLegacy' implementation
+// is the one requiring to know connected devices on creation:
+//
+// class StreamLegacy : public StreamCommonImpl {
+// public:
+// StreamLegacy(StreamContext* context, const Metadata& metadata,
+// const std::vector<AudioDevice>& devices);
+// };
+//
+// class StreamOutLegacy final : public StreamOut, public StreamSwitcher {
+// public:
+// StreamOutLegacy(StreamContext&& context, metatadata etc.)
+// private:
+// DeviceSwitchBehavior switchCurrentStream(const std::vector<AudioDevice>&) override {
+// // This implementation effectively postpones stream creation until
+// // receiving the first call to 'setConnectedDevices' with a non-empty list.
+// return isStubStream() ? DeviceSwitchBehavior::CREATE_NEW_STREAM :
+// DeviceSwitchBehavior::USE_CURRENT_STREAM;
+// }
+// std::unique_ptr<StreamCommonInterfaceEx> createNewStream(
+// const std::vector<AudioDevice>& devices,
+// StreamContext* context, const Metadata& metadata) override {
+// return std::unique_ptr<StreamCommonInterfaceEx>(new InnerStreamWrapper<StreamLegacy>(
+// context, metadata, devices));
+// }
+// void onClose(StreamDescriptor::State) override { defaultOnClose(); }
+// }
+//
+
+class StreamCommonInterfaceEx : virtual public StreamCommonInterface {
+ public:
+ virtual StreamDescriptor::State getStatePriorToClosing() const = 0;
+};
+
+template <typename T>
+class InnerStreamWrapper : public T, public StreamCommonInterfaceEx {
+ public:
+ template <typename... Args>
+ InnerStreamWrapper(Args&&... args) : T(std::forward<Args>(args)...) {}
+ StreamDescriptor::State getStatePriorToClosing() const override { return mStatePriorToClosing; }
+
+ private:
+ // Do not need to do anything on close notification from the inner stream
+ // because StreamSwitcher handles IStreamCommon::close by itself.
+ void onClose(StreamDescriptor::State statePriorToClosing) override {
+ mStatePriorToClosing = statePriorToClosing;
+ }
+
+ StreamDescriptor::State mStatePriorToClosing = StreamDescriptor::State::STANDBY;
+};
+
+class StreamSwitcher : virtual public StreamCommonInterface {
+ public:
+ StreamSwitcher(StreamContext* context, const Metadata& metadata);
+
+ ndk::ScopedAStatus close() override;
+ ndk::ScopedAStatus prepareToClose() override;
+ ndk::ScopedAStatus updateHwAvSyncId(int32_t in_hwAvSyncId) override;
+ ndk::ScopedAStatus getVendorParameters(const std::vector<std::string>& in_ids,
+ std::vector<VendorParameter>* _aidl_return) override;
+ ndk::ScopedAStatus setVendorParameters(const std::vector<VendorParameter>& in_parameters,
+ bool in_async) override;
+ ndk::ScopedAStatus addEffect(
+ const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect)
+ override;
+ ndk::ScopedAStatus removeEffect(
+ const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect)
+ override;
+
+ ndk::ScopedAStatus getStreamCommonCommon(std::shared_ptr<IStreamCommon>* _aidl_return) override;
+ ndk::ScopedAStatus updateMetadataCommon(const Metadata& metadata) override;
+
+ ndk::ScopedAStatus initInstance(
+ const std::shared_ptr<StreamCommonInterface>& delegate) override;
+ const StreamContext& getContext() const override;
+ bool isClosed() const override;
+ const ConnectedDevices& getConnectedDevices() const override;
+ ndk::ScopedAStatus setConnectedDevices(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices)
+ override;
+ ndk::ScopedAStatus bluetoothParametersUpdated() override;
+
+ protected:
+ // Since switching a stream requires closing down the current stream, StreamSwitcher
+ // asks the extending class its intent on the connected devices change.
+ enum DeviceSwitchBehavior {
+ // Continue using the current stream implementation. If it's the stub implementation,
+ // StreamSwitcher starts treating the stub stream as a "real" implementation,
+ // without effectively closing it and starting again.
+ USE_CURRENT_STREAM,
+ // This is the normal case when the extending class provides a "real" implementation
+ // which is not a stub implementation.
+ CREATE_NEW_STREAM,
+ // This is the case when the extending class wants to revert back to the initial
+ // condition of using a stub stream provided by the StreamSwitcher. This behavior
+ // is only allowed when the list of connected devices is empty.
+ SWITCH_TO_STUB_STREAM,
+ // Use when the set of devices is not supported by the extending class. This returns
+ // 'EX_UNSUPPORTED_OPERATION' from 'setConnectedDevices'.
+ UNSUPPORTED_DEVICES,
+ };
+ // StreamSwitcher will call these methods from 'setConnectedDevices'. If the switch behavior
+ // is 'CREATE_NEW_STREAM', the 'createwNewStream' function will be called (with the same
+ // device vector) for obtaining a new stream implementation, assuming that closing
+ // the current stream was a success.
+ virtual DeviceSwitchBehavior switchCurrentStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) = 0;
+ virtual std::unique_ptr<StreamCommonInterfaceEx> createNewStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
+ StreamContext* context, const Metadata& metadata) = 0;
+ virtual void onClose(StreamDescriptor::State streamPriorToClosing) = 0;
+
+ bool isStubStream() const { return mIsStubStream; }
+ StreamCommonInterfaceEx* getCurrentStream() const { return mStream.get(); }
+
+ private:
+ using VndParam = std::pair<std::vector<VendorParameter>, bool /*isAsync*/>;
+
+ static constexpr bool isValidClosingStreamState(StreamDescriptor::State state) {
+ return state == StreamDescriptor::State::STANDBY || state == StreamDescriptor::State::ERROR;
+ }
+
+ ndk::ScopedAStatus closeCurrentStream(bool validateStreamState);
+
+ // StreamSwitcher does not own the context.
+ StreamContext* mContext;
+ Metadata mMetadata;
+ ChildInterface<StreamCommonDelegator> mCommon;
+ // The current stream.
+ std::unique_ptr<StreamCommonInterfaceEx> mStream;
+ // Indicates whether 'mCurrentStream' is a stub stream implementation
+ // maintained by StreamSwitcher until the extending class provides a "real"
+ // implementation. The invariant of this state is that there are no connected
+ // devices.
+ bool mIsStubStream = true;
+ // Storage for the data from commands received via 'IStreamCommon'.
+ std::optional<int32_t> mHwAvSyncId;
+ std::vector<VndParam> mMissedParameters;
+ std::vector<std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>> mEffects;
+ bool mBluetoothParametersUpdated = false;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/StreamUsb.h b/audio/aidl/default/include/core-impl/StreamUsb.h
index 36e64cb..608f27d 100644
--- a/audio/aidl/default/include/core-impl/StreamUsb.h
+++ b/audio/aidl/default/include/core-impl/StreamUsb.h
@@ -16,90 +16,61 @@
#pragma once
+#include <atomic>
#include <mutex>
#include <vector>
#include <aidl/android/media/audio/common/AudioChannelLayout.h>
-#include "core-impl/Stream.h"
-
-extern "C" {
-#include <tinyalsa/pcm.h>
-#include "alsa_device_proxy.h"
-}
+#include "StreamAlsa.h"
namespace aidl::android::hardware::audio::core {
-class DriverUsb : public DriverInterface {
+class StreamUsb : public StreamAlsa {
public:
- DriverUsb(const StreamContext& context, bool isInput);
- ::android::status_t init() override;
- ::android::status_t setConnectedDevices(
- const std::vector<::aidl::android::media::audio::common::AudioDevice>& connectedDevices)
- override;
- ::android::status_t drain(StreamDescriptor::DrainMode) override;
- ::android::status_t flush() override;
- ::android::status_t pause() override;
+ StreamUsb(StreamContext* context, const Metadata& metadata);
+ // Methods of 'DriverInterface'.
::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
int32_t* latencyMs) override;
- ::android::status_t standby() override;
- private:
- ::android::status_t exitStandby();
+ // Overridden methods of 'StreamCommonImpl', called on a Binder thread.
+ ndk::ScopedAStatus setConnectedDevices(const ConnectedDevices& devices) override;
- std::mutex mLock;
+ protected:
+ std::vector<alsa::DeviceProfile> getDeviceProfiles() override;
- const size_t mFrameSizeBytes;
- std::optional<struct pcm_config> mConfig;
- const bool mIsInput;
- // Cached device addresses for connected devices.
- std::vector<::aidl::android::media::audio::common::AudioDeviceAddress> mConnectedDevices
- GUARDED_BY(mLock);
- std::vector<std::shared_ptr<alsa_device_proxy>> mAlsaDeviceProxies GUARDED_BY(mLock);
- bool mIsStandby = true;
+ mutable std::mutex mLock;
+ std::vector<alsa::DeviceProfile> mConnectedDeviceProfiles GUARDED_BY(mLock);
+ std::atomic<bool> mConnectedDevicesUpdated = false;
};
-class StreamInUsb final : public StreamIn {
+class StreamInUsb final : public StreamIn, public StreamUsb {
+ public:
+ friend class ndk::SharedRefBase;
+ StreamInUsb(
+ StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
+ const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones);
+
+ private:
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
ndk::ScopedAStatus getActiveMicrophones(
std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo>* _aidl_return)
override;
-
- public:
- static ndk::ScopedAStatus createInstance(
- const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
- StreamContext&& context,
- const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones,
- std::shared_ptr<StreamIn>* result);
-
- private:
- friend class ndk::SharedRefBase;
- StreamInUsb(
- const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata,
- StreamContext&& context,
- const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones);
};
-class StreamOutUsb final : public StreamOut {
+class StreamOutUsb final : public StreamOut, public StreamUsb, public StreamOutHwVolumeHelper {
public:
- static ndk::ScopedAStatus createInstance(
- const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
- StreamContext&& context,
- const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
- offloadInfo,
- std::shared_ptr<StreamOut>* result);
-
- private:
friend class ndk::SharedRefBase;
- StreamOutUsb(const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
- StreamContext&& context,
+ StreamOutUsb(StreamContext&& context,
+ const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata,
const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>&
offloadInfo);
+ private:
+ void onClose(StreamDescriptor::State) override { defaultOnClose(); }
ndk::ScopedAStatus getHwVolume(std::vector<float>* _aidl_return) override;
ndk::ScopedAStatus setHwVolume(const std::vector<float>& in_channelVolumes) override;
-
- int mChannelCount;
- std::vector<float> mHwVolumes;
};
} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/include/core-impl/XmlConverter.h b/audio/aidl/default/include/core-impl/XmlConverter.h
index ec23edb..383ea24 100644
--- a/audio/aidl/default/include/core-impl/XmlConverter.h
+++ b/audio/aidl/default/include/core-impl/XmlConverter.h
@@ -20,6 +20,7 @@
#include <string>
#include <unordered_map>
+#include <media/AidlConversionUtil.h>
#include <system/audio_config.h>
#include <utils/Errors.h>
@@ -52,10 +53,16 @@
const ::android::status_t& status) {
std::string errorMessage;
if (status != ::android::OK) {
- if (!isReadableConfigFile) {
- errorMessage = "Could not read requested config file:" + configFilePath;
+ if (configFilePath.empty()) {
+ errorMessage = "No audio configuration files found";
+ } else if (!isReadableConfigFile) {
+ errorMessage = std::string("Could not read requested XML config file: \"")
+ .append(configFilePath)
+ .append("\"");
} else {
- errorMessage = "Invalid config file: " + configFilePath;
+ errorMessage = std::string("Invalid XML config file: \"")
+ .append(configFilePath)
+ .append("\"");
}
}
return errorMessage;
@@ -78,7 +85,7 @@
* </Modules>
*/
template <typename W, typename X, typename A>
-static std::vector<A> convertWrappedCollectionToAidl(
+std::vector<A> convertWrappedCollectionToAidlUnchecked(
const std::vector<W>& xsdcWrapperTypeVec,
std::function<const std::vector<X>&(const W&)> getInnerTypeVec,
std::function<A(const X&)> convertToAidl) {
@@ -100,12 +107,12 @@
}
template <typename X, typename A>
-static std::vector<A> convertCollectionToAidl(const std::vector<X>& xsdcTypeVec,
- std::function<A(const X&)> convertToAidl) {
+std::vector<A> convertCollectionToAidlUnchecked(const std::vector<X>& xsdcTypeVec,
+ std::function<A(const X&)> itemConversion) {
std::vector<A> resultAidlTypeVec;
resultAidlTypeVec.reserve(xsdcTypeVec.size());
std::transform(xsdcTypeVec.begin(), xsdcTypeVec.end(), std::back_inserter(resultAidlTypeVec),
- convertToAidl);
+ itemConversion);
return resultAidlTypeVec;
}
@@ -121,8 +128,7 @@
* </Wrapper>
*/
template <typename W, typename R>
-static std::unordered_map<std::string, R> generateReferenceMap(
- const std::vector<W>& xsdcWrapperTypeVec) {
+std::unordered_map<std::string, R> generateReferenceMap(const std::vector<W>& xsdcWrapperTypeVec) {
std::unordered_map<std::string, R> resultMap;
if (!xsdcWrapperTypeVec.empty()) {
/*
diff --git a/audio/aidl/default/include/effect-impl/EffectContext.h b/audio/aidl/default/include/effect-impl/EffectContext.h
index 22cdb6b..698e7a5 100644
--- a/audio/aidl/default/include/effect-impl/EffectContext.h
+++ b/audio/aidl/default/include/effect-impl/EffectContext.h
@@ -124,11 +124,11 @@
virtual RetCode setCommon(const Parameter::Common& common) {
mCommon = common;
- LOG(INFO) << __func__ << mCommon.toString();
+ LOG(VERBOSE) << __func__ << mCommon.toString();
return RetCode::SUCCESS;
}
virtual Parameter::Common getCommon() {
- LOG(DEBUG) << __func__ << mCommon.toString();
+ LOG(VERBOSE) << __func__ << mCommon.toString();
return mCommon;
}
diff --git a/audio/aidl/default/include/effect-impl/EffectWorker.h b/audio/aidl/default/include/effect-impl/EffectWorker.h
deleted file mode 100644
index b456817..0000000
--- a/audio/aidl/default/include/effect-impl/EffectWorker.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2022 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 <algorithm>
-#include <memory>
-#include <mutex>
-#include <string>
-
-#include "EffectContext.h"
-#include "EffectThread.h"
-
-namespace aidl::android::hardware::audio::effect {
-
-std::string toString(RetCode& code);
-
-class EffectWorker : public EffectThread {
- public:
- // set effect context for worker, suppose to only happen once here
- void setContext(std::shared_ptr<EffectContext> context) {
- std::call_once(mOnceFlag, [&]() { mContext = context; });
- };
-
- // handle FMQ and call effect implemented virtual function
- void process() override {
- RETURN_VALUE_IF(!mContext, void(), "nullContext");
- std::shared_ptr<EffectContext::StatusMQ> statusMQ = mContext->getStatusFmq();
- std::shared_ptr<EffectContext::DataMQ> inputMQ = mContext->getInputDataFmq();
- std::shared_ptr<EffectContext::DataMQ> outputMQ = mContext->getOutputDataFmq();
-
- // Only this worker will read from input data MQ and write to output data MQ.
- auto readSamples = inputMQ->availableToRead(), writeSamples = outputMQ->availableToWrite();
- if (readSamples && writeSamples) {
- auto processSamples = std::min(readSamples, writeSamples);
- LOG(DEBUG) << __func__ << " available to read " << readSamples << " available to write "
- << writeSamples << " process " << processSamples;
-
- auto buffer = mContext->getWorkBuffer();
- inputMQ->read(buffer, processSamples);
-
- IEffect::Status status = effectProcessImpl(buffer, buffer, processSamples);
- outputMQ->write(buffer, status.fmqProduced);
- statusMQ->writeBlocking(&status, 1);
- LOG(DEBUG) << __func__ << " done processing, effect consumed " << status.fmqConsumed
- << " produced " << status.fmqProduced;
- } else {
- // TODO: maybe add some sleep here to avoid busy waiting
- }
- }
-
- // must implement by each effect implementation
- // TODO: consider if this interface need adjustment to handle in-place processing
- virtual IEffect::Status effectProcessImpl(float* in, float* out, int samples) = 0;
-
- private:
- // make sure the context only set once.
- std::once_flag mOnceFlag;
- std::shared_ptr<EffectContext> mContext;
-};
-
-} // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/include/effectFactory-impl/EffectConfig.h b/audio/aidl/default/include/effectFactory-impl/EffectConfig.h
index f8a86e1..344846a 100644
--- a/audio/aidl/default/include/effectFactory-impl/EffectConfig.h
+++ b/audio/aidl/default/include/effectFactory-impl/EffectConfig.h
@@ -40,14 +40,15 @@
public:
explicit EffectConfig(const std::string& file);
- struct LibraryUuid {
+ struct Library {
std::string name; // library name
- ::aidl::android::media::audio::common::AudioUuid uuid;
+ ::aidl::android::media::audio::common::AudioUuid uuid; // implementation UUID
+ std::optional<::aidl::android::media::audio::common::AudioUuid> type; // optional type UUID
};
// <effects>
struct EffectLibraries {
- std::optional<struct LibraryUuid> proxyLibrary;
- std::vector<struct LibraryUuid> libraries;
+ std::optional<struct Library> proxyLibrary;
+ std::vector<struct Library> libraries;
};
int getSkippedElements() const { return mSkippedElements; }
@@ -56,7 +57,7 @@
return mEffectsMap;
}
- static bool findUuid(const std::string& xmlEffectName,
+ static bool findUuid(const std::pair<std::string, struct EffectLibraries>& effectElem,
::aidl::android::media::audio::common::AudioUuid* uuid);
using ProcessingLibrariesMap = std::map<Processing::Type, std::vector<struct EffectLibraries>>;
@@ -96,8 +97,8 @@
bool parseProcessing(Processing::Type::Tag typeTag, const tinyxml2::XMLElement& xml);
// Function to parse effect.library name and effect.uuid from xml
- bool parseLibraryUuid(const tinyxml2::XMLElement& xml, struct LibraryUuid& libraryUuid,
- bool isProxy = false);
+ bool parseLibrary(const tinyxml2::XMLElement& xml, struct Library& library,
+ bool isProxy = false);
const char* dump(const tinyxml2::XMLElement& element,
tinyxml2::XMLPrinter&& printer = {}) const;
diff --git a/audio/aidl/default/include/effectFactory-impl/EffectFactory.h b/audio/aidl/default/include/effectFactory-impl/EffectFactory.h
index ad59ca7..d0b8204 100644
--- a/audio/aidl/default/include/effectFactory-impl/EffectFactory.h
+++ b/audio/aidl/default/include/effectFactory-impl/EffectFactory.h
@@ -24,6 +24,7 @@
#include <vector>
#include <aidl/android/hardware/audio/effect/BnFactory.h>
+#include <android-base/thread_annotations.h>
#include "EffectConfig.h"
namespace aidl::android::hardware::audio::effect {
@@ -82,9 +83,11 @@
private:
const EffectConfig mConfig;
~Factory();
+
+ std::mutex mMutex;
// Set of effect descriptors supported by the devices.
- std::set<Descriptor> mDescSet;
- std::set<Descriptor::Identity> mIdentitySet;
+ std::set<Descriptor> mDescSet GUARDED_BY(mMutex);
+ std::set<Descriptor::Identity> mIdentitySet GUARDED_BY(mMutex);
static constexpr int kMapEntryHandleIndex = 0;
static constexpr int kMapEntryInterfaceIndex = 1;
@@ -94,26 +97,29 @@
std::string /* library name */>
DlEntry;
- std::map<aidl::android::media::audio::common::AudioUuid /* implUUID */, DlEntry> mEffectLibMap;
+ std::map<aidl::android::media::audio::common::AudioUuid /* implUUID */, DlEntry> mEffectLibMap
+ GUARDED_BY(mMutex);
typedef std::pair<aidl::android::media::audio::common::AudioUuid, ndk::SpAIBinder> EffectEntry;
- std::map<std::weak_ptr<IEffect>, EffectEntry, std::owner_less<>> mEffectMap;
+ std::map<std::weak_ptr<IEffect>, EffectEntry, std::owner_less<>> mEffectMap GUARDED_BY(mMutex);
- ndk::ScopedAStatus destroyEffectImpl(const std::shared_ptr<IEffect>& in_handle);
- void cleanupEffectMap();
+ ndk::ScopedAStatus destroyEffectImpl_l(const std::shared_ptr<IEffect>& in_handle)
+ REQUIRES(mMutex);
+ void cleanupEffectMap_l() REQUIRES(mMutex);
bool openEffectLibrary(const ::aidl::android::media::audio::common::AudioUuid& impl,
const std::string& path);
void createIdentityWithConfig(
- const EffectConfig::LibraryUuid& configLib,
+ const EffectConfig::Library& configLib,
const ::aidl::android::media::audio::common::AudioUuid& typeUuidStr,
const std::optional<::aidl::android::media::audio::common::AudioUuid> proxyUuid);
- ndk::ScopedAStatus getDescriptorWithUuid(
- const aidl::android::media::audio::common::AudioUuid& uuid, Descriptor* desc);
+ ndk::ScopedAStatus getDescriptorWithUuid_l(
+ const aidl::android::media::audio::common::AudioUuid& uuid, Descriptor* desc)
+ REQUIRES(mMutex);
void loadEffectLibs();
/* Get effect_dl_interface_s from library handle */
- void getDlSyms(DlEntry& entry);
+ void getDlSyms_l(DlEntry& entry) REQUIRES(mMutex);
};
} // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/main.cpp b/audio/aidl/default/main.cpp
index af71aa8..a0c0fab 100644
--- a/audio/aidl/default/main.cpp
+++ b/audio/aidl/default/main.cpp
@@ -16,20 +16,21 @@
#include <cstdlib>
#include <ctime>
+#include <sstream>
#include <utility>
+#include <vector>
#include <android-base/logging.h>
+#include <android-base/properties.h>
#include <android/binder_ibinder_platform.h>
#include <android/binder_manager.h>
#include <android/binder_process.h>
#include "core-impl/Config.h"
#include "core-impl/Module.h"
-#include "core-impl/ModuleUsb.h"
using aidl::android::hardware::audio::core::Config;
using aidl::android::hardware::audio::core::Module;
-using aidl::android::hardware::audio::core::ModuleUsb;
int main() {
// Random values are used in the implementation.
@@ -52,18 +53,21 @@
CHECK_EQ(STATUS_OK, status);
// Make modules
- auto createModule = [](Module::Type type, const std::string& instance) {
+ auto createModule = [](Module::Type type) {
auto module = Module::createInstance(type);
ndk::SpAIBinder moduleBinder = module->asBinder();
- const std::string moduleName = std::string(Module::descriptor).append("/").append(instance);
+ std::stringstream moduleName;
+ moduleName << Module::descriptor << "/" << type;
AIBinder_setMinSchedulerPolicy(moduleBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
- binder_status_t status = AServiceManager_addService(moduleBinder.get(), moduleName.c_str());
+ binder_status_t status =
+ AServiceManager_addService(moduleBinder.get(), moduleName.str().c_str());
CHECK_EQ(STATUS_OK, status);
return std::make_pair(module, moduleBinder);
};
- auto modules = {createModule(Module::Type::DEFAULT, "default"),
- createModule(Module::Type::R_SUBMIX, "r_submix"),
- createModule(Module::Type::USB, "usb")};
+ auto modules = {createModule(Module::Type::DEFAULT), createModule(Module::Type::R_SUBMIX),
+ createModule(Module::Type::USB), createModule(Module::Type::STUB),
+ createModule(Module::Type::BLUETOOTH)};
+ (void)modules;
ABinderProcess_joinThreadPool();
return EXIT_FAILURE; // should not reach
diff --git a/audio/aidl/default/primary/PrimaryMixer.cpp b/audio/aidl/default/primary/PrimaryMixer.cpp
new file mode 100644
index 0000000..577d010
--- /dev/null
+++ b/audio/aidl/default/primary/PrimaryMixer.cpp
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2023 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 "AHAL_PrimaryMixer"
+
+#include "PrimaryMixer.h"
+
+namespace aidl::android::hardware::audio::core::primary {
+
+// static
+PrimaryMixer& PrimaryMixer::getInstance() {
+ static PrimaryMixer gInstance;
+ return gInstance;
+}
+
+} // namespace aidl::android::hardware::audio::core::primary
diff --git a/audio/aidl/default/primary/PrimaryMixer.h b/audio/aidl/default/primary/PrimaryMixer.h
new file mode 100644
index 0000000..3806428
--- /dev/null
+++ b/audio/aidl/default/primary/PrimaryMixer.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 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 <map>
+#include <memory>
+#include <mutex>
+#include <vector>
+
+#include <android-base/thread_annotations.h>
+#include <android/binder_auto_utils.h>
+
+#include "alsa/Mixer.h"
+
+namespace aidl::android::hardware::audio::core::primary {
+
+class PrimaryMixer : public alsa::Mixer {
+ public:
+ static constexpr int kAlsaCard = 0;
+ static constexpr int kAlsaDevice = 0;
+
+ static PrimaryMixer& getInstance();
+
+ private:
+ PrimaryMixer() : alsa::Mixer(kAlsaCard) {}
+};
+
+} // namespace aidl::android::hardware::audio::core::primary
diff --git a/audio/aidl/default/primary/StreamPrimary.cpp b/audio/aidl/default/primary/StreamPrimary.cpp
new file mode 100644
index 0000000..e01be8a
--- /dev/null
+++ b/audio/aidl/default/primary/StreamPrimary.cpp
@@ -0,0 +1,186 @@
+/*
+ * Copyright (C) 2023 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 <limits>
+
+#define LOG_TAG "AHAL_StreamPrimary"
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <error/expected_utils.h>
+
+#include "PrimaryMixer.h"
+#include "core-impl/StreamPrimary.h"
+#include "core-impl/StreamStub.h"
+
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
+using aidl::android::media::audio::common::AudioDevice;
+using aidl::android::media::audio::common::AudioDeviceDescription;
+using aidl::android::media::audio::common::AudioDeviceType;
+using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::MicrophoneInfo;
+using android::base::GetBoolProperty;
+
+namespace aidl::android::hardware::audio::core {
+
+StreamPrimary::StreamPrimary(StreamContext* context, const Metadata& metadata)
+ : StreamAlsa(context, metadata, 3 /*readWriteRetries*/), mIsInput(isInput(metadata)) {}
+
+std::vector<alsa::DeviceProfile> StreamPrimary::getDeviceProfiles() {
+ static const std::vector<alsa::DeviceProfile> kBuiltInSource{
+ alsa::DeviceProfile{.card = primary::PrimaryMixer::kAlsaCard,
+ .device = primary::PrimaryMixer::kAlsaDevice,
+ .direction = PCM_IN,
+ .isExternal = false}};
+ static const std::vector<alsa::DeviceProfile> kBuiltInSink{
+ alsa::DeviceProfile{.card = primary::PrimaryMixer::kAlsaCard,
+ .device = primary::PrimaryMixer::kAlsaDevice,
+ .direction = PCM_OUT,
+ .isExternal = false}};
+ return mIsInput ? kBuiltInSource : kBuiltInSink;
+}
+
+StreamInPrimary::StreamInPrimary(StreamContext&& context, const SinkMetadata& sinkMetadata,
+ const std::vector<MicrophoneInfo>& microphones)
+ : StreamIn(std::move(context), microphones),
+ StreamSwitcher(&mContextInstance, sinkMetadata),
+ StreamInHwGainHelper(&mContextInstance) {}
+
+bool StreamInPrimary::useStubStream(const AudioDevice& device) {
+ static const bool kSimulateInput =
+ GetBoolProperty("ro.boot.audio.tinyalsa.simulate_input", false);
+ return kSimulateInput || device.type.type == AudioDeviceType::IN_TELEPHONY_RX ||
+ device.type.type == AudioDeviceType::IN_FM_TUNER ||
+ device.type.connection == AudioDeviceDescription::CONNECTION_BUS;
+}
+
+StreamSwitcher::DeviceSwitchBehavior StreamInPrimary::switchCurrentStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
+ LOG(DEBUG) << __func__;
+ if (devices.size() > 1) {
+ LOG(ERROR) << __func__ << ": primary stream can only be connected to one device, got: "
+ << devices.size();
+ return DeviceSwitchBehavior::UNSUPPORTED_DEVICES;
+ }
+ if (devices.empty() || useStubStream(devices[0]) == isStubStream()) {
+ return DeviceSwitchBehavior::USE_CURRENT_STREAM;
+ }
+ return DeviceSwitchBehavior::CREATE_NEW_STREAM;
+}
+
+std::unique_ptr<StreamCommonInterfaceEx> StreamInPrimary::createNewStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
+ StreamContext* context, const Metadata& metadata) {
+ if (devices.empty()) {
+ LOG(FATAL) << __func__ << ": called with empty devices"; // see 'switchCurrentStream'
+ }
+ if (useStubStream(devices[0])) {
+ return std::unique_ptr<StreamCommonInterfaceEx>(
+ new InnerStreamWrapper<StreamStub>(context, metadata));
+ }
+ return std::unique_ptr<StreamCommonInterfaceEx>(
+ new InnerStreamWrapper<StreamPrimary>(context, metadata));
+}
+
+ndk::ScopedAStatus StreamInPrimary::getHwGain(std::vector<float>* _aidl_return) {
+ if (isStubStream()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ return getHwGainImpl(_aidl_return);
+}
+
+ndk::ScopedAStatus StreamInPrimary::setHwGain(const std::vector<float>& in_channelGains) {
+ if (isStubStream()) {
+ LOG(DEBUG) << __func__ << ": gains " << ::android::internal::ToString(in_channelGains);
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ auto currentGains = mHwGains;
+ RETURN_STATUS_IF_ERROR(setHwGainImpl(in_channelGains));
+ if (in_channelGains.size() < 1) {
+ LOG(FATAL) << __func__ << ": unexpected gain vector size: " << in_channelGains.size();
+ }
+ if (auto status = primary::PrimaryMixer::getInstance().setMicGain(in_channelGains[0]);
+ !status.isOk()) {
+ mHwGains = currentGains;
+ return status;
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+StreamOutPrimary::StreamOutPrimary(StreamContext&& context, const SourceMetadata& sourceMetadata,
+ const std::optional<AudioOffloadInfo>& offloadInfo)
+ : StreamOut(std::move(context), offloadInfo),
+ StreamSwitcher(&mContextInstance, sourceMetadata),
+ StreamOutHwVolumeHelper(&mContextInstance) {}
+
+bool StreamOutPrimary::useStubStream(const AudioDevice& device) {
+ static const bool kSimulateOutput =
+ GetBoolProperty("ro.boot.audio.tinyalsa.ignore_output", false);
+ return kSimulateOutput || device.type.type == AudioDeviceType::OUT_TELEPHONY_TX ||
+ device.type.connection == AudioDeviceDescription::CONNECTION_BUS;
+}
+
+StreamSwitcher::DeviceSwitchBehavior StreamOutPrimary::switchCurrentStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
+ LOG(DEBUG) << __func__;
+ if (devices.size() > 1) {
+ LOG(ERROR) << __func__ << ": primary stream can only be connected to one device, got: "
+ << devices.size();
+ return DeviceSwitchBehavior::UNSUPPORTED_DEVICES;
+ }
+ if (devices.empty() || useStubStream(devices[0]) == isStubStream()) {
+ return DeviceSwitchBehavior::USE_CURRENT_STREAM;
+ }
+ return DeviceSwitchBehavior::CREATE_NEW_STREAM;
+}
+
+std::unique_ptr<StreamCommonInterfaceEx> StreamOutPrimary::createNewStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
+ StreamContext* context, const Metadata& metadata) {
+ if (devices.empty()) {
+ LOG(FATAL) << __func__ << ": called with empty devices"; // see 'switchCurrentStream'
+ }
+ if (useStubStream(devices[0])) {
+ return std::unique_ptr<StreamCommonInterfaceEx>(
+ new InnerStreamWrapper<StreamStub>(context, metadata));
+ }
+ return std::unique_ptr<StreamCommonInterfaceEx>(
+ new InnerStreamWrapper<StreamPrimary>(context, metadata));
+}
+
+ndk::ScopedAStatus StreamOutPrimary::getHwVolume(std::vector<float>* _aidl_return) {
+ if (isStubStream()) {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ return getHwVolumeImpl(_aidl_return);
+}
+
+ndk::ScopedAStatus StreamOutPrimary::setHwVolume(const std::vector<float>& in_channelVolumes) {
+ if (isStubStream()) {
+ LOG(DEBUG) << __func__ << ": volumes " << ::android::internal::ToString(in_channelVolumes);
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ auto currentVolumes = mHwVolumes;
+ RETURN_STATUS_IF_ERROR(setHwVolumeImpl(in_channelVolumes));
+ if (auto status = primary::PrimaryMixer::getInstance().setVolumes(in_channelVolumes);
+ !status.isOk()) {
+ mHwVolumes = currentVolumes;
+ return status;
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp b/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
new file mode 100644
index 0000000..adea877
--- /dev/null
+++ b/audio/aidl/default/r_submix/ModuleRemoteSubmix.cpp
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2023 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 "AHAL_ModuleRemoteSubmix"
+
+#include <vector>
+
+#include <android-base/logging.h>
+#include <error/expected_utils.h>
+
+#include "core-impl/ModuleRemoteSubmix.h"
+#include "core-impl/StreamRemoteSubmix.h"
+
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
+using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::AudioPort;
+using aidl::android::media::audio::common::AudioPortConfig;
+using aidl::android::media::audio::common::MicrophoneInfo;
+
+namespace aidl::android::hardware::audio::core {
+
+ndk::ScopedAStatus ModuleRemoteSubmix::getMicMute(bool* _aidl_return __unused) {
+ LOG(DEBUG) << __func__ << ": is not supported";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::setMicMute(bool in_mute __unused) {
+ LOG(DEBUG) << __func__ << ": is not supported";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::createInputStream(
+ StreamContext&& context, const SinkMetadata& sinkMetadata,
+ const std::vector<MicrophoneInfo>& microphones, std::shared_ptr<StreamIn>* result) {
+ return createStreamInstance<StreamInRemoteSubmix>(result, std::move(context), sinkMetadata,
+ microphones);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::createOutputStream(
+ StreamContext&& context, const SourceMetadata& sourceMetadata,
+ const std::optional<AudioOffloadInfo>& offloadInfo, std::shared_ptr<StreamOut>* result) {
+ return createStreamInstance<StreamOutRemoteSubmix>(result, std::move(context), sourceMetadata,
+ offloadInfo);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::populateConnectedDevicePort(AudioPort* audioPort) {
+ // Find the corresponding mix port and copy its profiles.
+ std::vector<AudioRoute> routes;
+ // At this moment, the port has the same ID as the template port, see connectExternalDevice.
+ RETURN_STATUS_IF_ERROR(getAudioRoutesForAudioPort(audioPort->id, &routes));
+ if (routes.empty()) {
+ LOG(ERROR) << __func__ << ": no routes found for the port " << audioPort->toString();
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ const auto& route = *routes.begin();
+ AudioPort mixPort;
+ if (route.sinkPortId == audioPort->id) {
+ if (route.sourcePortIds.empty()) {
+ LOG(ERROR) << __func__ << ": invalid route " << route.toString();
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
+ }
+ RETURN_STATUS_IF_ERROR(getAudioPort(*route.sourcePortIds.begin(), &mixPort));
+ } else {
+ RETURN_STATUS_IF_ERROR(getAudioPort(route.sinkPortId, &mixPort));
+ }
+ audioPort->profiles = mixPort.profiles;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::checkAudioPatchEndpointsMatch(
+ const std::vector<AudioPortConfig*>& sources, const std::vector<AudioPortConfig*>& sinks) {
+ for (const auto& source : sources) {
+ for (const auto& sink : sinks) {
+ if (source->sampleRate != sink->sampleRate ||
+ source->channelMask != sink->channelMask || source->format != sink->format) {
+ LOG(ERROR) << __func__
+ << ": mismatch port configuration, source=" << source->toString()
+ << ", sink=" << sink->toString();
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ }
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::onMasterMuteChanged(bool __unused) {
+ LOG(DEBUG) << __func__ << ": is not supported";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+ndk::ScopedAStatus ModuleRemoteSubmix::onMasterVolumeChanged(float __unused) {
+ LOG(DEBUG) << __func__ << ": is not supported";
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp b/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
new file mode 100644
index 0000000..9c9c08b
--- /dev/null
+++ b/audio/aidl/default/r_submix/StreamRemoteSubmix.cpp
@@ -0,0 +1,432 @@
+/*
+ * Copyright (C) 2023 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 "AHAL_StreamRemoteSubmix"
+#include <android-base/logging.h>
+
+#include <cmath>
+
+#include "core-impl/StreamRemoteSubmix.h"
+
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
+using aidl::android::hardware::audio::core::r_submix::SubmixRoute;
+using aidl::android::media::audio::common::AudioDeviceAddress;
+using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::MicrophoneDynamicInfo;
+using aidl::android::media::audio::common::MicrophoneInfo;
+
+namespace aidl::android::hardware::audio::core {
+
+StreamRemoteSubmix::StreamRemoteSubmix(StreamContext* context, const Metadata& metadata,
+ const AudioDeviceAddress& deviceAddress)
+ : StreamCommonImpl(context, metadata),
+ mDeviceAddress(deviceAddress),
+ mIsInput(isInput(metadata)) {
+ mStreamConfig.frameSize = context->getFrameSize();
+ mStreamConfig.format = context->getFormat();
+ mStreamConfig.channelLayout = context->getChannelLayout();
+ mStreamConfig.sampleRate = context->getSampleRate();
+}
+
+std::mutex StreamRemoteSubmix::sSubmixRoutesLock;
+std::map<AudioDeviceAddress, std::shared_ptr<SubmixRoute>> StreamRemoteSubmix::sSubmixRoutes;
+
+::android::status_t StreamRemoteSubmix::init() {
+ {
+ std::lock_guard guard(sSubmixRoutesLock);
+ auto routeItr = sSubmixRoutes.find(mDeviceAddress);
+ if (routeItr != sSubmixRoutes.end()) {
+ mCurrentRoute = routeItr->second;
+ }
+ }
+ // If route is not available for this port, add it.
+ if (mCurrentRoute == nullptr) {
+ // Initialize the pipe.
+ mCurrentRoute = std::make_shared<SubmixRoute>();
+ if (::android::OK != mCurrentRoute->createPipe(mStreamConfig)) {
+ LOG(ERROR) << __func__ << ": create pipe failed";
+ return ::android::NO_INIT;
+ }
+ {
+ std::lock_guard guard(sSubmixRoutesLock);
+ sSubmixRoutes.emplace(mDeviceAddress, mCurrentRoute);
+ }
+ } else {
+ if (!mCurrentRoute->isStreamConfigValid(mIsInput, mStreamConfig)) {
+ LOG(ERROR) << __func__ << ": invalid stream config";
+ return ::android::NO_INIT;
+ }
+ sp<MonoPipe> sink = mCurrentRoute->getSink();
+ if (sink == nullptr) {
+ LOG(ERROR) << __func__ << ": nullptr sink when opening stream";
+ return ::android::NO_INIT;
+ }
+ // If the sink has been shutdown or pipe recreation is forced, delete the pipe and
+ // recreate it.
+ if (sink->isShutdown()) {
+ LOG(DEBUG) << __func__ << ": Non-nullptr shut down sink when opening stream";
+ if (::android::OK != mCurrentRoute->resetPipe()) {
+ LOG(ERROR) << __func__ << ": reset pipe failed";
+ return ::android::NO_INIT;
+ }
+ }
+ }
+
+ mCurrentRoute->openStream(mIsInput);
+ return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::drain(StreamDescriptor::DrainMode) {
+ usleep(1000);
+ return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::flush() {
+ usleep(1000);
+ return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::pause() {
+ usleep(1000);
+ return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::standby() {
+ mCurrentRoute->standby(mIsInput);
+ return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::start() {
+ mCurrentRoute->exitStandby(mIsInput);
+ return ::android::OK;
+}
+
+ndk::ScopedAStatus StreamRemoteSubmix::prepareToClose() {
+ if (!mIsInput) {
+ std::shared_ptr<SubmixRoute> route = nullptr;
+ {
+ std::lock_guard guard(sSubmixRoutesLock);
+ auto routeItr = sSubmixRoutes.find(mDeviceAddress);
+ if (routeItr != sSubmixRoutes.end()) {
+ route = routeItr->second;
+ }
+ }
+ if (route != nullptr) {
+ sp<MonoPipe> sink = route->getSink();
+ if (sink == nullptr) {
+ ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ LOG(DEBUG) << __func__ << ": shutting down MonoPipe sink";
+
+ sink->shutdown(true);
+ } else {
+ LOG(DEBUG) << __func__ << ": stream already closed.";
+ ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ }
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+// Remove references to the specified input and output streams. When the device no longer
+// references input and output streams destroy the associated pipe.
+void StreamRemoteSubmix::shutdown() {
+ mCurrentRoute->closeStream(mIsInput);
+ // If all stream instances are closed, we can remove route information for this port.
+ if (!mCurrentRoute->hasAtleastOneStreamOpen()) {
+ mCurrentRoute->releasePipe();
+ LOG(DEBUG) << __func__ << ": pipe destroyed";
+
+ std::lock_guard guard(sSubmixRoutesLock);
+ sSubmixRoutes.erase(mDeviceAddress);
+ }
+ mCurrentRoute.reset();
+}
+
+::android::status_t StreamRemoteSubmix::transfer(void* buffer, size_t frameCount,
+ size_t* actualFrameCount, int32_t* latencyMs) {
+ *latencyMs = (getStreamPipeSizeInFrames() * MILLIS_PER_SECOND) / mStreamConfig.sampleRate;
+ LOG(VERBOSE) << __func__ << ": Latency " << *latencyMs << "ms";
+
+ sp<MonoPipe> sink = mCurrentRoute->getSink();
+ if (sink != nullptr) {
+ if (sink->isShutdown()) {
+ sink.clear();
+ LOG(VERBOSE) << __func__ << ": pipe shutdown, ignoring the transfer.";
+ // the pipe has already been shutdown, this buffer will be lost but we must simulate
+ // timing so we don't drain the output faster than realtime
+ const size_t delayUs = static_cast<size_t>(
+ std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
+ usleep(delayUs);
+
+ *actualFrameCount = frameCount;
+ return ::android::OK;
+ }
+ } else {
+ LOG(ERROR) << __func__ << ": transfer without a pipe!";
+ return ::android::UNEXPECTED_NULL;
+ }
+ mCurrentRoute->exitStandby(mIsInput);
+ return (mIsInput ? inRead(buffer, frameCount, actualFrameCount)
+ : outWrite(buffer, frameCount, actualFrameCount));
+}
+
+::android::status_t StreamRemoteSubmix::refinePosition(StreamDescriptor::Position* position) {
+ sp<MonoPipeReader> source = mCurrentRoute->getSource();
+ if (source == nullptr) {
+ return ::android::NO_INIT;
+ }
+ const ssize_t framesInPipe = source->availableToRead();
+ if (framesInPipe <= 0) {
+ // No need to update the position frames
+ return ::android::OK;
+ }
+ if (mIsInput) {
+ position->frames += framesInPipe;
+ } else if (position->frames >= framesInPipe) {
+ position->frames -= framesInPipe;
+ }
+ return ::android::OK;
+}
+
+// Calculate the maximum size of the pipe buffer in frames for the specified stream.
+size_t StreamRemoteSubmix::getStreamPipeSizeInFrames() {
+ auto pipeConfig = mCurrentRoute->mPipeConfig;
+ const size_t maxFrameSize = std::max(mStreamConfig.frameSize, pipeConfig.frameSize);
+ return (pipeConfig.frameCount * pipeConfig.frameSize) / maxFrameSize;
+}
+
+::android::status_t StreamRemoteSubmix::outWrite(void* buffer, size_t frameCount,
+ size_t* actualFrameCount) {
+ sp<MonoPipe> sink = mCurrentRoute->getSink();
+ if (sink != nullptr) {
+ if (sink->isShutdown()) {
+ sink.clear();
+ LOG(VERBOSE) << __func__ << ": pipe shutdown, ignoring the write.";
+ // the pipe has already been shutdown, this buffer will be lost but we must
+ // simulate timing so we don't drain the output faster than realtime
+ const size_t delayUs = static_cast<size_t>(
+ std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
+ usleep(delayUs);
+ *actualFrameCount = frameCount;
+ return ::android::OK;
+ }
+ } else {
+ LOG(FATAL) << __func__ << ": without a pipe!";
+ return ::android::UNKNOWN_ERROR;
+ }
+
+ const size_t availableToWrite = sink->availableToWrite();
+ // NOTE: sink has been checked above and sink and source life cycles are synchronized
+ sp<MonoPipeReader> source = mCurrentRoute->getSource();
+ // If the write to the sink should be blocked, flush enough frames from the pipe to make space
+ // to write the most recent data.
+ if (!mCurrentRoute->shouldBlockWrite() && availableToWrite < frameCount) {
+ static uint8_t flushBuffer[64];
+ const size_t flushBufferSizeFrames = sizeof(flushBuffer) / mStreamConfig.frameSize;
+ size_t framesToFlushFromSource = frameCount - availableToWrite;
+ LOG(VERBOSE) << __func__ << ": flushing " << framesToFlushFromSource
+ << " frames from the pipe to avoid blocking";
+ while (framesToFlushFromSource) {
+ const size_t flushSize = std::min(framesToFlushFromSource, flushBufferSizeFrames);
+ framesToFlushFromSource -= flushSize;
+ // read does not block
+ source->read(flushBuffer, flushSize);
+ }
+ }
+
+ ssize_t writtenFrames = sink->write(buffer, frameCount);
+ if (writtenFrames < 0) {
+ if (writtenFrames == (ssize_t)::android::NEGOTIATE) {
+ LOG(ERROR) << __func__ << ": write to pipe returned NEGOTIATE";
+ sink.clear();
+ *actualFrameCount = 0;
+ return ::android::UNKNOWN_ERROR;
+ } else {
+ // write() returned UNDERRUN or WOULD_BLOCK, retry
+ LOG(ERROR) << __func__ << ": write to pipe returned unexpected " << writtenFrames;
+ writtenFrames = sink->write(buffer, frameCount);
+ }
+ }
+ sink.clear();
+
+ if (writtenFrames < 0) {
+ LOG(ERROR) << __func__ << ": failed writing to pipe with " << writtenFrames;
+ *actualFrameCount = 0;
+ return ::android::UNKNOWN_ERROR;
+ }
+ LOG(VERBOSE) << __func__ << ": wrote " << writtenFrames << "frames";
+ *actualFrameCount = writtenFrames;
+ return ::android::OK;
+}
+
+::android::status_t StreamRemoteSubmix::inRead(void* buffer, size_t frameCount,
+ size_t* actualFrameCount) {
+ // about to read from audio source
+ sp<MonoPipeReader> source = mCurrentRoute->getSource();
+ if (source == nullptr) {
+ int readErrorCount = mCurrentRoute->notifyReadError();
+ if (readErrorCount < kMaxReadErrorLogs) {
+ LOG(ERROR) << __func__
+ << ": no audio pipe yet we're trying to read! (not all errors will be "
+ "logged)";
+ } else {
+ LOG(ERROR) << __func__ << ": Read errors " << readErrorCount;
+ }
+ const size_t delayUs = static_cast<size_t>(
+ std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
+ usleep(delayUs);
+ memset(buffer, 0, mStreamConfig.frameSize * frameCount);
+ *actualFrameCount = frameCount;
+ return ::android::OK;
+ }
+
+ // read the data from the pipe
+ int attempts = 0;
+ const size_t delayUs = static_cast<size_t>(std::roundf(kReadAttemptSleepUs));
+ char* buff = (char*)buffer;
+ size_t remainingFrames = frameCount;
+ int availableToRead = source->availableToRead();
+
+ while ((remainingFrames > 0) && (availableToRead > 0) && (attempts < kMaxReadFailureAttempts)) {
+ LOG(VERBOSE) << __func__ << ": frames available to read " << availableToRead;
+
+ ssize_t framesRead = source->read(buff, remainingFrames);
+
+ LOG(VERBOSE) << __func__ << ": frames read " << framesRead;
+
+ if (framesRead > 0) {
+ remainingFrames -= framesRead;
+ buff += framesRead * mStreamConfig.frameSize;
+ availableToRead -= framesRead;
+ LOG(VERBOSE) << __func__ << ": (attempts = " << attempts << ") got " << framesRead
+ << " frames, remaining=" << remainingFrames;
+ } else {
+ attempts++;
+ LOG(WARNING) << __func__ << ": read returned " << framesRead
+ << " , read failure attempts = " << attempts;
+ usleep(delayUs);
+ }
+ }
+ // done using the source
+ source.clear();
+
+ if (remainingFrames > 0) {
+ const size_t remainingBytes = remainingFrames * mStreamConfig.frameSize;
+ LOG(VERBOSE) << __func__ << ": clearing remaining_frames = " << remainingFrames;
+ memset(((char*)buffer) + (mStreamConfig.frameSize * frameCount) - remainingBytes, 0,
+ remainingBytes);
+ }
+
+ long readCounterFrames = mCurrentRoute->updateReadCounterFrames(frameCount);
+ *actualFrameCount = frameCount;
+
+ // compute how much we need to sleep after reading the data by comparing the wall clock with
+ // the projected time at which we should return.
+ // wall clock after reading from the pipe
+ auto recordDurationUs = std::chrono::steady_clock::now() - mCurrentRoute->getRecordStartTime();
+
+ // readCounterFrames contains the number of frames that have been read since the beginning of
+ // recording (including this call): it's converted to usec and compared to how long we've been
+ // recording for, which gives us how long we must wait to sync the projected recording time, and
+ // the observed recording time.
+ const int projectedVsObservedOffsetUs =
+ std::roundf((readCounterFrames * MICROS_PER_SECOND / mStreamConfig.sampleRate) -
+ recordDurationUs.count());
+
+ LOG(VERBOSE) << __func__ << ": record duration " << recordDurationUs.count()
+ << " microseconds, will wait: " << projectedVsObservedOffsetUs << " microseconds";
+ if (projectedVsObservedOffsetUs > 0) {
+ usleep(projectedVsObservedOffsetUs);
+ }
+ return ::android::OK;
+}
+
+StreamInRemoteSubmix::StreamInRemoteSubmix(StreamContext&& context,
+ const SinkMetadata& sinkMetadata,
+ const std::vector<MicrophoneInfo>& microphones)
+ : StreamIn(std::move(context), microphones), StreamSwitcher(&mContextInstance, sinkMetadata) {}
+
+ndk::ScopedAStatus StreamInRemoteSubmix::getActiveMicrophones(
+ std::vector<MicrophoneDynamicInfo>* _aidl_return) {
+ LOG(DEBUG) << __func__ << ": not supported";
+ *_aidl_return = std::vector<MicrophoneDynamicInfo>();
+ return ndk::ScopedAStatus::ok();
+}
+
+StreamSwitcher::DeviceSwitchBehavior StreamInRemoteSubmix::switchCurrentStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
+ // This implementation effectively postpones stream creation until
+ // receiving the first call to 'setConnectedDevices' with a non-empty list.
+ if (isStubStream()) {
+ if (devices.size() == 1) {
+ auto deviceDesc = devices.front().type;
+ if (deviceDesc.type ==
+ ::aidl::android::media::audio::common::AudioDeviceType::IN_SUBMIX) {
+ return DeviceSwitchBehavior::CREATE_NEW_STREAM;
+ }
+ LOG(ERROR) << __func__ << ": Device type " << toString(deviceDesc.type)
+ << " not supported";
+ } else {
+ LOG(ERROR) << __func__ << ": Only single device supported.";
+ }
+ return DeviceSwitchBehavior::UNSUPPORTED_DEVICES;
+ }
+ return DeviceSwitchBehavior::USE_CURRENT_STREAM;
+}
+
+std::unique_ptr<StreamCommonInterfaceEx> StreamInRemoteSubmix::createNewStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
+ StreamContext* context, const Metadata& metadata) {
+ return std::unique_ptr<StreamCommonInterfaceEx>(
+ new InnerStreamWrapper<StreamRemoteSubmix>(context, metadata, devices.front().address));
+}
+
+StreamOutRemoteSubmix::StreamOutRemoteSubmix(StreamContext&& context,
+ const SourceMetadata& sourceMetadata,
+ const std::optional<AudioOffloadInfo>& offloadInfo)
+ : StreamOut(std::move(context), offloadInfo),
+ StreamSwitcher(&mContextInstance, sourceMetadata) {}
+
+StreamSwitcher::DeviceSwitchBehavior StreamOutRemoteSubmix::switchCurrentStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
+ // This implementation effectively postpones stream creation until
+ // receiving the first call to 'setConnectedDevices' with a non-empty list.
+ if (isStubStream()) {
+ if (devices.size() == 1) {
+ auto deviceDesc = devices.front().type;
+ if (deviceDesc.type ==
+ ::aidl::android::media::audio::common::AudioDeviceType::OUT_SUBMIX) {
+ return DeviceSwitchBehavior::CREATE_NEW_STREAM;
+ }
+ LOG(ERROR) << __func__ << ": Device type " << toString(deviceDesc.type)
+ << " not supported";
+ } else {
+ LOG(ERROR) << __func__ << ": Only single device supported.";
+ }
+ return DeviceSwitchBehavior::UNSUPPORTED_DEVICES;
+ }
+ return DeviceSwitchBehavior::USE_CURRENT_STREAM;
+}
+
+std::unique_ptr<StreamCommonInterfaceEx> StreamOutRemoteSubmix::createNewStream(
+ const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
+ StreamContext* context, const Metadata& metadata) {
+ return std::unique_ptr<StreamCommonInterfaceEx>(
+ new InnerStreamWrapper<StreamRemoteSubmix>(context, metadata, devices.front().address));
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/r_submix/SubmixRoute.cpp b/audio/aidl/default/r_submix/SubmixRoute.cpp
new file mode 100644
index 0000000..ddac64d
--- /dev/null
+++ b/audio/aidl/default/r_submix/SubmixRoute.cpp
@@ -0,0 +1,230 @@
+/*
+ * Copyright (C) 2023 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 "AHAL_SubmixRoute"
+#include <android-base/logging.h>
+#include <media/AidlConversionCppNdk.h>
+
+#include <Utils.h>
+
+#include "SubmixRoute.h"
+
+using aidl::android::hardware::audio::common::getChannelCount;
+
+namespace aidl::android::hardware::audio::core::r_submix {
+
+// Verify a submix input or output stream can be opened.
+bool SubmixRoute::isStreamConfigValid(bool isInput, const AudioConfig& streamConfig) {
+ // If the stream is already open, don't open it again.
+ // ENABLE_LEGACY_INPUT_OPEN is default behaviour
+ if (!isInput && isStreamOutOpen()) {
+ LOG(ERROR) << __func__ << ": output stream already open.";
+ return false;
+ }
+ // If either stream is open, verify the existing pipe config matches the stream config.
+ if (hasAtleastOneStreamOpen() && !isStreamConfigCompatible(streamConfig)) {
+ return false;
+ }
+ return true;
+}
+
+// Compare this stream config with existing pipe config, returning false if they do *not*
+// match, true otherwise.
+bool SubmixRoute::isStreamConfigCompatible(const AudioConfig& streamConfig) {
+ if (streamConfig.channelLayout != mPipeConfig.channelLayout) {
+ LOG(ERROR) << __func__ << ": channel count mismatch, stream channels = "
+ << streamConfig.channelLayout.toString()
+ << " pipe config channels = " << mPipeConfig.channelLayout.toString();
+ return false;
+ }
+ if (streamConfig.sampleRate != mPipeConfig.sampleRate) {
+ LOG(ERROR) << __func__
+ << ": sample rate mismatch, stream sample rate = " << streamConfig.sampleRate
+ << " pipe config sample rate = " << mPipeConfig.sampleRate;
+ return false;
+ }
+ if (streamConfig.format != mPipeConfig.format) {
+ LOG(ERROR) << __func__
+ << ": format mismatch, stream format = " << streamConfig.format.toString()
+ << " pipe config format = " << mPipeConfig.format.toString();
+ return false;
+ }
+ return true;
+}
+
+bool SubmixRoute::hasAtleastOneStreamOpen() {
+ std::lock_guard guard(mLock);
+ return (mStreamInOpen || mStreamOutOpen);
+}
+
+// We DO NOT block if:
+// - no peer input stream is present
+// - the peer input is in standby AFTER having been active.
+// We DO block if:
+// - the input was never activated to avoid discarding first frames in the pipe in case capture
+// start was delayed
+bool SubmixRoute::shouldBlockWrite() {
+ std::lock_guard guard(mLock);
+ return (mStreamInOpen || (mStreamInStandby && (mReadCounterFrames != 0)));
+}
+
+int SubmixRoute::notifyReadError() {
+ std::lock_guard guard(mLock);
+ return ++mReadErrorCount;
+}
+
+long SubmixRoute::updateReadCounterFrames(size_t frameCount) {
+ std::lock_guard guard(mLock);
+ mReadCounterFrames += frameCount;
+ return mReadCounterFrames;
+}
+
+void SubmixRoute::openStream(bool isInput) {
+ std::lock_guard guard(mLock);
+ if (isInput) {
+ if (mStreamInOpen) {
+ mInputRefCount++;
+ } else {
+ mInputRefCount = 1;
+ mStreamInOpen = true;
+ }
+ mStreamInStandby = true;
+ mReadCounterFrames = 0;
+ mReadErrorCount = 0;
+ } else {
+ mStreamOutOpen = true;
+ }
+}
+
+void SubmixRoute::closeStream(bool isInput) {
+ std::lock_guard guard(mLock);
+ if (isInput) {
+ mInputRefCount--;
+ if (mInputRefCount == 0) {
+ mStreamInOpen = false;
+ if (mSink != nullptr) {
+ mSink->shutdown(true);
+ }
+ }
+ } else {
+ mStreamOutOpen = false;
+ }
+}
+
+// If SubmixRoute doesn't exist for a port, create a pipe for the submix audio device of size
+// buffer_size_frames and store config of the submix audio device.
+::android::status_t SubmixRoute::createPipe(const AudioConfig& streamConfig) {
+ const int channelCount = getChannelCount(streamConfig.channelLayout);
+ const audio_format_t audioFormat = VALUE_OR_RETURN_STATUS(
+ aidl2legacy_AudioFormatDescription_audio_format_t(streamConfig.format));
+ const ::android::NBAIO_Format format =
+ ::android::Format_from_SR_C(streamConfig.sampleRate, channelCount, audioFormat);
+ const ::android::NBAIO_Format offers[1] = {format};
+ size_t numCounterOffers = 0;
+
+ const size_t pipeSizeInFrames =
+ r_submix::kDefaultPipeSizeInFrames *
+ ((float)streamConfig.sampleRate / r_submix::kDefaultSampleRateHz);
+ LOG(VERBOSE) << __func__ << ": creating pipe, rate : " << streamConfig.sampleRate
+ << ", pipe size : " << pipeSizeInFrames;
+
+ // Create a MonoPipe with optional blocking set to true.
+ sp<MonoPipe> sink = sp<MonoPipe>::make(pipeSizeInFrames, format, true /*writeCanBlock*/);
+ if (sink == nullptr) {
+ LOG(FATAL) << __func__ << ": sink is null";
+ return ::android::UNEXPECTED_NULL;
+ }
+
+ // Negotiation between the source and sink cannot fail as the device open operation
+ // creates both ends of the pipe using the same audio format.
+ ssize_t index = sink->negotiate(offers, 1, nullptr, numCounterOffers);
+ if (index != 0) {
+ LOG(FATAL) << __func__ << ": Negotiation for the sink failed, index = " << index;
+ return ::android::BAD_INDEX;
+ }
+ sp<MonoPipeReader> source = sp<MonoPipeReader>::make(sink.get());
+ if (source == nullptr) {
+ LOG(FATAL) << __func__ << ": source is null";
+ return ::android::UNEXPECTED_NULL;
+ }
+ numCounterOffers = 0;
+ index = source->negotiate(offers, 1, nullptr, numCounterOffers);
+ if (index != 0) {
+ LOG(FATAL) << __func__ << ": Negotiation for the source failed, index = " << index;
+ return ::android::BAD_INDEX;
+ }
+ LOG(VERBOSE) << __func__ << ": created pipe";
+
+ mPipeConfig = streamConfig;
+ mPipeConfig.frameCount = sink->maxFrames();
+
+ LOG(VERBOSE) << __func__ << ": Pipe frame size : " << mPipeConfig.frameSize
+ << ", pipe frames : " << mPipeConfig.frameCount;
+
+ // Save references to the source and sink.
+ {
+ std::lock_guard guard(mLock);
+ mSink = std::move(sink);
+ mSource = std::move(source);
+ }
+
+ return ::android::OK;
+}
+
+// Release references to the sink and source.
+void SubmixRoute::releasePipe() {
+ std::lock_guard guard(mLock);
+ mSink.clear();
+ mSource.clear();
+}
+
+::android::status_t SubmixRoute::resetPipe() {
+ releasePipe();
+ return createPipe(mPipeConfig);
+}
+
+void SubmixRoute::standby(bool isInput) {
+ std::lock_guard guard(mLock);
+
+ if (isInput) {
+ mStreamInStandby = true;
+ } else if (!mStreamOutStandby) {
+ mStreamOutStandby = true;
+ mStreamOutStandbyTransition = true;
+ }
+}
+
+void SubmixRoute::exitStandby(bool isInput) {
+ std::lock_guard guard(mLock);
+
+ if (isInput) {
+ if (mStreamInStandby || mStreamOutStandbyTransition) {
+ mStreamInStandby = false;
+ mStreamOutStandbyTransition = false;
+ // keep track of when we exit input standby (== first read == start "real recording")
+ // or when we start recording silence, and reset projected time
+ mRecordStartTime = std::chrono::steady_clock::now();
+ mReadCounterFrames = 0;
+ }
+ } else {
+ if (mStreamOutStandby) {
+ mStreamOutStandby = false;
+ mStreamOutStandbyTransition = true;
+ }
+ }
+}
+
+} // namespace aidl::android::hardware::audio::core::r_submix
diff --git a/audio/aidl/default/r_submix/SubmixRoute.h b/audio/aidl/default/r_submix/SubmixRoute.h
new file mode 100644
index 0000000..1a98df2
--- /dev/null
+++ b/audio/aidl/default/r_submix/SubmixRoute.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2023 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 <mutex>
+
+#include <audio_utils/clock.h>
+
+#include <media/nbaio/MonoPipe.h>
+#include <media/nbaio/MonoPipeReader.h>
+
+#include <aidl/android/media/audio/common/AudioChannelLayout.h>
+
+#include "core-impl/Stream.h"
+
+using aidl::android::media::audio::common::AudioChannelLayout;
+using aidl::android::media::audio::common::AudioFormatDescription;
+using aidl::android::media::audio::common::AudioFormatType;
+using aidl::android::media::audio::common::PcmType;
+using ::android::MonoPipe;
+using ::android::MonoPipeReader;
+using ::android::sp;
+
+namespace aidl::android::hardware::audio::core::r_submix {
+
+static constexpr int kDefaultSampleRateHz = 48000;
+// Size at default sample rate
+// NOTE: This value will be rounded up to the nearest power of 2 by MonoPipe().
+static constexpr int kDefaultPipeSizeInFrames = (1024 * 4);
+
+// Configuration of the audio stream.
+struct AudioConfig {
+ int sampleRate = kDefaultSampleRateHz;
+ AudioFormatDescription format =
+ AudioFormatDescription{.type = AudioFormatType::PCM, .pcm = PcmType::INT_16_BIT};
+ AudioChannelLayout channelLayout =
+ AudioChannelLayout::make<AudioChannelLayout::Tag::layoutMask>(
+ AudioChannelLayout::LAYOUT_STEREO);
+ size_t frameSize;
+ size_t frameCount;
+};
+
+class SubmixRoute {
+ public:
+ AudioConfig mPipeConfig;
+
+ bool isStreamInOpen() {
+ std::lock_guard guard(mLock);
+ return mStreamInOpen;
+ }
+ bool getStreamInStandby() {
+ std::lock_guard guard(mLock);
+ return mStreamInStandby;
+ }
+ bool isStreamOutOpen() {
+ std::lock_guard guard(mLock);
+ return mStreamOutOpen;
+ }
+ bool getStreamOutStandby() {
+ std::lock_guard guard(mLock);
+ return mStreamOutStandby;
+ }
+ long getReadCounterFrames() {
+ std::lock_guard guard(mLock);
+ return mReadCounterFrames;
+ }
+ int getReadErrorCount() {
+ std::lock_guard guard(mLock);
+ return mReadErrorCount;
+ }
+ std::chrono::time_point<std::chrono::steady_clock> getRecordStartTime() {
+ std::lock_guard guard(mLock);
+ return mRecordStartTime;
+ }
+ sp<MonoPipe> getSink() {
+ std::lock_guard guard(mLock);
+ return mSink;
+ }
+ sp<MonoPipeReader> getSource() {
+ std::lock_guard guard(mLock);
+ return mSource;
+ }
+
+ bool isStreamConfigValid(bool isInput, const AudioConfig& streamConfig);
+ void closeStream(bool isInput);
+ ::android::status_t createPipe(const AudioConfig& streamConfig);
+ void exitStandby(bool isInput);
+ bool hasAtleastOneStreamOpen();
+ int notifyReadError();
+ void openStream(bool isInput);
+ void releasePipe();
+ ::android::status_t resetPipe();
+ bool shouldBlockWrite();
+ void standby(bool isInput);
+ long updateReadCounterFrames(size_t frameCount);
+
+ private:
+ bool isStreamConfigCompatible(const AudioConfig& streamConfig);
+
+ std::mutex mLock;
+
+ bool mStreamInOpen GUARDED_BY(mLock) = false;
+ int mInputRefCount GUARDED_BY(mLock) = 0;
+ bool mStreamInStandby GUARDED_BY(mLock) = true;
+ bool mStreamOutStandbyTransition GUARDED_BY(mLock) = false;
+ bool mStreamOutOpen GUARDED_BY(mLock) = false;
+ bool mStreamOutStandby GUARDED_BY(mLock) = true;
+ // how many frames have been requested to be read since standby
+ long mReadCounterFrames GUARDED_BY(mLock) = 0;
+ int mReadErrorCount GUARDED_BY(mLock) = 0;
+ // wall clock when recording starts
+ std::chrono::time_point<std::chrono::steady_clock> mRecordStartTime GUARDED_BY(mLock);
+
+ // Pipe variables: they handle the ring buffer that "pipes" audio:
+ // - from the submix virtual audio output == what needs to be played
+ // remotely, seen as an output for the client
+ // - to the virtual audio source == what is captured by the component
+ // which "records" the submix / virtual audio source, and handles it as needed.
+ // A usecase example is one where the component capturing the audio is then sending it over
+ // Wifi for presentation on a remote Wifi Display device (e.g. a dongle attached to a TV, or a
+ // TV with Wifi Display capabilities), or to a wireless audio player.
+ sp<MonoPipe> mSink GUARDED_BY(mLock);
+ sp<MonoPipeReader> mSource GUARDED_BY(mLock);
+};
+
+} // namespace aidl::android::hardware::audio::core::r_submix
diff --git a/audio/aidl/default/stub/ModuleStub.cpp b/audio/aidl/default/stub/ModuleStub.cpp
new file mode 100644
index 0000000..9f6e0b4
--- /dev/null
+++ b/audio/aidl/default/stub/ModuleStub.cpp
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2023 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 <vector>
+
+#define LOG_TAG "AHAL_ModuleStub"
+#include <Utils.h>
+#include <android-base/logging.h>
+
+#include "core-impl/Bluetooth.h"
+#include "core-impl/ModuleStub.h"
+#include "core-impl/StreamStub.h"
+
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
+using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::AudioPort;
+using aidl::android::media::audio::common::AudioPortConfig;
+using aidl::android::media::audio::common::MicrophoneInfo;
+
+namespace aidl::android::hardware::audio::core {
+
+ndk::ScopedAStatus ModuleStub::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
+ if (!mBluetooth) {
+ mBluetooth = ndk::SharedRefBase::make<Bluetooth>();
+ }
+ *_aidl_return = mBluetooth.getInstance();
+ LOG(DEBUG) << __func__
+ << ": returning instance of IBluetooth: " << _aidl_return->get()->asBinder().get();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleStub::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
+ if (!mBluetoothA2dp) {
+ mBluetoothA2dp = ndk::SharedRefBase::make<BluetoothA2dp>();
+ }
+ *_aidl_return = mBluetoothA2dp.getInstance();
+ LOG(DEBUG) << __func__ << ": returning instance of IBluetoothA2dp: "
+ << _aidl_return->get()->asBinder().get();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleStub::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
+ if (!mBluetoothLe) {
+ mBluetoothLe = ndk::SharedRefBase::make<BluetoothLe>();
+ }
+ *_aidl_return = mBluetoothLe.getInstance();
+ LOG(DEBUG) << __func__
+ << ": returning instance of IBluetoothLe: " << _aidl_return->get()->asBinder().get();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleStub::createInputStream(StreamContext&& context,
+ const SinkMetadata& sinkMetadata,
+ const std::vector<MicrophoneInfo>& microphones,
+ std::shared_ptr<StreamIn>* result) {
+ return createStreamInstance<StreamInStub>(result, std::move(context), sinkMetadata,
+ microphones);
+}
+
+ndk::ScopedAStatus ModuleStub::createOutputStream(
+ StreamContext&& context, const SourceMetadata& sourceMetadata,
+ const std::optional<AudioOffloadInfo>& offloadInfo, std::shared_ptr<StreamOut>* result) {
+ return createStreamInstance<StreamOutStub>(result, std::move(context), sourceMetadata,
+ offloadInfo);
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/stub/StreamStub.cpp b/audio/aidl/default/stub/StreamStub.cpp
new file mode 100644
index 0000000..660a51e
--- /dev/null
+++ b/audio/aidl/default/stub/StreamStub.cpp
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2023 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 <cmath>
+
+#define LOG_TAG "AHAL_Stream"
+#include <android-base/logging.h>
+#include <audio_utils/clock.h>
+
+#include "core-impl/Module.h"
+#include "core-impl/StreamStub.h"
+
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
+using aidl::android::media::audio::common::AudioDevice;
+using aidl::android::media::audio::common::AudioOffloadInfo;
+using aidl::android::media::audio::common::MicrophoneInfo;
+
+namespace aidl::android::hardware::audio::core {
+
+StreamStub::StreamStub(StreamContext* context, const Metadata& metadata)
+ : StreamCommonImpl(context, metadata),
+ mBufferSizeFrames(getContext().getBufferSizeInFrames()),
+ mFrameSizeBytes(getContext().getFrameSize()),
+ mSampleRate(getContext().getSampleRate()),
+ mIsAsynchronous(!!getContext().getAsyncCallback()),
+ mIsInput(isInput(metadata)) {}
+
+::android::status_t StreamStub::init() {
+ mIsInitialized = true;
+ return ::android::OK;
+}
+
+::android::status_t StreamStub::drain(StreamDescriptor::DrainMode) {
+ if (!mIsInitialized) {
+ LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+ }
+ if (!mIsInput) {
+ if (!mIsAsynchronous) {
+ static constexpr float kMicrosPerSecond = MICROS_PER_SECOND;
+ const size_t delayUs = static_cast<size_t>(
+ std::roundf(mBufferSizeFrames * kMicrosPerSecond / mSampleRate));
+ usleep(delayUs);
+ } else {
+ usleep(500);
+ }
+ }
+ return ::android::OK;
+}
+
+::android::status_t StreamStub::flush() {
+ if (!mIsInitialized) {
+ LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+ }
+ return ::android::OK;
+}
+
+::android::status_t StreamStub::pause() {
+ if (!mIsInitialized) {
+ LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+ }
+ return ::android::OK;
+}
+
+::android::status_t StreamStub::standby() {
+ if (!mIsInitialized) {
+ LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+ }
+ usleep(500);
+ mIsStandby = true;
+ return ::android::OK;
+}
+
+::android::status_t StreamStub::start() {
+ if (!mIsInitialized) {
+ LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+ }
+ usleep(500);
+ mIsStandby = false;
+ return ::android::OK;
+}
+
+::android::status_t StreamStub::transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
+ int32_t* latencyMs) {
+ if (!mIsInitialized) {
+ LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver";
+ }
+ if (mIsStandby) {
+ LOG(FATAL) << __func__ << ": must not happen while in standby";
+ }
+ static constexpr float kMicrosPerSecond = MICROS_PER_SECOND;
+ static constexpr float kScaleFactor = .8f;
+ if (mIsAsynchronous) {
+ usleep(500);
+ } else {
+ const size_t delayUs = static_cast<size_t>(
+ std::roundf(kScaleFactor * frameCount * kMicrosPerSecond / mSampleRate));
+ usleep(delayUs);
+ }
+ if (mIsInput) {
+ uint8_t* byteBuffer = static_cast<uint8_t*>(buffer);
+ for (size_t i = 0; i < frameCount * mFrameSizeBytes; ++i) {
+ byteBuffer[i] = std::rand() % 255;
+ }
+ }
+ *actualFrameCount = frameCount;
+ *latencyMs = Module::kLatencyMs;
+ return ::android::OK;
+}
+
+void StreamStub::shutdown() {
+ mIsInitialized = false;
+}
+
+StreamInStub::StreamInStub(StreamContext&& context, const SinkMetadata& sinkMetadata,
+ const std::vector<MicrophoneInfo>& microphones)
+ : StreamIn(std::move(context), microphones), StreamStub(&mContextInstance, sinkMetadata) {}
+
+StreamOutStub::StreamOutStub(StreamContext&& context, const SourceMetadata& sourceMetadata,
+ const std::optional<AudioOffloadInfo>& offloadInfo)
+ : StreamOut(std::move(context), offloadInfo), StreamStub(&mContextInstance, sourceMetadata) {}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/audio/aidl/default/tests/AudioPolicyConfigXmlConverterTest.cpp b/audio/aidl/default/tests/AudioPolicyConfigXmlConverterTest.cpp
new file mode 100644
index 0000000..572bc5a
--- /dev/null
+++ b/audio/aidl/default/tests/AudioPolicyConfigXmlConverterTest.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2023 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 <memory>
+// #include <string>
+// #include <vector>
+
+#include <android-base/macros.h>
+#include <gtest/gtest.h>
+#define LOG_TAG "AudioPolicyConfigXmlConverterTest"
+#include <log/log.h>
+
+#include <core-impl/AudioPolicyConfigXmlConverter.h>
+#include <media/AidlConversionCppNdk.h>
+
+using aidl::android::hardware::audio::core::internal::AudioPolicyConfigXmlConverter;
+using aidl::android::media::audio::common::AudioFormatDescription;
+
+namespace {
+
+void ValidateAudioFormatDescription(const AudioFormatDescription& format) {
+ auto conv = ::aidl::android::aidl2legacy_AudioFormatDescription_audio_format_t(format);
+ ASSERT_TRUE(conv.ok()) << format.toString();
+}
+
+} // namespace
+
+TEST(AudioPolicyConfigXmlConverterTest, DefaultSurroundSoundConfigIsValid) {
+ auto config = AudioPolicyConfigXmlConverter::getDefaultSurroundSoundConfig();
+ for (const auto& family : config.formatFamilies) {
+ EXPECT_NO_FATAL_FAILURE(ValidateAudioFormatDescription(family.primaryFormat));
+ SCOPED_TRACE(family.primaryFormat.toString());
+ for (const auto& sub : family.subFormats) {
+ EXPECT_NO_FATAL_FAILURE(ValidateAudioFormatDescription(sub));
+ }
+ }
+}
diff --git a/audio/aidl/default/usb/ModuleUsb.cpp b/audio/aidl/default/usb/ModuleUsb.cpp
index ecdbd5c..f926e09 100644
--- a/audio/aidl/default/usb/ModuleUsb.cpp
+++ b/audio/aidl/default/usb/ModuleUsb.cpp
@@ -14,63 +14,34 @@
* limitations under the License.
*/
-#define LOG_TAG "AHAL_ModuleUsb"
-
#include <vector>
+#define LOG_TAG "AHAL_ModuleUsb"
#include <Utils.h>
#include <android-base/logging.h>
-#include <tinyalsa/asoundlib.h>
#include "UsbAlsaMixerControl.h"
-#include "UsbAlsaUtils.h"
+#include "alsa/Utils.h"
#include "core-impl/ModuleUsb.h"
+#include "core-impl/StreamUsb.h"
-extern "C" {
-#include "alsa_device_profile.h"
-}
-
-using aidl::android::hardware::audio::common::isUsbInputDeviceType;
-using aidl::android::media::audio::common::AudioChannelLayout;
-using aidl::android::media::audio::common::AudioDeviceAddress;
+using aidl::android::hardware::audio::common::SinkMetadata;
+using aidl::android::hardware::audio::common::SourceMetadata;
using aidl::android::media::audio::common::AudioDeviceDescription;
-using aidl::android::media::audio::common::AudioDeviceType;
-using aidl::android::media::audio::common::AudioFormatDescription;
-using aidl::android::media::audio::common::AudioFormatType;
+using aidl::android::media::audio::common::AudioOffloadInfo;
using aidl::android::media::audio::common::AudioPort;
using aidl::android::media::audio::common::AudioPortConfig;
using aidl::android::media::audio::common::AudioPortExt;
-using aidl::android::media::audio::common::AudioProfile;
+using aidl::android::media::audio::common::MicrophoneInfo;
namespace aidl::android::hardware::audio::core {
namespace {
-std::vector<AudioChannelLayout> populateChannelMasksFromProfile(const alsa_device_profile* profile,
- bool isInput) {
- std::vector<AudioChannelLayout> channels;
- for (size_t i = 0; i < AUDIO_PORT_MAX_CHANNEL_MASKS && profile->channel_counts[i] != 0; ++i) {
- auto layoutMask =
- usb::getChannelLayoutMaskFromChannelCount(profile->channel_counts[i], isInput);
- if (layoutMask.getTag() == AudioChannelLayout::Tag::layoutMask) {
- channels.push_back(layoutMask);
- }
- auto indexMask = usb::getChannelIndexMaskFromChannelCount(profile->channel_counts[i]);
- if (indexMask.getTag() == AudioChannelLayout::Tag::indexMask) {
- channels.push_back(indexMask);
- }
- }
- return channels;
-}
-
-std::vector<int> populateSampleRatesFromProfile(const alsa_device_profile* profile) {
- std::vector<int> sampleRates;
- for (int i = 0; i < std::min(MAX_PROFILE_SAMPLE_RATES, AUDIO_PORT_MAX_SAMPLING_RATES) &&
- profile->sample_rates[i] != 0;
- i++) {
- sampleRates.push_back(profile->sample_rates[i]);
- }
- return sampleRates;
+bool isUsbDevicePort(const AudioPort& audioPort) {
+ return audioPort.ext.getTag() == AudioPortExt::Tag::device &&
+ audioPort.ext.get<AudioPortExt::Tag::device>().device.type.connection ==
+ AudioDeviceDescription::CONNECTION_USB;
}
} // namespace
@@ -97,56 +68,31 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
-ndk::ScopedAStatus ModuleUsb::populateConnectedDevicePort(AudioPort* audioPort) {
- if (audioPort->ext.getTag() != AudioPortExt::Tag::device) {
- LOG(ERROR) << __func__ << ": port id " << audioPort->id << " is not a device port";
+ndk::ScopedAStatus ModuleUsb::createInputStream(StreamContext&& context,
+ const SinkMetadata& sinkMetadata,
+ const std::vector<MicrophoneInfo>& microphones,
+ std::shared_ptr<StreamIn>* result) {
+ return createStreamInstance<StreamInUsb>(result, std::move(context), sinkMetadata, microphones);
+}
+
+ndk::ScopedAStatus ModuleUsb::createOutputStream(StreamContext&& context,
+ const SourceMetadata& sourceMetadata,
+ const std::optional<AudioOffloadInfo>& offloadInfo,
+ std::shared_ptr<StreamOut>* result) {
+ if (offloadInfo.has_value()) {
+ LOG(ERROR) << __func__ << ": offload is not supported";
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
- auto& devicePort = audioPort->ext.get<AudioPortExt::Tag::device>();
- if (devicePort.device.type.connection != AudioDeviceDescription::CONNECTION_USB) {
+ return createStreamInstance<StreamOutUsb>(result, std::move(context), sourceMetadata,
+ offloadInfo);
+}
+
+ndk::ScopedAStatus ModuleUsb::populateConnectedDevicePort(AudioPort* audioPort) {
+ if (!isUsbDevicePort(*audioPort)) {
LOG(ERROR) << __func__ << ": port id " << audioPort->id << " is not a usb device port";
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
- if (devicePort.device.address.getTag() != AudioDeviceAddress::Tag::alsa) {
- LOG(ERROR) << __func__ << ": port id " << audioPort->id << " is not using alsa address";
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
- }
- auto& alsaAddress = devicePort.device.address.get<AudioDeviceAddress::Tag::alsa>();
- if (alsaAddress.size() != 2 || alsaAddress[0] < 0 || alsaAddress[1] < 0) {
- LOG(ERROR) << __func__ << ": port id " << audioPort->id << " invalid alsa address";
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
- }
-
- const bool isInput = isUsbInputDeviceType(devicePort.device.type.type);
- alsa_device_profile profile;
- profile_init(&profile, isInput ? PCM_IN : PCM_OUT);
- profile.card = alsaAddress[0];
- profile.device = alsaAddress[1];
- if (!profile_read_device_info(&profile)) {
- LOG(ERROR) << __func__ << ": failed to read device info, card=" << profile.card
- << ", device=" << profile.device;
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
- }
-
- std::vector<AudioChannelLayout> channels = populateChannelMasksFromProfile(&profile, isInput);
- std::vector<int> sampleRates = populateSampleRatesFromProfile(&profile);
-
- for (size_t i = 0; i < std::min(MAX_PROFILE_FORMATS, AUDIO_PORT_MAX_AUDIO_PROFILES) &&
- profile.formats[i] != PCM_FORMAT_INVALID;
- ++i) {
- auto audioFormatDescription =
- usb::legacy2aidl_pcm_format_AudioFormatDescription(profile.formats[i]);
- if (audioFormatDescription.type == AudioFormatType::DEFAULT) {
- LOG(WARNING) << __func__ << ": unknown pcm type=" << profile.formats[i];
- continue;
- }
- AudioProfile audioProfile = {.format = audioFormatDescription,
- .channelMasks = channels,
- .sampleRates = sampleRates};
- audioPort->profiles.push_back(std::move(audioProfile));
- }
-
- return ndk::ScopedAStatus::ok();
+ return ModuleAlsa::populateConnectedDevicePort(audioPort);
}
ndk::ScopedAStatus ModuleUsb::checkAudioPatchEndpointsMatch(
@@ -167,16 +113,15 @@
void ModuleUsb::onExternalDeviceConnectionChanged(
const ::aidl::android::media::audio::common::AudioPort& audioPort, bool connected) {
- if (audioPort.ext.getTag() != AudioPortExt::Tag::device) {
+ if (!isUsbDevicePort(audioPort)) {
return;
}
- const auto& address = audioPort.ext.get<AudioPortExt::Tag::device>().device.address;
- if (address.getTag() != AudioDeviceAddress::alsa) {
+ auto profile = alsa::getDeviceProfile(audioPort);
+ if (!profile.has_value()) {
return;
}
- const int card = address.get<AudioDeviceAddress::alsa>()[0];
- usb::UsbAlsaMixerControl::getInstance().setDeviceConnectionState(card, mMasterMute,
- mMasterVolume, connected);
+ usb::UsbAlsaMixerControl::getInstance().setDeviceConnectionState(profile->card, getMasterMute(),
+ getMasterVolume(), connected);
}
ndk::ScopedAStatus ModuleUsb::onMasterMuteChanged(bool mute) {
diff --git a/audio/aidl/default/usb/StreamUsb.cpp b/audio/aidl/default/usb/StreamUsb.cpp
index 5d1d7fe..b60b4fd 100644
--- a/audio/aidl/default/usb/StreamUsb.cpp
+++ b/audio/aidl/default/usb/StreamUsb.cpp
@@ -14,211 +14,75 @@
* limitations under the License.
*/
+#include <limits>
+
#define LOG_TAG "AHAL_StreamUsb"
#include <android-base/logging.h>
-
-#include <Utils.h>
+#include <error/expected_utils.h>
#include "UsbAlsaMixerControl.h"
-#include "UsbAlsaUtils.h"
-#include "core-impl/Module.h"
#include "core-impl/StreamUsb.h"
-extern "C" {
-#include "alsa_device_profile.h"
-}
-
-using aidl::android::hardware::audio::common::getChannelCount;
using aidl::android::hardware::audio::common::SinkMetadata;
using aidl::android::hardware::audio::common::SourceMetadata;
using aidl::android::media::audio::common::AudioDevice;
-using aidl::android::media::audio::common::AudioDeviceAddress;
using aidl::android::media::audio::common::AudioOffloadInfo;
-using aidl::android::media::audio::common::AudioPortExt;
using aidl::android::media::audio::common::MicrophoneDynamicInfo;
using aidl::android::media::audio::common::MicrophoneInfo;
-using android::OK;
-using android::status_t;
namespace aidl::android::hardware::audio::core {
-DriverUsb::DriverUsb(const StreamContext& context, bool isInput)
- : mFrameSizeBytes(context.getFrameSize()), mIsInput(isInput) {
- struct pcm_config config;
- config.channels = usb::getChannelCountFromChannelMask(context.getChannelLayout(), isInput);
- if (config.channels == 0) {
- LOG(ERROR) << __func__ << ": invalid channel=" << context.getChannelLayout().toString();
- return;
- }
- config.format = usb::aidl2legacy_AudioFormatDescription_pcm_format(context.getFormat());
- if (config.format == PCM_FORMAT_INVALID) {
- LOG(ERROR) << __func__ << ": invalid format=" << context.getFormat().toString();
- return;
- }
- config.rate = context.getSampleRate();
- if (config.rate == 0) {
- LOG(ERROR) << __func__ << ": invalid sample rate=" << config.rate;
- return;
- }
- mConfig = config;
-}
+StreamUsb::StreamUsb(StreamContext* context, const Metadata& metadata)
+ : StreamAlsa(context, metadata, 1 /*readWriteRetries*/) {}
-::android::status_t DriverUsb::init() {
- return mConfig.has_value() ? ::android::OK : ::android::NO_INIT;
-}
-
-::android::status_t DriverUsb::setConnectedDevices(
+ndk::ScopedAStatus StreamUsb::setConnectedDevices(
const std::vector<AudioDevice>& connectedDevices) {
if (mIsInput && connectedDevices.size() > 1) {
LOG(ERROR) << __func__ << ": wrong device size(" << connectedDevices.size()
<< ") for input stream";
- return ::android::BAD_VALUE;
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
+ std::vector<alsa::DeviceProfile> connectedDeviceProfiles;
for (const auto& connectedDevice : connectedDevices) {
- if (connectedDevice.address.getTag() != AudioDeviceAddress::alsa) {
- LOG(ERROR) << __func__ << ": bad device address" << connectedDevice.address.toString();
- return ::android::BAD_VALUE;
- }
- }
- std::lock_guard guard(mLock);
- mAlsaDeviceProxies.clear();
- mConnectedDevices.clear();
- for (const auto& connectedDevice : connectedDevices) {
- mConnectedDevices.push_back(connectedDevice.address);
- }
- return ::android::OK;
-}
-
-::android::status_t DriverUsb::drain(StreamDescriptor::DrainMode) {
- usleep(1000);
- return ::android::OK;
-}
-
-::android::status_t DriverUsb::flush() {
- usleep(1000);
- return ::android::OK;
-}
-
-::android::status_t DriverUsb::pause() {
- usleep(1000);
- return ::android::OK;
-}
-
-::android::status_t DriverUsb::transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
- int32_t* latencyMs) {
- if (!mConfig.has_value() || mConnectedDevices.empty()) {
- LOG(ERROR) << __func__ << ": failed, has config: " << mConfig.has_value()
- << ", has connected devices: " << mConnectedDevices.empty();
- return ::android::NO_INIT;
- }
- if (mIsStandby) {
- if (::android::status_t status = exitStandby(); status != ::android::OK) {
- LOG(ERROR) << __func__ << ": failed to exit standby, status=" << status;
- return status;
- }
- }
- std::vector<std::shared_ptr<alsa_device_proxy>> alsaDeviceProxies;
- {
- std::lock_guard guard(mLock);
- alsaDeviceProxies = mAlsaDeviceProxies;
- }
- const size_t bytesToTransfer = frameCount * mFrameSizeBytes;
- if (mIsInput) {
- // For input case, only support single device.
- proxy_read(alsaDeviceProxies[0].get(), buffer, bytesToTransfer);
- } else {
- for (auto& proxy : alsaDeviceProxies) {
- proxy_write(proxy.get(), buffer, bytesToTransfer);
- }
- }
- *actualFrameCount = frameCount;
- *latencyMs = Module::kLatencyMs;
- return ::android::OK;
-}
-
-::android::status_t DriverUsb::standby() {
- if (!mIsStandby) {
- std::lock_guard guard(mLock);
- mAlsaDeviceProxies.clear();
- mIsStandby = true;
- }
- return ::android::OK;
-}
-
-::android::status_t DriverUsb::exitStandby() {
- std::vector<AudioDeviceAddress> connectedDevices;
- {
- std::lock_guard guard(mLock);
- connectedDevices = mConnectedDevices;
- }
- std::vector<std::shared_ptr<alsa_device_proxy>> alsaDeviceProxies;
- for (const auto& device : connectedDevices) {
- alsa_device_profile profile;
- profile_init(&profile, mIsInput ? PCM_IN : PCM_OUT);
- profile.card = device.get<AudioDeviceAddress::alsa>()[0];
- profile.device = device.get<AudioDeviceAddress::alsa>()[1];
- if (!profile_read_device_info(&profile)) {
+ auto profile = alsa::getDeviceProfile(connectedDevice, mIsInput);
+ if (!profile.has_value()) {
LOG(ERROR) << __func__
- << ": unable to read device info, device address=" << device.toString();
- return ::android::UNKNOWN_ERROR;
+ << ": unsupported device address=" << connectedDevice.address.toString();
+ return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
-
- auto proxy = std::shared_ptr<alsa_device_proxy>(new alsa_device_proxy(),
- [](alsa_device_proxy* proxy) {
- proxy_close(proxy);
- free(proxy);
- });
- // Always ask for alsa configure as required since the configuration should be supported
- // by the connected device. That is guaranteed by `setAudioPortConfig` and
- // `setAudioPatch`.
- if (int err =
- proxy_prepare(proxy.get(), &profile, &mConfig.value(), true /*is_bit_perfect*/);
- err != 0) {
- LOG(ERROR) << __func__ << ": fail to prepare for device address=" << device.toString()
- << " error=" << err;
- return ::android::UNKNOWN_ERROR;
- }
- if (int err = proxy_open(proxy.get()); err != 0) {
- LOG(ERROR) << __func__ << ": failed to open device, address=" << device.toString()
- << " error=" << err;
- return ::android::UNKNOWN_ERROR;
- }
- alsaDeviceProxies.push_back(std::move(proxy));
+ connectedDeviceProfiles.push_back(*profile);
}
- {
- std::lock_guard guard(mLock);
- mAlsaDeviceProxies = alsaDeviceProxies;
- }
- mIsStandby = false;
- return ::android::OK;
-}
-
-// static
-ndk::ScopedAStatus StreamInUsb::createInstance(const SinkMetadata& sinkMetadata,
- StreamContext&& context,
- const std::vector<MicrophoneInfo>& microphones,
- std::shared_ptr<StreamIn>* result) {
- std::shared_ptr<StreamIn> stream =
- ndk::SharedRefBase::make<StreamInUsb>(sinkMetadata, std::move(context), microphones);
- if (auto status = initInstance(stream); !status.isOk()) {
- return status;
- }
- *result = std::move(stream);
+ RETURN_STATUS_IF_ERROR(setConnectedDevices(connectedDevices));
+ std::lock_guard guard(mLock);
+ mConnectedDeviceProfiles = std::move(connectedDeviceProfiles);
+ mConnectedDevicesUpdated.store(true, std::memory_order_release);
return ndk::ScopedAStatus::ok();
}
-StreamInUsb::StreamInUsb(const SinkMetadata& sinkMetadata, StreamContext&& context,
+::android::status_t StreamUsb::transfer(void* buffer, size_t frameCount, size_t* actualFrameCount,
+ int32_t* latencyMs) {
+ if (mConnectedDevicesUpdated.load(std::memory_order_acquire)) {
+ // 'setConnectedDevices' was called. I/O will be restarted.
+ *actualFrameCount = 0;
+ *latencyMs = StreamDescriptor::LATENCY_UNKNOWN;
+ return ::android::OK;
+ }
+ return StreamAlsa::transfer(buffer, frameCount, actualFrameCount, latencyMs);
+}
+
+std::vector<alsa::DeviceProfile> StreamUsb::getDeviceProfiles() {
+ std::vector<alsa::DeviceProfile> connectedDevices;
+ {
+ std::lock_guard guard(mLock);
+ connectedDevices = mConnectedDeviceProfiles;
+ mConnectedDevicesUpdated.store(false, std::memory_order_release);
+ }
+ return connectedDevices;
+}
+
+StreamInUsb::StreamInUsb(StreamContext&& context, const SinkMetadata& sinkMetadata,
const std::vector<MicrophoneInfo>& microphones)
- : StreamIn(
- sinkMetadata, std::move(context),
- [](const StreamContext& ctx) -> DriverInterface* {
- return new DriverUsb(ctx, true /*isInput*/);
- },
- [](const StreamContext& ctx, DriverInterface* driver) -> StreamWorkerInterface* {
- // The default worker implementation is used.
- return new StreamInWorker(ctx, driver);
- },
- microphones) {}
+ : StreamIn(std::move(context), microphones), StreamUsb(&mContextInstance, sinkMetadata) {}
ndk::ScopedAStatus StreamInUsb::getActiveMicrophones(
std::vector<MicrophoneDynamicInfo>* _aidl_return __unused) {
@@ -226,59 +90,33 @@
return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
}
-// static
-ndk::ScopedAStatus StreamOutUsb::createInstance(const SourceMetadata& sourceMetadata,
- StreamContext&& context,
- const std::optional<AudioOffloadInfo>& offloadInfo,
- std::shared_ptr<StreamOut>* result) {
- if (offloadInfo.has_value()) {
- LOG(ERROR) << __func__ << ": offload is not supported";
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
- }
- std::shared_ptr<StreamOut> stream =
- ndk::SharedRefBase::make<StreamOutUsb>(sourceMetadata, std::move(context), offloadInfo);
- if (auto status = initInstance(stream); !status.isOk()) {
- return status;
- }
- *result = std::move(stream);
- return ndk::ScopedAStatus::ok();
-}
-
-StreamOutUsb::StreamOutUsb(const SourceMetadata& sourceMetadata, StreamContext&& context,
+StreamOutUsb::StreamOutUsb(StreamContext&& context, const SourceMetadata& sourceMetadata,
const std::optional<AudioOffloadInfo>& offloadInfo)
- : StreamOut(
- sourceMetadata, std::move(context),
- [](const StreamContext& ctx) -> DriverInterface* {
- return new DriverUsb(ctx, false /*isInput*/);
- },
- [](const StreamContext& ctx, DriverInterface* driver) -> StreamWorkerInterface* {
- // The default worker implementation is used.
- return new StreamOutWorker(ctx, driver);
- },
- offloadInfo) {
- mChannelCount = getChannelCount(mContext.getChannelLayout());
-}
+ : StreamOut(std::move(context), offloadInfo),
+ StreamUsb(&mContextInstance, sourceMetadata),
+ StreamOutHwVolumeHelper(&mContextInstance) {}
ndk::ScopedAStatus StreamOutUsb::getHwVolume(std::vector<float>* _aidl_return) {
- *_aidl_return = mHwVolumes;
- return ndk::ScopedAStatus::ok();
+ return getHwVolumeImpl(_aidl_return);
}
ndk::ScopedAStatus StreamOutUsb::setHwVolume(const std::vector<float>& in_channelVolumes) {
- for (const auto& device : mConnectedDevices) {
- if (device.address.getTag() != AudioDeviceAddress::alsa) {
- LOG(DEBUG) << __func__ << ": skip as the device address is not alsa";
- continue;
- }
- const int card = device.address.get<AudioDeviceAddress::alsa>()[0];
- if (auto result =
- usb::UsbAlsaMixerControl::getInstance().setVolumes(card, in_channelVolumes);
- !result.isOk()) {
- LOG(ERROR) << __func__ << ": failed to set volume for device, card=" << card;
- return result;
+ auto currentVolumes = mHwVolumes;
+ RETURN_STATUS_IF_ERROR(setHwVolumeImpl(in_channelVolumes));
+ // Avoid using mConnectedDeviceProfiles because it requires a lock.
+ for (const auto& device : getConnectedDevices()) {
+ if (auto deviceProfile = alsa::getDeviceProfile(device, mIsInput);
+ deviceProfile.has_value()) {
+ if (auto result = usb::UsbAlsaMixerControl::getInstance().setVolumes(
+ deviceProfile->card, in_channelVolumes);
+ !result.isOk()) {
+ LOG(ERROR) << __func__
+ << ": failed to set volume for device address=" << *deviceProfile;
+ mHwVolumes = currentVolumes;
+ return result;
+ }
}
}
- mHwVolumes = in_channelVolumes;
return ndk::ScopedAStatus::ok();
}
diff --git a/audio/aidl/default/usb/UsbAlsaMixerControl.cpp b/audio/aidl/default/usb/UsbAlsaMixerControl.cpp
index b5337d1..0a49446 100644
--- a/audio/aidl/default/usb/UsbAlsaMixerControl.cpp
+++ b/audio/aidl/default/usb/UsbAlsaMixerControl.cpp
@@ -17,151 +17,12 @@
#define LOG_TAG "AHAL_UsbAlsaMixerControl"
#include <android-base/logging.h>
-#include <cmath>
-#include <string>
-#include <vector>
-
#include <android/binder_status.h>
#include "UsbAlsaMixerControl.h"
namespace aidl::android::hardware::audio::core::usb {
-//-----------------------------------------------------------------------------
-
-MixerControl::MixerControl(struct mixer_ctl* ctl)
- : mCtl(ctl),
- mNumValues(mixer_ctl_get_num_values(ctl)),
- mMinValue(mixer_ctl_get_range_min(ctl)),
- mMaxValue(mixer_ctl_get_range_max(ctl)) {}
-
-unsigned int MixerControl::getNumValues() const {
- return mNumValues;
-}
-
-int MixerControl::getMaxValue() const {
- return mMaxValue;
-}
-
-int MixerControl::getMinValue() const {
- return mMinValue;
-}
-
-int MixerControl::setArray(const void* array, size_t count) {
- const std::lock_guard guard(mLock);
- return mixer_ctl_set_array(mCtl, array, count);
-}
-
-//-----------------------------------------------------------------------------
-
-// static
-const std::map<AlsaMixer::Control, std::vector<AlsaMixer::ControlNamesAndExpectedCtlType>>
- AlsaMixer::kPossibleControls = {
- {AlsaMixer::MASTER_SWITCH, {{"Master Playback Switch", MIXER_CTL_TYPE_BOOL}}},
- {AlsaMixer::MASTER_VOLUME, {{"Master Playback Volume", MIXER_CTL_TYPE_INT}}},
- {AlsaMixer::HW_VOLUME,
- {{"Headphone Playback Volume", MIXER_CTL_TYPE_INT},
- {"Headset Playback Volume", MIXER_CTL_TYPE_INT},
- {"PCM Playback Volume", MIXER_CTL_TYPE_INT}}}};
-
-// static
-std::map<AlsaMixer::Control, std::shared_ptr<MixerControl>> AlsaMixer::initializeMixerControls(
- struct mixer* mixer) {
- std::map<AlsaMixer::Control, std::shared_ptr<MixerControl>> mixerControls;
- std::string mixerCtlNames;
- for (const auto& [control, possibleCtls] : kPossibleControls) {
- for (const auto& [ctlName, expectedCtlType] : possibleCtls) {
- struct mixer_ctl* ctl = mixer_get_ctl_by_name(mixer, ctlName.c_str());
- if (ctl != nullptr && mixer_ctl_get_type(ctl) == expectedCtlType) {
- mixerControls.emplace(control, std::make_unique<MixerControl>(ctl));
- if (!mixerCtlNames.empty()) {
- mixerCtlNames += ",";
- }
- mixerCtlNames += ctlName;
- break;
- }
- }
- }
- LOG(DEBUG) << __func__ << ": available mixer control names=[" << mixerCtlNames << "]";
- return mixerControls;
-}
-
-AlsaMixer::AlsaMixer(struct mixer* mixer)
- : mMixer(mixer), mMixerControls(initializeMixerControls(mMixer)) {}
-
-AlsaMixer::~AlsaMixer() {
- mixer_close(mMixer);
-}
-
-namespace {
-
-int volumeFloatToInteger(float fValue, int maxValue, int minValue) {
- return minValue + std::ceil((maxValue - minValue) * fValue);
-}
-
-float volumeIntegerToFloat(int iValue, int maxValue, int minValue) {
- if (iValue > maxValue) {
- return 1.0f;
- }
- if (iValue < minValue) {
- return 0.0f;
- }
- return static_cast<float>(iValue - minValue) / (maxValue - minValue);
-}
-
-} // namespace
-
-ndk::ScopedAStatus AlsaMixer::setMasterMute(bool muted) {
- auto it = mMixerControls.find(AlsaMixer::MASTER_SWITCH);
- if (it == mMixerControls.end()) {
- return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
- }
- const int numValues = it->second->getNumValues();
- std::vector<int> values(numValues, muted ? 0 : 1);
- if (int err = it->second->setArray(values.data(), numValues); err != 0) {
- LOG(ERROR) << __func__ << ": failed to set master mute, err=" << err;
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
- }
- return ndk::ScopedAStatus::ok();
-}
-
-ndk::ScopedAStatus AlsaMixer::setMasterVolume(float volume) {
- auto it = mMixerControls.find(AlsaMixer::MASTER_VOLUME);
- if (it == mMixerControls.end()) {
- return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
- }
- const int numValues = it->second->getNumValues();
- std::vector<int> values(numValues, volumeFloatToInteger(volume, it->second->getMaxValue(),
- it->second->getMinValue()));
- if (int err = it->second->setArray(values.data(), numValues); err != 0) {
- LOG(ERROR) << __func__ << ": failed to set master volume, err=" << err;
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
- }
- return ndk::ScopedAStatus::ok();
-}
-
-ndk::ScopedAStatus AlsaMixer::setVolumes(std::vector<float> volumes) {
- auto it = mMixerControls.find(AlsaMixer::HW_VOLUME);
- if (it == mMixerControls.end()) {
- return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
- }
- const int numValues = it->second->getNumValues();
- const int maxValue = it->second->getMaxValue();
- const int minValue = it->second->getMinValue();
- std::vector<int> values;
- size_t i = 0;
- for (; i < numValues && i < values.size(); ++i) {
- values.emplace_back(volumeFloatToInteger(volumes[i], maxValue, minValue));
- }
- if (int err = it->second->setArray(values.data(), values.size()); err != 0) {
- LOG(ERROR) << __func__ << ": failed to set volume, err=" << err;
- return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
- }
- return ndk::ScopedAStatus::ok();
-}
-
-//-----------------------------------------------------------------------------
-
// static
UsbAlsaMixerControl& UsbAlsaMixerControl::getInstance() {
static UsbAlsaMixerControl gInstance;
@@ -172,12 +33,10 @@
bool connected) {
LOG(DEBUG) << __func__ << ": card=" << card << ", connected=" << connected;
if (connected) {
- struct mixer* mixer = mixer_open(card);
- if (mixer == nullptr) {
- PLOG(ERROR) << __func__ << ": failed to open mixer for card=" << card;
+ auto alsaMixer = std::make_shared<alsa::Mixer>(card);
+ if (!alsaMixer->isValid()) {
return;
}
- auto alsaMixer = std::make_shared<AlsaMixer>(mixer);
alsaMixer->setMasterMute(masterMuted);
alsaMixer->setMasterVolume(masterVolume);
const std::lock_guard guard(mLock);
@@ -216,7 +75,7 @@
return ndk::ScopedAStatus::ok();
}
-ndk::ScopedAStatus UsbAlsaMixerControl::setVolumes(int card, std::vector<float> volumes) {
+ndk::ScopedAStatus UsbAlsaMixerControl::setVolumes(int card, const std::vector<float>& volumes) {
auto alsaMixer = getAlsaMixer(card);
if (alsaMixer == nullptr) {
LOG(ERROR) << __func__ << ": no mixer control found for card=" << card;
@@ -225,13 +84,13 @@
return alsaMixer->setVolumes(volumes);
}
-std::shared_ptr<AlsaMixer> UsbAlsaMixerControl::getAlsaMixer(int card) {
+std::shared_ptr<alsa::Mixer> UsbAlsaMixerControl::getAlsaMixer(int card) {
const std::lock_guard guard(mLock);
const auto it = mMixerControls.find(card);
return it == mMixerControls.end() ? nullptr : it->second;
}
-std::map<int, std::shared_ptr<AlsaMixer>> UsbAlsaMixerControl::getAlsaMixers() {
+std::map<int, std::shared_ptr<alsa::Mixer>> UsbAlsaMixerControl::getAlsaMixers() {
const std::lock_guard guard(mLock);
return mMixerControls;
}
diff --git a/audio/aidl/default/usb/UsbAlsaMixerControl.h b/audio/aidl/default/usb/UsbAlsaMixerControl.h
index cbcddd8..c3265f8 100644
--- a/audio/aidl/default/usb/UsbAlsaMixerControl.h
+++ b/audio/aidl/default/usb/UsbAlsaMixerControl.h
@@ -19,67 +19,15 @@
#include <map>
#include <memory>
#include <mutex>
-#include <optional>
-#include <string>
#include <vector>
#include <android-base/thread_annotations.h>
#include <android/binder_auto_utils.h>
-extern "C" {
-#include <tinyalsa/mixer.h>
-}
+#include "alsa/Mixer.h"
namespace aidl::android::hardware::audio::core::usb {
-class MixerControl {
- public:
- explicit MixerControl(struct mixer_ctl* ctl);
-
- unsigned int getNumValues() const;
- int getMaxValue() const;
- int getMinValue() const;
- int setArray(const void* array, size_t count);
-
- private:
- std::mutex mLock;
- // The mixer_ctl object is owned by ALSA and will be released when the mixer is closed.
- struct mixer_ctl* mCtl GUARDED_BY(mLock);
- const unsigned int mNumValues;
- const int mMinValue;
- const int mMaxValue;
-};
-
-class AlsaMixer {
- public:
- explicit AlsaMixer(struct mixer* mixer);
-
- ~AlsaMixer();
-
- bool isValid() const { return mMixer != nullptr; }
-
- ndk::ScopedAStatus setMasterMute(bool muted);
- ndk::ScopedAStatus setMasterVolume(float volume);
- ndk::ScopedAStatus setVolumes(std::vector<float> volumes);
-
- private:
- enum Control {
- MASTER_SWITCH,
- MASTER_VOLUME,
- HW_VOLUME,
- };
- using ControlNamesAndExpectedCtlType = std::pair<std::string, enum mixer_ctl_type>;
- static const std::map<Control, std::vector<ControlNamesAndExpectedCtlType>> kPossibleControls;
- static std::map<Control, std::shared_ptr<MixerControl>> initializeMixerControls(
- struct mixer* mixer);
-
- // The mixer object is owned by ALSA and will be released when the mixer is closed.
- struct mixer* mMixer;
- // `mMixerControls` will only be initialized in constructor. After that, it wil only be
- // read but not be modified.
- const std::map<Control, std::shared_ptr<MixerControl>> mMixerControls;
-};
-
class UsbAlsaMixerControl {
public:
static UsbAlsaMixerControl& getInstance();
@@ -91,16 +39,16 @@
ndk::ScopedAStatus setMasterMute(bool muted);
ndk::ScopedAStatus setMasterVolume(float volume);
// The volume settings can be different on sound cards. It is controlled by streams.
- ndk::ScopedAStatus setVolumes(int card, std::vector<float> volumes);
+ ndk::ScopedAStatus setVolumes(int card, const std::vector<float>& volumes);
private:
- std::shared_ptr<AlsaMixer> getAlsaMixer(int card);
- std::map<int, std::shared_ptr<AlsaMixer>> getAlsaMixers();
+ std::shared_ptr<alsa::Mixer> getAlsaMixer(int card);
+ std::map<int, std::shared_ptr<alsa::Mixer>> getAlsaMixers();
std::mutex mLock;
// A map whose key is the card number and value is a shared pointer to corresponding
// AlsaMixer object.
- std::map<int, std::shared_ptr<AlsaMixer>> mMixerControls GUARDED_BY(mLock);
+ std::map<int, std::shared_ptr<alsa::Mixer>> mMixerControls GUARDED_BY(mLock);
};
} // namespace aidl::android::hardware::audio::core::usb
diff --git a/audio/aidl/default/usb/UsbAlsaUtils.cpp b/audio/aidl/default/usb/UsbAlsaUtils.cpp
deleted file mode 100644
index 74d9c28..0000000
--- a/audio/aidl/default/usb/UsbAlsaUtils.cpp
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2023 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 <map>
-#include <set>
-
-#include <Utils.h>
-#include <aidl/android/media/audio/common/AudioFormatType.h>
-#include <aidl/android/media/audio/common/PcmType.h>
-
-#include "UsbAlsaUtils.h"
-#include "core-impl/utils.h"
-
-using aidl::android::hardware::audio::common::getChannelCount;
-using aidl::android::media::audio::common::AudioChannelLayout;
-using aidl::android::media::audio::common::AudioFormatDescription;
-using aidl::android::media::audio::common::AudioFormatType;
-using aidl::android::media::audio::common::PcmType;
-
-namespace aidl::android::hardware::audio::core::usb {
-
-namespace {
-
-using AudioChannelCountToMaskMap = std::map<unsigned int, AudioChannelLayout>;
-using AudioFormatDescToPcmFormatMap = std::map<AudioFormatDescription, enum pcm_format>;
-using PcmFormatToAudioFormatDescMap = std::map<enum pcm_format, AudioFormatDescription>;
-
-static const AudioChannelLayout INVALID_CHANNEL_LAYOUT =
- AudioChannelLayout::make<AudioChannelLayout::Tag::invalid>(0);
-
-#define DEFINE_CHANNEL_LAYOUT_MASK(n) \
- AudioChannelLayout::make<AudioChannelLayout::Tag::layoutMask>(AudioChannelLayout::LAYOUT_##n)
-
-static const std::set<AudioChannelLayout> SUPPORTED_OUT_CHANNEL_LAYOUTS = {
- DEFINE_CHANNEL_LAYOUT_MASK(MONO), DEFINE_CHANNEL_LAYOUT_MASK(STEREO),
- DEFINE_CHANNEL_LAYOUT_MASK(2POINT1), DEFINE_CHANNEL_LAYOUT_MASK(QUAD),
- DEFINE_CHANNEL_LAYOUT_MASK(PENTA), DEFINE_CHANNEL_LAYOUT_MASK(5POINT1),
- DEFINE_CHANNEL_LAYOUT_MASK(6POINT1), DEFINE_CHANNEL_LAYOUT_MASK(7POINT1),
- DEFINE_CHANNEL_LAYOUT_MASK(7POINT1POINT4), DEFINE_CHANNEL_LAYOUT_MASK(22POINT2),
-};
-
-static const std::set<AudioChannelLayout> SUPPORTED_IN_CHANNEL_LAYOUTS = {
- DEFINE_CHANNEL_LAYOUT_MASK(MONO),
- DEFINE_CHANNEL_LAYOUT_MASK(STEREO),
-};
-
-#define DEFINE_CHANNEL_INDEX_MASK(n) \
- AudioChannelLayout::make<AudioChannelLayout::Tag::indexMask>(AudioChannelLayout::INDEX_MASK_##n)
-
-static const std::set<AudioChannelLayout> SUPPORTED_INDEX_CHANNEL_LAYOUTS = {
- DEFINE_CHANNEL_INDEX_MASK(1), DEFINE_CHANNEL_INDEX_MASK(2), DEFINE_CHANNEL_INDEX_MASK(3),
- DEFINE_CHANNEL_INDEX_MASK(4), DEFINE_CHANNEL_INDEX_MASK(5), DEFINE_CHANNEL_INDEX_MASK(6),
- DEFINE_CHANNEL_INDEX_MASK(7), DEFINE_CHANNEL_INDEX_MASK(8), DEFINE_CHANNEL_INDEX_MASK(9),
- DEFINE_CHANNEL_INDEX_MASK(10), DEFINE_CHANNEL_INDEX_MASK(11), DEFINE_CHANNEL_INDEX_MASK(12),
- DEFINE_CHANNEL_INDEX_MASK(13), DEFINE_CHANNEL_INDEX_MASK(14), DEFINE_CHANNEL_INDEX_MASK(15),
- DEFINE_CHANNEL_INDEX_MASK(16), DEFINE_CHANNEL_INDEX_MASK(17), DEFINE_CHANNEL_INDEX_MASK(18),
- DEFINE_CHANNEL_INDEX_MASK(19), DEFINE_CHANNEL_INDEX_MASK(20), DEFINE_CHANNEL_INDEX_MASK(21),
- DEFINE_CHANNEL_INDEX_MASK(22), DEFINE_CHANNEL_INDEX_MASK(23), DEFINE_CHANNEL_INDEX_MASK(24),
-};
-
-static AudioChannelCountToMaskMap make_ChannelCountToMaskMap(
- const std::set<AudioChannelLayout>& channelMasks) {
- AudioChannelCountToMaskMap channelMaskToCountMap;
- for (const auto& channelMask : channelMasks) {
- channelMaskToCountMap.emplace(getChannelCount(channelMask), channelMask);
- }
- return channelMaskToCountMap;
-}
-
-const AudioChannelCountToMaskMap& getSupportedChannelOutLayoutMap() {
- static const AudioChannelCountToMaskMap outLayouts =
- make_ChannelCountToMaskMap(SUPPORTED_OUT_CHANNEL_LAYOUTS);
- return outLayouts;
-}
-
-const AudioChannelCountToMaskMap& getSupportedChannelInLayoutMap() {
- static const AudioChannelCountToMaskMap inLayouts =
- make_ChannelCountToMaskMap(SUPPORTED_IN_CHANNEL_LAYOUTS);
- return inLayouts;
-}
-
-const AudioChannelCountToMaskMap& getSupportedChannelIndexLayoutMap() {
- static const AudioChannelCountToMaskMap indexLayouts =
- make_ChannelCountToMaskMap(SUPPORTED_INDEX_CHANNEL_LAYOUTS);
- return indexLayouts;
-}
-
-AudioFormatDescription make_AudioFormatDescription(AudioFormatType type) {
- AudioFormatDescription result;
- result.type = type;
- return result;
-}
-
-AudioFormatDescription make_AudioFormatDescription(PcmType pcm) {
- auto result = make_AudioFormatDescription(AudioFormatType::PCM);
- result.pcm = pcm;
- return result;
-}
-
-const AudioFormatDescToPcmFormatMap& getAudioFormatDescriptorToPcmFormatMap() {
- static const AudioFormatDescToPcmFormatMap formatDescToPcmFormatMap = {
- {make_AudioFormatDescription(PcmType::UINT_8_BIT), PCM_FORMAT_S8},
- {make_AudioFormatDescription(PcmType::INT_16_BIT), PCM_FORMAT_S16_LE},
- {make_AudioFormatDescription(PcmType::FIXED_Q_8_24), PCM_FORMAT_S24_LE},
- {make_AudioFormatDescription(PcmType::INT_24_BIT), PCM_FORMAT_S24_3LE},
- {make_AudioFormatDescription(PcmType::INT_32_BIT), PCM_FORMAT_S32_LE},
- {make_AudioFormatDescription(PcmType::FLOAT_32_BIT), PCM_FORMAT_FLOAT_LE},
- };
- return formatDescToPcmFormatMap;
-}
-
-static PcmFormatToAudioFormatDescMap make_PcmFormatToAudioFormatDescMap(
- const AudioFormatDescToPcmFormatMap& formatDescToPcmFormatMap) {
- PcmFormatToAudioFormatDescMap result;
- for (const auto& formatPair : formatDescToPcmFormatMap) {
- result.emplace(formatPair.second, formatPair.first);
- }
- return result;
-}
-
-const PcmFormatToAudioFormatDescMap& getPcmFormatToAudioFormatDescMap() {
- static const PcmFormatToAudioFormatDescMap pcmFormatToFormatDescMap =
- make_PcmFormatToAudioFormatDescMap(getAudioFormatDescriptorToPcmFormatMap());
- return pcmFormatToFormatDescMap;
-}
-
-} // namespace
-
-AudioChannelLayout getChannelLayoutMaskFromChannelCount(unsigned int channelCount, int isInput) {
- return findValueOrDefault(
- isInput ? getSupportedChannelInLayoutMap() : getSupportedChannelOutLayoutMap(),
- channelCount, INVALID_CHANNEL_LAYOUT);
-}
-
-AudioChannelLayout getChannelIndexMaskFromChannelCount(unsigned int channelCount) {
- return findValueOrDefault(getSupportedChannelIndexLayoutMap(), channelCount,
- INVALID_CHANNEL_LAYOUT);
-}
-
-unsigned int getChannelCountFromChannelMask(const AudioChannelLayout& channelMask, bool isInput) {
- switch (channelMask.getTag()) {
- case AudioChannelLayout::Tag::layoutMask: {
- return findKeyOrDefault(
- isInput ? getSupportedChannelInLayoutMap() : getSupportedChannelOutLayoutMap(),
- (unsigned int)getChannelCount(channelMask), 0u /*defaultValue*/);
- }
- case AudioChannelLayout::Tag::indexMask: {
- return findKeyOrDefault(getSupportedChannelIndexLayoutMap(),
- (unsigned int)getChannelCount(channelMask),
- 0u /*defaultValue*/);
- }
- case AudioChannelLayout::Tag::none:
- case AudioChannelLayout::Tag::invalid:
- case AudioChannelLayout::Tag::voiceMask:
- default:
- return 0;
- }
-}
-
-AudioFormatDescription legacy2aidl_pcm_format_AudioFormatDescription(enum pcm_format legacy) {
- return findValueOrDefault(getPcmFormatToAudioFormatDescMap(), legacy, AudioFormatDescription());
-}
-
-pcm_format aidl2legacy_AudioFormatDescription_pcm_format(const AudioFormatDescription& aidl) {
- return findValueOrDefault(getAudioFormatDescriptorToPcmFormatMap(), aidl, PCM_FORMAT_INVALID);
-}
-
-} // namespace aidl::android::hardware::audio::core::usb
diff --git a/audio/aidl/default/usb/UsbAlsaUtils.h b/audio/aidl/default/usb/UsbAlsaUtils.h
deleted file mode 100644
index 2d2f0f4..0000000
--- a/audio/aidl/default/usb/UsbAlsaUtils.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2023 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 <aidl/android/media/audio/common/AudioChannelLayout.h>
-#include <aidl/android/media/audio/common/AudioFormatDescription.h>
-
-extern "C" {
-#include <tinyalsa/pcm.h>
-}
-
-namespace aidl::android::hardware::audio::core::usb {
-
-::aidl::android::media::audio::common::AudioChannelLayout getChannelLayoutMaskFromChannelCount(
- unsigned int channelCount, int isInput);
-::aidl::android::media::audio::common::AudioChannelLayout getChannelIndexMaskFromChannelCount(
- unsigned int channelCount);
-unsigned int getChannelCountFromChannelMask(
- const ::aidl::android::media::audio::common::AudioChannelLayout& channelMask, bool isInput);
-::aidl::android::media::audio::common::AudioFormatDescription
-legacy2aidl_pcm_format_AudioFormatDescription(enum pcm_format legacy);
-pcm_format aidl2legacy_AudioFormatDescription_pcm_format(
- const ::aidl::android::media::audio::common::AudioFormatDescription& aidl);
-
-} // namespace aidl::android::hardware::audio::core::usb
\ No newline at end of file
diff --git a/audio/aidl/vts/Android.bp b/audio/aidl/vts/Android.bp
index 852255d..f7cf4ce 100644
--- a/audio/aidl/vts/Android.bp
+++ b/audio/aidl/vts/Android.bp
@@ -55,6 +55,7 @@
"VtsHalAudioCoreConfigTargetTest.cpp",
"VtsHalAudioCoreModuleTargetTest.cpp",
],
+ test_config: "VtsHalAudioCoreTargetTest.xml",
}
cc_test {
diff --git a/audio/aidl/vts/EffectHelper.h b/audio/aidl/vts/EffectHelper.h
index 4e84f6b..2c8edf2 100644
--- a/audio/aidl/vts/EffectHelper.h
+++ b/audio/aidl/vts/EffectHelper.h
@@ -30,6 +30,7 @@
#include <android/binder_auto_utils.h>
#include <fmq/AidlMessageQueue.h>
#include <gtest/gtest.h>
+#include <system/audio_aidl_utils.h>
#include <system/audio_effects/aidl_effects_utils.h>
#include <system/audio_effects/effect_uuid.h>
@@ -51,6 +52,7 @@
using aidl::android::media::audio::common::AudioFormatType;
using aidl::android::media::audio::common::AudioUuid;
using aidl::android::media::audio::common::PcmType;
+using ::android::audio::utils::toString;
using ::android::hardware::EventFlag;
const AudioFormatDescription kDefaultFormatDescription = {
@@ -63,6 +65,12 @@
::aidl::android::hardware::common::fmq::SynchronizedReadWrite>
DataMQ;
+static inline std::string getPrefix(Descriptor& descriptor) {
+ std::string prefix = "Implementor_" + descriptor.common.implementor + "_name_" +
+ descriptor.common.name + "_UUID_" + toString(descriptor.common.id.uuid);
+ return prefix;
+}
+
class EffectHelper {
public:
static void create(std::shared_ptr<IFactory> factory, std::shared_ptr<IEffect>& effect,
@@ -71,7 +79,7 @@
auto& id = desc.common.id;
ASSERT_STATUS(status, factory->createEffect(id.uuid, &effect));
if (status == EX_NONE) {
- ASSERT_NE(effect, nullptr) << id.uuid.toString();
+ ASSERT_NE(effect, nullptr) << toString(id.uuid);
}
}
@@ -242,11 +250,11 @@
maxLimit = std::numeric_limits<S>::max();
if (s.size()) {
const auto min = *s.begin(), max = *s.rbegin();
- s.insert(min + (max - min) / 2);
- if (min != minLimit) {
+ s.insert((min & max) + ((min ^ max) >> 1));
+ if (min > minLimit + 1) {
s.insert(min - 1);
}
- if (max != maxLimit) {
+ if (max < maxLimit - 1) {
s.insert(max + 1);
}
}
diff --git a/audio/aidl/vts/ModuleConfig.cpp b/audio/aidl/vts/ModuleConfig.cpp
index 8c448a8..8fdb155 100644
--- a/audio/aidl/vts/ModuleConfig.cpp
+++ b/audio/aidl/vts/ModuleConfig.cpp
@@ -30,6 +30,7 @@
using aidl::android::hardware::audio::common::isBitPositionFlagSet;
using aidl::android::hardware::audio::core::IModule;
using aidl::android::media::audio::common::AudioChannelLayout;
+using aidl::android::media::audio::common::AudioDeviceDescription;
using aidl::android::media::audio::common::AudioDeviceType;
using aidl::android::media::audio::common::AudioEncapsulationMode;
using aidl::android::media::audio::common::AudioFormatDescription;
@@ -65,15 +66,36 @@
return {};
}
+std::vector<aidl::android::media::audio::common::AudioPort>
+ModuleConfig::getAudioPortsForDeviceTypes(const std::vector<AudioDeviceType>& deviceTypes,
+ const std::string& connection) {
+ return getAudioPortsForDeviceTypes(mPorts, deviceTypes, connection);
+}
+
// static
std::vector<aidl::android::media::audio::common::AudioPort> ModuleConfig::getBuiltInMicPorts(
const std::vector<aidl::android::media::audio::common::AudioPort>& ports) {
+ return getAudioPortsForDeviceTypes(
+ ports, std::vector<AudioDeviceType>{AudioDeviceType::IN_MICROPHONE,
+ AudioDeviceType::IN_MICROPHONE_BACK});
+}
+
+std::vector<aidl::android::media::audio::common::AudioPort>
+ModuleConfig::getAudioPortsForDeviceTypes(
+ const std::vector<aidl::android::media::audio::common::AudioPort>& ports,
+ const std::vector<AudioDeviceType>& deviceTypes, const std::string& connection) {
std::vector<AudioPort> result;
- std::copy_if(ports.begin(), ports.end(), std::back_inserter(result), [](const auto& port) {
- const auto type = port.ext.template get<AudioPortExt::Tag::device>().device.type;
- return type.connection.empty() && (type.type == AudioDeviceType::IN_MICROPHONE ||
- type.type == AudioDeviceType::IN_MICROPHONE_BACK);
- });
+ for (const auto& port : ports) {
+ if (port.ext.getTag() != AudioPortExt::Tag::device) continue;
+ const auto type = port.ext.get<AudioPortExt::Tag::device>().device.type;
+ if (type.connection == connection) {
+ for (auto deviceType : deviceTypes) {
+ if (type.type == deviceType) {
+ result.push_back(port);
+ }
+ }
+ }
+ }
return result;
}
@@ -96,7 +118,10 @@
} else {
mAttachedSinkDevicePorts.insert(port.id);
}
- } else if (port.profiles.empty()) {
+ } else if (devicePort.device.type.connection != AudioDeviceDescription::CONNECTION_VIRTUAL
+ // The "virtual" connection is used for remote submix which is a dynamic
+ // device but it can be connected and used w/o external hardware.
+ && port.profiles.empty()) {
mExternalDevicePorts.insert(port.id);
}
}
@@ -115,6 +140,31 @@
return result;
}
+std::vector<AudioPort> ModuleConfig::getConnectedExternalDevicePorts() const {
+ std::vector<AudioPort> result;
+ std::copy_if(mPorts.begin(), mPorts.end(), std::back_inserter(result), [&](const auto& port) {
+ return mConnectedExternalSinkDevicePorts.count(port.id) != 0 ||
+ mConnectedExternalSourceDevicePorts.count(port.id) != 0;
+ });
+ return result;
+}
+
+std::set<int32_t> ModuleConfig::getConnectedSinkDevicePorts() const {
+ std::set<int32_t> result;
+ result.insert(mAttachedSinkDevicePorts.begin(), mAttachedSinkDevicePorts.end());
+ result.insert(mConnectedExternalSinkDevicePorts.begin(),
+ mConnectedExternalSinkDevicePorts.end());
+ return result;
+}
+
+std::set<int32_t> ModuleConfig::getConnectedSourceDevicePorts() const {
+ std::set<int32_t> result;
+ result.insert(mAttachedSourceDevicePorts.begin(), mAttachedSourceDevicePorts.end());
+ result.insert(mConnectedExternalSourceDevicePorts.begin(),
+ mConnectedExternalSourceDevicePorts.end());
+ return result;
+}
+
std::vector<AudioPort> ModuleConfig::getExternalDevicePorts() const {
std::vector<AudioPort> result;
std::copy_if(mPorts.begin(), mPorts.end(), std::back_inserter(result),
@@ -122,76 +172,77 @@
return result;
}
-std::vector<AudioPort> ModuleConfig::getInputMixPorts(bool attachedOnly) const {
+std::vector<AudioPort> ModuleConfig::getInputMixPorts(bool connectedOnly) const {
std::vector<AudioPort> result;
std::copy_if(mPorts.begin(), mPorts.end(), std::back_inserter(result), [&](const auto& port) {
return port.ext.getTag() == AudioPortExt::Tag::mix &&
port.flags.getTag() == AudioIoFlags::Tag::input &&
- (!attachedOnly || !getAttachedSourceDevicesPortsForMixPort(port).empty());
+ (!connectedOnly || !getConnectedSourceDevicesPortsForMixPort(port).empty());
});
return result;
}
-std::vector<AudioPort> ModuleConfig::getOutputMixPorts(bool attachedOnly) const {
+std::vector<AudioPort> ModuleConfig::getOutputMixPorts(bool connectedOnly) const {
std::vector<AudioPort> result;
std::copy_if(mPorts.begin(), mPorts.end(), std::back_inserter(result), [&](const auto& port) {
return port.ext.getTag() == AudioPortExt::Tag::mix &&
port.flags.getTag() == AudioIoFlags::Tag::output &&
- (!attachedOnly || !getAttachedSinkDevicesPortsForMixPort(port).empty());
+ (!connectedOnly || !getConnectedSinkDevicesPortsForMixPort(port).empty());
});
return result;
}
-std::vector<AudioPort> ModuleConfig::getNonBlockingMixPorts(bool attachedOnly,
+std::vector<AudioPort> ModuleConfig::getNonBlockingMixPorts(bool connectedOnly,
bool singlePort) const {
- return findMixPorts(false /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+ return findMixPorts(false /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
AudioOutputFlags::NON_BLOCKING);
});
}
-std::vector<AudioPort> ModuleConfig::getOffloadMixPorts(bool attachedOnly, bool singlePort) const {
- return findMixPorts(false /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+std::vector<AudioPort> ModuleConfig::getOffloadMixPorts(bool connectedOnly, bool singlePort) const {
+ return findMixPorts(false /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
AudioOutputFlags::COMPRESS_OFFLOAD);
});
}
-std::vector<AudioPort> ModuleConfig::getPrimaryMixPorts(bool attachedOnly, bool singlePort) const {
- return findMixPorts(false /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+std::vector<AudioPort> ModuleConfig::getPrimaryMixPorts(bool connectedOnly, bool singlePort) const {
+ return findMixPorts(false /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
AudioOutputFlags::PRIMARY);
});
}
-std::vector<AudioPort> ModuleConfig::getMmapOutMixPorts(bool attachedOnly, bool singlePort) const {
- return findMixPorts(false /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+std::vector<AudioPort> ModuleConfig::getMmapOutMixPorts(bool connectedOnly, bool singlePort) const {
+ return findMixPorts(false /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
AudioOutputFlags::MMAP_NOIRQ);
});
}
-std::vector<AudioPort> ModuleConfig::getMmapInMixPorts(bool attachedOnly, bool singlePort) const {
- return findMixPorts(true /*isInput*/, attachedOnly, singlePort, [&](const AudioPort& port) {
+std::vector<AudioPort> ModuleConfig::getMmapInMixPorts(bool connectedOnly, bool singlePort) const {
+ return findMixPorts(true /*isInput*/, connectedOnly, singlePort, [&](const AudioPort& port) {
return isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
AudioInputFlags::MMAP_NOIRQ);
});
}
-std::vector<AudioPort> ModuleConfig::getAttachedDevicesPortsForMixPort(
+std::vector<AudioPort> ModuleConfig::getConnectedDevicesPortsForMixPort(
bool isInput, const AudioPortConfig& mixPortConfig) const {
const auto mixPortIt = findById<AudioPort>(mPorts, mixPortConfig.portId);
if (mixPortIt != mPorts.end()) {
- return getAttachedDevicesPortsForMixPort(isInput, *mixPortIt);
+ return getConnectedDevicesPortsForMixPort(isInput, *mixPortIt);
}
return {};
}
-std::vector<AudioPort> ModuleConfig::getAttachedSinkDevicesPortsForMixPort(
+std::vector<AudioPort> ModuleConfig::getConnectedSinkDevicesPortsForMixPort(
const AudioPort& mixPort) const {
std::vector<AudioPort> result;
+ std::set<int32_t> connectedSinkDevicePorts = getConnectedSinkDevicePorts();
for (const auto& route : mRoutes) {
- if (mAttachedSinkDevicePorts.count(route.sinkPortId) != 0 &&
+ if ((connectedSinkDevicePorts.count(route.sinkPortId) != 0) &&
std::find(route.sourcePortIds.begin(), route.sourcePortIds.end(), mixPort.id) !=
route.sourcePortIds.end()) {
const auto devicePortIt = findById<AudioPort>(mPorts, route.sinkPortId);
@@ -201,13 +252,14 @@
return result;
}
-std::vector<AudioPort> ModuleConfig::getAttachedSourceDevicesPortsForMixPort(
+std::vector<AudioPort> ModuleConfig::getConnectedSourceDevicesPortsForMixPort(
const AudioPort& mixPort) const {
std::vector<AudioPort> result;
+ std::set<int32_t> connectedSourceDevicePorts = getConnectedSourceDevicePorts();
for (const auto& route : mRoutes) {
if (route.sinkPortId == mixPort.id) {
for (const auto srcId : route.sourcePortIds) {
- if (mAttachedSourceDevicePorts.count(srcId) != 0) {
+ if (connectedSourceDevicePorts.count(srcId) != 0) {
const auto devicePortIt = findById<AudioPort>(mPorts, srcId);
if (devicePortIt != mPorts.end()) result.push_back(*devicePortIt);
}
@@ -217,9 +269,10 @@
return result;
}
-std::optional<AudioPort> ModuleConfig::getSourceMixPortForAttachedDevice() const {
+std::optional<AudioPort> ModuleConfig::getSourceMixPortForConnectedDevice() const {
+ std::set<int32_t> connectedSinkDevicePorts = getConnectedSinkDevicePorts();
for (const auto& route : mRoutes) {
- if (mAttachedSinkDevicePorts.count(route.sinkPortId) != 0) {
+ if (connectedSinkDevicePorts.count(route.sinkPortId) != 0) {
const auto mixPortIt = findById<AudioPort>(mPorts, route.sourcePortIds[0]);
if (mixPortIt != mPorts.end()) return *mixPortIt;
}
@@ -229,7 +282,7 @@
std::optional<ModuleConfig::SrcSinkPair> ModuleConfig::getNonRoutableSrcSinkPair(
bool isInput) const {
- const auto mixPorts = getMixPorts(isInput, false /*attachedOnly*/);
+ const auto mixPorts = getMixPorts(isInput, false /*connectedOnly*/);
std::set<std::pair<int32_t, int32_t>> allowedRoutes;
for (const auto& route : mRoutes) {
for (const auto srcPortId : route.sourcePortIds) {
@@ -239,7 +292,8 @@
auto make_pair = [isInput](auto& device, auto& mix) {
return isInput ? std::make_pair(device, mix) : std::make_pair(mix, device);
};
- for (const auto portId : isInput ? mAttachedSourceDevicePorts : mAttachedSinkDevicePorts) {
+ for (const auto portId :
+ isInput ? getConnectedSourceDevicePorts() : getConnectedSinkDevicePorts()) {
const auto devicePortIt = findById<AudioPort>(mPorts, portId);
if (devicePortIt == mPorts.end()) continue;
auto devicePortConfig = getSingleConfigForDevicePort(*devicePortIt);
@@ -258,10 +312,11 @@
std::optional<ModuleConfig::SrcSinkPair> ModuleConfig::getRoutableSrcSinkPair(bool isInput) const {
if (isInput) {
+ std::set<int32_t> connectedSourceDevicePorts = getConnectedSourceDevicePorts();
for (const auto& route : mRoutes) {
auto srcPortIdIt = std::find_if(
route.sourcePortIds.begin(), route.sourcePortIds.end(),
- [&](const auto& portId) { return mAttachedSourceDevicePorts.count(portId); });
+ [&](const auto& portId) { return connectedSourceDevicePorts.count(portId); });
if (srcPortIdIt == route.sourcePortIds.end()) continue;
const auto devicePortIt = findById<AudioPort>(mPorts, *srcPortIdIt);
const auto mixPortIt = findById<AudioPort>(mPorts, route.sinkPortId);
@@ -272,8 +327,9 @@
return std::make_pair(devicePortConfig, mixPortConfig.value());
}
} else {
+ std::set<int32_t> connectedSinkDevicePorts = getConnectedSinkDevicePorts();
for (const auto& route : mRoutes) {
- if (mAttachedSinkDevicePorts.count(route.sinkPortId) == 0) continue;
+ if (connectedSinkDevicePorts.count(route.sinkPortId) == 0) continue;
const auto mixPortIt = findById<AudioPort>(mPorts, route.sourcePortIds[0]);
const auto devicePortIt = findById<AudioPort>(mPorts, route.sinkPortId);
if (devicePortIt == mPorts.end() || mixPortIt == mPorts.end()) continue;
@@ -289,11 +345,12 @@
std::vector<ModuleConfig::SrcSinkGroup> ModuleConfig::getRoutableSrcSinkGroups(bool isInput) const {
std::vector<SrcSinkGroup> result;
if (isInput) {
+ std::set<int32_t> connectedSourceDevicePorts = getConnectedSourceDevicePorts();
for (const auto& route : mRoutes) {
std::vector<int32_t> srcPortIds;
std::copy_if(route.sourcePortIds.begin(), route.sourcePortIds.end(),
std::back_inserter(srcPortIds), [&](const auto& portId) {
- return mAttachedSourceDevicePorts.count(portId);
+ return connectedSourceDevicePorts.count(portId);
});
if (srcPortIds.empty()) continue;
const auto mixPortIt = findById<AudioPort>(mPorts, route.sinkPortId);
@@ -313,8 +370,9 @@
}
}
} else {
+ std::set<int32_t> connectedSinkDevicePorts = getConnectedSinkDevicePorts();
for (const auto& route : mRoutes) {
- if (mAttachedSinkDevicePorts.count(route.sinkPortId) == 0) continue;
+ if (connectedSinkDevicePorts.count(route.sinkPortId) == 0) continue;
const auto devicePortIt = findById<AudioPort>(mPorts, route.sinkPortId);
if (devicePortIt == mPorts.end()) continue;
auto devicePortConfig = getSingleConfigForDevicePort(*devicePortIt);
@@ -348,6 +406,8 @@
result.append(android::internal::ToString(mAttachedSourceDevicePorts));
result.append("\nExternal device ports: ");
result.append(android::internal::ToString(mExternalDevicePorts));
+ result.append("\nConnected external device ports: ");
+ result.append(android::internal::ToString(getConnectedExternalDevicePorts()));
result.append("\nRoutes: ");
result.append(android::internal::ToString(mRoutes));
return result;
@@ -380,10 +440,10 @@
}
std::vector<AudioPort> ModuleConfig::findMixPorts(
- bool isInput, bool attachedOnly, bool singlePort,
+ bool isInput, bool connectedOnly, bool singlePort,
const std::function<bool(const AudioPort&)>& pred) const {
std::vector<AudioPort> result;
- const auto mixPorts = getMixPorts(isInput, attachedOnly);
+ const auto mixPorts = getMixPorts(isInput, connectedOnly);
for (auto mixPortIt = mixPorts.begin(); mixPortIt != mixPorts.end();) {
mixPortIt = std::find_if(mixPortIt, mixPorts.end(), pred);
if (mixPortIt == mixPorts.end()) break;
@@ -397,7 +457,7 @@
const std::vector<AudioPort>& ports, bool isInput, bool singleProfile) const {
std::vector<AudioPortConfig> result;
for (const auto& mixPort : ports) {
- if (getAttachedDevicesPortsForMixPort(isInput, mixPort).empty()) {
+ if (getConnectedDevicesPortsForMixPort(isInput, mixPort).empty()) {
continue;
}
for (const auto& profile : mixPort.profiles) {
@@ -439,10 +499,48 @@
return result;
}
+const ndk::ScopedAStatus& ModuleConfig::onExternalDeviceConnected(IModule* module,
+ const AudioPort& port) {
+ // Update ports and routes
+ mStatus = module->getAudioPorts(&mPorts);
+ if (!mStatus.isOk()) return mStatus;
+ mStatus = module->getAudioRoutes(&mRoutes);
+ if (!mStatus.isOk()) return mStatus;
+
+ // Validate port is present in module
+ if (std::find(mPorts.begin(), mPorts.end(), port) == mPorts.end()) {
+ mStatus = ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
+ return mStatus;
+ }
+
+ if (port.flags.getTag() == aidl::android::media::audio::common::AudioIoFlags::Tag::input) {
+ mConnectedExternalSourceDevicePorts.insert(port.id);
+ } else {
+ mConnectedExternalSinkDevicePorts.insert(port.id);
+ }
+ return mStatus;
+}
+
+const ndk::ScopedAStatus& ModuleConfig::onExternalDeviceDisconnected(IModule* module,
+ const AudioPort& port) {
+ // Update ports and routes
+ mStatus = module->getAudioPorts(&mPorts);
+ if (!mStatus.isOk()) return mStatus;
+ mStatus = module->getAudioRoutes(&mRoutes);
+ if (!mStatus.isOk()) return mStatus;
+
+ if (port.flags.getTag() == aidl::android::media::audio::common::AudioIoFlags::Tag::input) {
+ mConnectedExternalSourceDevicePorts.erase(port.id);
+ } else {
+ mConnectedExternalSinkDevicePorts.erase(port.id);
+ }
+ return mStatus;
+}
+
bool ModuleConfig::isMmapSupported() const {
const std::vector<AudioPort> mmapOutMixPorts =
- getMmapOutMixPorts(false /*attachedOnly*/, false /*singlePort*/);
+ getMmapOutMixPorts(false /*connectedOnly*/, false /*singlePort*/);
const std::vector<AudioPort> mmapInMixPorts =
- getMmapInMixPorts(false /*attachedOnly*/, false /*singlePort*/);
+ getMmapInMixPorts(false /*connectedOnly*/, false /*singlePort*/);
return !mmapOutMixPorts.empty() || !mmapInMixPorts.empty();
}
diff --git a/audio/aidl/vts/ModuleConfig.h b/audio/aidl/vts/ModuleConfig.h
index 6a22075..bce1de1 100644
--- a/audio/aidl/vts/ModuleConfig.h
+++ b/audio/aidl/vts/ModuleConfig.h
@@ -37,6 +37,14 @@
static std::optional<aidl::android::media::audio::common::AudioOffloadInfo>
generateOffloadInfoIfNeeded(
const aidl::android::media::audio::common::AudioPortConfig& portConfig);
+
+ std::vector<aidl::android::media::audio::common::AudioPort> getAudioPortsForDeviceTypes(
+ const std::vector<aidl::android::media::audio::common::AudioDeviceType>& deviceTypes,
+ const std::string& connection = "");
+ static std::vector<aidl::android::media::audio::common::AudioPort> getAudioPortsForDeviceTypes(
+ const std::vector<aidl::android::media::audio::common::AudioPort>& ports,
+ const std::vector<aidl::android::media::audio::common::AudioDeviceType>& deviceTypes,
+ const std::string& connection = "");
static std::vector<aidl::android::media::audio::common::AudioPort> getBuiltInMicPorts(
const std::vector<aidl::android::media::audio::common::AudioPort>& ports);
@@ -45,45 +53,55 @@
std::string getError() const { return mStatus.getMessage(); }
std::vector<aidl::android::media::audio::common::AudioPort> getAttachedDevicePorts() const;
+ std::vector<aidl::android::media::audio::common::AudioPort> getConnectedExternalDevicePorts()
+ const;
+ std::set<int32_t> getConnectedSinkDevicePorts() const;
+ std::set<int32_t> getConnectedSourceDevicePorts() const;
std::vector<aidl::android::media::audio::common::AudioPort> getAttachedMicrophonePorts() const {
return getBuiltInMicPorts(getAttachedDevicePorts());
}
std::vector<aidl::android::media::audio::common::AudioPort> getExternalDevicePorts() const;
std::vector<aidl::android::media::audio::common::AudioPort> getInputMixPorts(
- bool attachedOnly) const;
+ bool connectedOnly /*Permanently attached and connected external devices*/) const;
std::vector<aidl::android::media::audio::common::AudioPort> getOutputMixPorts(
- bool attachedOnly) const;
+ bool connectedOnly /*Permanently attached and connected external devices*/) const;
std::vector<aidl::android::media::audio::common::AudioPort> getMixPorts(
- bool isInput, bool attachedOnly) const {
- return isInput ? getInputMixPorts(attachedOnly) : getOutputMixPorts(attachedOnly);
+ bool isInput,
+ bool connectedOnly /*Permanently attached and connected external devices*/) const {
+ return isInput ? getInputMixPorts(connectedOnly) : getOutputMixPorts(connectedOnly);
}
std::vector<aidl::android::media::audio::common::AudioPort> getNonBlockingMixPorts(
- bool attachedOnly, bool singlePort) const;
+ bool connectedOnly /*Permanently attached and connected external devices*/,
+ bool singlePort) const;
std::vector<aidl::android::media::audio::common::AudioPort> getOffloadMixPorts(
- bool attachedOnly, bool singlePort) const;
+ bool connectedOnly /*Permanently attached and connected external devices*/,
+ bool singlePort) const;
std::vector<aidl::android::media::audio::common::AudioPort> getPrimaryMixPorts(
- bool attachedOnly, bool singlePort) const;
+ bool connectedOnly /*Permanently attached and connected external devices*/,
+ bool singlePort) const;
std::vector<aidl::android::media::audio::common::AudioPort> getMmapOutMixPorts(
- bool attachedOnly, bool singlePort) const;
+ bool connectedOnly /*Permanently attached and connected external devices*/,
+ bool singlePort) const;
std::vector<aidl::android::media::audio::common::AudioPort> getMmapInMixPorts(
- bool attachedOnly, bool singlePort) const;
+ bool connectedOnly /*Permanently attached and connected external devices*/,
+ bool singlePort) const;
- std::vector<aidl::android::media::audio::common::AudioPort> getAttachedDevicesPortsForMixPort(
+ std::vector<aidl::android::media::audio::common::AudioPort> getConnectedDevicesPortsForMixPort(
bool isInput, const aidl::android::media::audio::common::AudioPort& mixPort) const {
- return isInput ? getAttachedSourceDevicesPortsForMixPort(mixPort)
- : getAttachedSinkDevicesPortsForMixPort(mixPort);
+ return isInput ? getConnectedSourceDevicesPortsForMixPort(mixPort)
+ : getConnectedSinkDevicesPortsForMixPort(mixPort);
}
- std::vector<aidl::android::media::audio::common::AudioPort> getAttachedDevicesPortsForMixPort(
+ std::vector<aidl::android::media::audio::common::AudioPort> getConnectedDevicesPortsForMixPort(
bool isInput,
const aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) const;
std::vector<aidl::android::media::audio::common::AudioPort>
- getAttachedSinkDevicesPortsForMixPort(
+ getConnectedSinkDevicesPortsForMixPort(
const aidl::android::media::audio::common::AudioPort& mixPort) const;
std::vector<aidl::android::media::audio::common::AudioPort>
- getAttachedSourceDevicesPortsForMixPort(
+ getConnectedSourceDevicesPortsForMixPort(
const aidl::android::media::audio::common::AudioPort& mixPort) const;
std::optional<aidl::android::media::audio::common::AudioPort>
- getSourceMixPortForAttachedDevice() const;
+ getSourceMixPortForConnectedDevice() const;
std::optional<SrcSinkPair> getNonRoutableSrcSinkPair(bool isInput) const;
std::optional<SrcSinkPair> getRoutableSrcSinkPair(bool isInput) const;
@@ -96,15 +114,15 @@
std::vector<aidl::android::media::audio::common::AudioPortConfig> getPortConfigsForMixPorts()
const {
auto inputs =
- generateAudioMixPortConfigs(getInputMixPorts(false /*attachedOnly*/), true, false);
- auto outputs = generateAudioMixPortConfigs(getOutputMixPorts(false /*attachedOnly*/), false,
- false);
+ generateAudioMixPortConfigs(getInputMixPorts(false /*connectedOnly*/), true, false);
+ auto outputs = generateAudioMixPortConfigs(getOutputMixPorts(false /*connectedOnly*/),
+ false, false);
inputs.insert(inputs.end(), outputs.begin(), outputs.end());
return inputs;
}
std::vector<aidl::android::media::audio::common::AudioPortConfig> getPortConfigsForMixPorts(
bool isInput) const {
- return generateAudioMixPortConfigs(getMixPorts(isInput, false /*attachedOnly*/), isInput,
+ return generateAudioMixPortConfigs(getMixPorts(isInput, false /*connectedOnly*/), isInput,
false);
}
std::vector<aidl::android::media::audio::common::AudioPortConfig> getPortConfigsForMixPorts(
@@ -114,7 +132,7 @@
std::optional<aidl::android::media::audio::common::AudioPortConfig> getSingleConfigForMixPort(
bool isInput) const {
const auto config = generateAudioMixPortConfigs(
- getMixPorts(isInput, false /*attachedOnly*/), isInput, true);
+ getMixPorts(isInput, false /*connectedOnly*/), isInput, true);
if (!config.empty()) {
return *config.begin();
}
@@ -139,13 +157,20 @@
return *config.begin();
}
+ const ndk::ScopedAStatus& onExternalDeviceConnected(
+ aidl::android::hardware::audio::core::IModule* module,
+ const aidl::android::media::audio::common::AudioPort& port);
+ const ndk::ScopedAStatus& onExternalDeviceDisconnected(
+ aidl::android::hardware::audio::core::IModule* module,
+ const aidl::android::media::audio::common::AudioPort& port);
+
bool isMmapSupported() const;
std::string toString() const;
private:
std::vector<aidl::android::media::audio::common::AudioPort> findMixPorts(
- bool isInput, bool attachedOnly, bool singlePort,
+ bool isInput, bool connectedOnly, bool singlePort,
const std::function<bool(const aidl::android::media::audio::common::AudioPort&)>& pred)
const;
std::vector<aidl::android::media::audio::common::AudioPortConfig> generateAudioMixPortConfigs(
@@ -167,5 +192,7 @@
std::set<int32_t> mAttachedSinkDevicePorts;
std::set<int32_t> mAttachedSourceDevicePorts;
std::set<int32_t> mExternalDevicePorts;
+ std::set<int32_t> mConnectedExternalSinkDevicePorts;
+ std::set<int32_t> mConnectedExternalSourceDevicePorts;
std::vector<aidl::android::hardware::audio::core::AudioRoute> mRoutes;
};
diff --git a/audio/aidl/vts/TestUtils.h b/audio/aidl/vts/TestUtils.h
index 72ca56f..b559669 100644
--- a/audio/aidl/vts/TestUtils.h
+++ b/audio/aidl/vts/TestUtils.h
@@ -77,3 +77,10 @@
#define EXPECT_STATUS(expected, ret) \
EXPECT_PRED_FORMAT2(::android::hardware::audio::common::testing::detail::assertResult, \
expected, ret)
+
+#define SKIP_TEST_IF_DATA_UNSUPPORTED(flags) \
+ ({ \
+ if ((flags).hwAcceleratorMode == Flags::HardwareAccelerator::TUNNEL || (flags).bypass) { \
+ GTEST_SKIP() << "Skip data path for offload"; \
+ } \
+ })
\ No newline at end of file
diff --git a/audio/aidl/vts/VtsHalAECTargetTest.cpp b/audio/aidl/vts/VtsHalAECTargetTest.cpp
index 8828c41..0354e3c 100644
--- a/audio/aidl/vts/VtsHalAECTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAECTargetTest.cpp
@@ -51,7 +51,7 @@
ASSERT_NE(nullptr, mFactory);
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
- Parameter::Specific specific = getDefaultParamSpecific();
+ auto specific = getDefaultParamSpecific();
Parameter::Common common = EffectHelper::createParamCommon(
0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
@@ -65,8 +65,13 @@
ASSERT_NO_FATAL_FAILURE(destroy(mFactory, mEffect));
}
- Parameter::Specific getDefaultParamSpecific() {
- AcousticEchoCanceler aec = AcousticEchoCanceler::make<AcousticEchoCanceler::echoDelayUs>(0);
+ std::optional<Parameter::Specific> getDefaultParamSpecific() {
+ auto aec = AcousticEchoCanceler::make<AcousticEchoCanceler::echoDelayUs>(0);
+ if (!isParameterValid<AcousticEchoCanceler, Range::acousticEchoCanceler>(aec,
+ mDescriptor)) {
+ return std::nullopt;
+ }
+
Parameter::Specific specific =
Parameter::Specific::make<Parameter::Specific::acousticEchoCanceler>(aec);
return specific;
@@ -162,10 +167,8 @@
auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
std::string echoDelay = std::to_string(std::get<PARAM_ECHO_DELAY>(info.param));
std::string mobileMode = std::get<PARAM_MOBILE_MODE>(info.param) ? "true" : "false";
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_EchoDelay_" + echoDelay +
- "_MobileMode_" + mobileMode;
+ std::string name =
+ getPrefix(descriptor) + "_EchoDelay_" + echoDelay + "_MobileMode_" + mobileMode;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalAGC1TargetTest.cpp b/audio/aidl/vts/VtsHalAGC1TargetTest.cpp
index edfcdf6..65c6a8f 100644
--- a/audio/aidl/vts/VtsHalAGC1TargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAGC1TargetTest.cpp
@@ -177,11 +177,9 @@
std::to_string(std::get<PARAM_MAX_COMPRESSION_GAIN>(info.param));
std::string enableLimiter = std::to_string(std::get<PARAM_ENABLE_LIMITER>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_target_peak_level_" +
- targetPeakLevel + "_max_compression_gain_" + maxCompressionGain +
- "_enable_limiter_" + enableLimiter;
+ std::string name = getPrefix(descriptor) + "_target_peak_level_" + targetPeakLevel +
+ "_max_compression_gain_" + maxCompressionGain + "_enable_limiter_" +
+ enableLimiter;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalAGC2TargetTest.cpp b/audio/aidl/vts/VtsHalAGC2TargetTest.cpp
index 8ba8e45..46a569e 100644
--- a/audio/aidl/vts/VtsHalAGC2TargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAGC2TargetTest.cpp
@@ -183,9 +183,7 @@
std::string margin =
std::to_string(static_cast<int>(std::get<PARAM_SATURATION_MARGIN>(info.param)));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_digital_gain_" + gain +
+ std::string name = getPrefix(descriptor) + "_digital_gain_" + gain +
"_level_estimator_" + estimator + "_margin_" + margin;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
diff --git a/audio/aidl/vts/VtsHalAudioCoreConfigTargetTest.cpp b/audio/aidl/vts/VtsHalAudioCoreConfigTargetTest.cpp
index e5e06eb..f82e8e5 100644
--- a/audio/aidl/vts/VtsHalAudioCoreConfigTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioCoreConfigTargetTest.cpp
@@ -20,21 +20,27 @@
#include <unordered_set>
#include <vector>
+#define LOG_TAG "VtsHalAudioCore.Config"
+
+#include <Utils.h>
#include <aidl/Gtest.h>
#include <aidl/Vintf.h>
#include <aidl/android/hardware/audio/core/IConfig.h>
#include <aidl/android/media/audio/common/AudioFlag.h>
#include <aidl/android/media/audio/common/AudioProductStrategyType.h>
-#define LOG_TAG "VtsHalAudioCore.Config"
#include <android-base/logging.h>
#include "AudioHalBinderServiceUtil.h"
#include "TestUtils.h"
using namespace android;
+using aidl::android::hardware::audio::common::isDefaultAudioFormat;
using aidl::android::hardware::audio::core::IConfig;
+using aidl::android::hardware::audio::core::SurroundSoundConfig;
using aidl::android::media::audio::common::AudioAttributes;
using aidl::android::media::audio::common::AudioFlag;
+using aidl::android::media::audio::common::AudioFormatDescription;
+using aidl::android::media::audio::common::AudioFormatType;
using aidl::android::media::audio::common::AudioHalAttributesGroup;
using aidl::android::media::audio::common::AudioHalCapCriterion;
using aidl::android::media::audio::common::AudioHalCapCriterionType;
@@ -46,6 +52,7 @@
using aidl::android::media::audio::common::AudioSource;
using aidl::android::media::audio::common::AudioStreamType;
using aidl::android::media::audio::common::AudioUsage;
+using aidl::android::media::audio::common::PcmType;
class AudioCoreConfig : public testing::TestWithParam<std::string> {
public:
@@ -58,6 +65,7 @@
void RestartService() {
ASSERT_NE(mConfig, nullptr);
mEngineConfig.reset();
+ mSurroundSoundConfig.reset();
mConfig = IConfig::fromBinder(mBinderUtil.restartService());
ASSERT_NE(mConfig, nullptr);
}
@@ -70,6 +78,14 @@
}
}
+ void SetUpSurroundSoundConfig() {
+ if (mSurroundSoundConfig == nullptr) {
+ auto tempConfig = std::make_unique<SurroundSoundConfig>();
+ ASSERT_IS_OK(mConfig->getSurroundSoundConfig(tempConfig.get()));
+ mSurroundSoundConfig = std::move(tempConfig);
+ }
+ }
+
static bool IsProductStrategyTypeReservedForSystemUse(const AudioProductStrategyType& pst) {
switch (pst) {
case AudioProductStrategyType::SYS_RESERVED_NONE:
@@ -325,9 +341,41 @@
}
}
+ void ValidateAudioFormatDescription(const AudioFormatDescription& format) {
+ EXPECT_NE(AudioFormatType::SYS_RESERVED_INVALID, format.type);
+ if (format.type == AudioFormatType::PCM) {
+ EXPECT_NE(PcmType::DEFAULT, format.pcm);
+ EXPECT_TRUE(format.encoding.empty()) << format.encoding;
+ } else {
+ EXPECT_FALSE(format.encoding.empty());
+ }
+ }
+
+ /**
+ * Verify that the surround sound configuration is not empty.
+ * Verify each of the formatFamilies has a non-empty primaryFormat.
+ * Verify that each format only appears once.
+ */
+ void ValidateSurroundSoundConfig() {
+ EXPECT_FALSE(mSurroundSoundConfig->formatFamilies.empty());
+ std::set<AudioFormatDescription> formatSet;
+ for (const SurroundSoundConfig::SurroundFormatFamily& family :
+ mSurroundSoundConfig->formatFamilies) {
+ EXPECT_NO_FATAL_FAILURE(ValidateAudioFormatDescription(family.primaryFormat));
+ EXPECT_FALSE(isDefaultAudioFormat(family.primaryFormat));
+ EXPECT_TRUE(formatSet.insert(family.primaryFormat).second);
+ for (const AudioFormatDescription& subformat : family.subFormats) {
+ EXPECT_NO_FATAL_FAILURE(ValidateAudioFormatDescription(subformat));
+ EXPECT_FALSE(isDefaultAudioFormat(subformat));
+ EXPECT_TRUE(formatSet.insert(subformat).second);
+ }
+ }
+ }
+
private:
std::shared_ptr<IConfig> mConfig;
std::unique_ptr<AudioHalEngineConfig> mEngineConfig;
+ std::unique_ptr<SurroundSoundConfig> mSurroundSoundConfig;
AudioHalBinderServiceUtil mBinderUtil;
};
@@ -344,6 +392,11 @@
EXPECT_NO_FATAL_FAILURE(ValidateAudioHalEngineConfig());
}
+TEST_P(AudioCoreConfig, GetSurroundSoundConfigIsValid) {
+ ASSERT_NO_FATAL_FAILURE(SetUpSurroundSoundConfig());
+ EXPECT_NO_FATAL_FAILURE(ValidateSurroundSoundConfig());
+}
+
INSTANTIATE_TEST_SUITE_P(AudioCoreConfigTest, AudioCoreConfig,
testing::ValuesIn(android::getAidlHalInstanceNames(IConfig::descriptor)),
android::PrintInstanceNameToString);
diff --git a/audio/aidl/vts/VtsHalAudioCoreModuleTargetTest.cpp b/audio/aidl/vts/VtsHalAudioCoreModuleTargetTest.cpp
index 825b865..b1eecd2 100644
--- a/audio/aidl/vts/VtsHalAudioCoreModuleTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioCoreModuleTargetTest.cpp
@@ -144,28 +144,36 @@
}
AudioPort GenerateUniqueDeviceAddress(const AudioPort& port) {
+ // Point-to-point connections do not use addresses.
+ static const std::set<std::string> kPointToPointConnections = {
+ AudioDeviceDescription::CONNECTION_ANALOG, AudioDeviceDescription::CONNECTION_HDMI,
+ AudioDeviceDescription::CONNECTION_HDMI_ARC,
+ AudioDeviceDescription::CONNECTION_HDMI_EARC, AudioDeviceDescription::CONNECTION_SPDIF};
static int nextId = 0;
using Tag = AudioDeviceAddress::Tag;
+ const auto& deviceDescription = port.ext.get<AudioPortExt::Tag::device>().device.type;
AudioDeviceAddress address;
- switch (suggestDeviceAddressTag(port.ext.get<AudioPortExt::Tag::device>().device.type)) {
- case Tag::id:
- address = AudioDeviceAddress::make<Tag::id>(std::to_string(++nextId));
- break;
- case Tag::mac:
- address = AudioDeviceAddress::make<Tag::mac>(
- std::vector<uint8_t>{1, 2, 3, 4, 5, static_cast<uint8_t>(++nextId & 0xff)});
- break;
- case Tag::ipv4:
- address = AudioDeviceAddress::make<Tag::ipv4>(
- std::vector<uint8_t>{192, 168, 0, static_cast<uint8_t>(++nextId & 0xff)});
- break;
- case Tag::ipv6:
- address = AudioDeviceAddress::make<Tag::ipv6>(std::vector<int32_t>{
- 0xfc00, 0x0123, 0x4567, 0x89ab, 0xcdef, 0, 0, ++nextId & 0xffff});
- break;
- case Tag::alsa:
- address = AudioDeviceAddress::make<Tag::alsa>(std::vector<int32_t>{1, ++nextId});
- break;
+ if (kPointToPointConnections.count(deviceDescription.connection) == 0) {
+ switch (suggestDeviceAddressTag(deviceDescription)) {
+ case Tag::id:
+ address = AudioDeviceAddress::make<Tag::id>(std::to_string(++nextId));
+ break;
+ case Tag::mac:
+ address = AudioDeviceAddress::make<Tag::mac>(
+ std::vector<uint8_t>{1, 2, 3, 4, 5, static_cast<uint8_t>(++nextId & 0xff)});
+ break;
+ case Tag::ipv4:
+ address = AudioDeviceAddress::make<Tag::ipv4>(
+ std::vector<uint8_t>{192, 168, 0, static_cast<uint8_t>(++nextId & 0xff)});
+ break;
+ case Tag::ipv6:
+ address = AudioDeviceAddress::make<Tag::ipv6>(std::vector<int32_t>{
+ 0xfc00, 0x0123, 0x4567, 0x89ab, 0xcdef, 0, 0, ++nextId & 0xffff});
+ break;
+ case Tag::alsa:
+ address = AudioDeviceAddress::make<Tag::alsa>(std::vector<int32_t>{1, ++nextId});
+ break;
+ }
}
AudioPort result = port;
result.ext.get<AudioPortExt::Tag::device>().device.address = std::move(address);
@@ -525,13 +533,21 @@
EXPECT_IS_OK(mModule->disconnectExternalDevice(getId()))
<< "when disconnecting device port ID " << getId();
}
+ if (mModuleConfig != nullptr) {
+ EXPECT_IS_OK(mModuleConfig->onExternalDeviceDisconnected(mModule, mConnectedPort))
+ << "when external device disconnected";
+ }
}
- void SetUp(IModule* module) {
+ void SetUp(IModule* module, ModuleConfig* moduleConfig) {
ASSERT_IS_OK(module->connectExternalDevice(mIdAndData, &mConnectedPort))
<< "when connecting device port ID & data " << mIdAndData.toString();
ASSERT_NE(mIdAndData.id, getId())
<< "ID of the connected port must not be the same as the ID of the template port";
+ ASSERT_NE(moduleConfig, nullptr);
+ ASSERT_IS_OK(moduleConfig->onExternalDeviceConnected(module, mConnectedPort))
+ << "when external device connected";
mModule = module;
+ mModuleConfig = moduleConfig;
}
int32_t getId() const { return mConnectedPort.id; }
const AudioPort& get() { return mConnectedPort; }
@@ -539,6 +555,7 @@
private:
const AudioPort mIdAndData;
IModule* mModule = nullptr;
+ ModuleConfig* mModuleConfig = nullptr;
AudioPort mConnectedPort;
};
@@ -1379,7 +1396,7 @@
<< "At least two mix ports have PRIMARY flag set: " << primaryMixPort.value()
<< " and " << port.id;
primaryMixPort = port.id;
- EXPECT_EQ(1, mixPort.maxOpenStreamCount)
+ EXPECT_GE(mixPort.maxOpenStreamCount, 0)
<< "Primary mix port " << port.id << " can not have maxOpenStreamCount "
<< mixPort.maxOpenStreamCount;
}
@@ -1422,7 +1439,7 @@
for (const auto& port : ports) {
AudioPort portWithData = GenerateUniqueDeviceAddress(port);
WithDevicePortConnectedState portConnected(portWithData);
- ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+ ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
const int32_t connectedPortId = portConnected.getId();
ASSERT_NE(portWithData.id, connectedPortId);
ASSERT_EQ(portWithData.ext.getTag(), portConnected.get().ext.getTag());
@@ -1526,7 +1543,7 @@
TEST_P(AudioCoreModule, SetAudioPortConfigSuggestedConfig) {
ASSERT_NO_FATAL_FAILURE(SetUpModuleConfig());
- auto srcMixPort = moduleConfig->getSourceMixPortForAttachedDevice();
+ auto srcMixPort = moduleConfig->getSourceMixPortForConnectedDevice();
if (!srcMixPort.has_value()) {
GTEST_SKIP() << "No mix port for attached output devices";
}
@@ -1578,7 +1595,7 @@
}
for (const auto& port : ports) {
WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(port));
- ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+ ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
ASSERT_NO_FATAL_FAILURE(
ApplyEveryConfig(moduleConfig->getPortConfigsForDevicePort(portConnected.get())));
}
@@ -1627,14 +1644,17 @@
if (ports.empty()) {
GTEST_SKIP() << "No external devices in the module.";
}
- AudioPort ignored;
WithDebugFlags doNotSimulateConnections = WithDebugFlags::createNested(*debug);
doNotSimulateConnections.flags().simulateDeviceConnections = false;
ASSERT_NO_FATAL_FAILURE(doNotSimulateConnections.SetUp(module.get()));
for (const auto& port : ports) {
- AudioPort portWithData = GenerateUniqueDeviceAddress(port);
- EXPECT_STATUS(EX_ILLEGAL_STATE, module->connectExternalDevice(portWithData, &ignored))
- << "static port " << portWithData.toString();
+ AudioPort portWithData = GenerateUniqueDeviceAddress(port), connectedPort;
+ ScopedAStatus status = module->connectExternalDevice(portWithData, &connectedPort);
+ EXPECT_STATUS(EX_ILLEGAL_STATE, status) << "static port " << portWithData.toString();
+ if (status.isOk()) {
+ EXPECT_IS_OK(module->disconnectExternalDevice(connectedPort.id))
+ << "when disconnecting device port ID " << connectedPort.id;
+ }
}
}
@@ -1645,7 +1665,7 @@
GTEST_SKIP() << "No external devices in the module.";
}
WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(*ports.begin()));
- ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+ ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
ModuleDebug midwayDebugChange = debug->flags();
midwayDebugChange.simulateDeviceConnections = false;
EXPECT_STATUS(EX_ILLEGAL_STATE, module->setModuleDebug(midwayDebugChange))
@@ -1700,7 +1720,7 @@
<< "when disconnecting already disconnected device port ID " << port.id;
AudioPort portWithData = GenerateUniqueDeviceAddress(port);
WithDevicePortConnectedState portConnected(portWithData);
- ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+ ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
EXPECT_STATUS(EX_ILLEGAL_ARGUMENT,
module->connectExternalDevice(portConnected.get(), &ignored))
<< "when trying to connect a connected device port "
@@ -1722,7 +1742,7 @@
}
for (const auto& port : ports) {
WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(port));
- ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+ ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
const auto portConfig = moduleConfig->getSingleConfigForDevicePort(portConnected.get());
{
WithAudioPortConfig config(portConfig);
@@ -1750,7 +1770,7 @@
int32_t connectedPortId;
{
WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(port));
- ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+ ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
connectedPortId = portConnected.getId();
std::vector<AudioRoute> connectedPortRoutes;
ASSERT_IS_OK(module->getAudioRoutesForAudioPort(connectedPortId, &connectedPortRoutes))
@@ -1791,7 +1811,7 @@
}
for (const auto& port : externalDevicePorts) {
WithDevicePortConnectedState portConnected(GenerateUniqueDeviceAddress(port));
- ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get()));
+ ASSERT_NO_FATAL_FAILURE(portConnected.SetUp(module.get(), moduleConfig.get()));
std::vector<AudioRoute> routes;
ASSERT_IS_OK(module->getAudioRoutesForAudioPort(portConnected.getId(), &routes));
std::vector<AudioPort> allPorts;
@@ -2456,7 +2476,7 @@
void OpenOverMaxCount() {
constexpr bool isInput = IOTraits<Stream>::is_input;
- auto ports = moduleConfig->getMixPorts(isInput, true /*attachedOnly*/);
+ auto ports = moduleConfig->getMixPorts(isInput, true /*connectedOnly*/);
bool hasSingleRun = false;
for (const auto& port : ports) {
const size_t maxStreamCount = port.ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
@@ -2577,7 +2597,7 @@
void HwGainHwVolume() {
const auto ports =
- moduleConfig->getMixPorts(IOTraits<Stream>::is_input, true /*attachedOnly*/);
+ moduleConfig->getMixPorts(IOTraits<Stream>::is_input, true /*connectedOnly*/);
if (ports.empty()) {
GTEST_SKIP() << "No mix ports";
}
@@ -2616,7 +2636,7 @@
// it as an invalid argument, or say that offloaded effects are not supported.
void AddRemoveEffectInvalidArguments() {
const auto ports =
- moduleConfig->getMixPorts(IOTraits<Stream>::is_input, true /*attachedOnly*/);
+ moduleConfig->getMixPorts(IOTraits<Stream>::is_input, true /*connectedOnly*/);
if (ports.empty()) {
GTEST_SKIP() << "No mix ports";
}
@@ -2739,7 +2759,7 @@
if (!status.isOk()) {
GTEST_SKIP() << "Microphone info is not supported";
}
- const auto ports = moduleConfig->getInputMixPorts(true /*attachedOnly*/);
+ const auto ports = moduleConfig->getInputMixPorts(true /*connectedOnly*/);
if (ports.empty()) {
GTEST_SKIP() << "No input mix ports for attached devices";
}
@@ -2756,13 +2776,14 @@
"non-empty list of active microphones";
}
if (auto micDevicePorts = ModuleConfig::getBuiltInMicPorts(
- moduleConfig->getAttachedSourceDevicesPortsForMixPort(port));
+ moduleConfig->getConnectedSourceDevicesPortsForMixPort(port));
!micDevicePorts.empty()) {
auto devicePortConfig = moduleConfig->getSingleConfigForDevicePort(micDevicePorts[0]);
WithAudioPatch patch(true /*isInput*/, stream.getPortConfig(), devicePortConfig);
ASSERT_NO_FATAL_FAILURE(patch.SetUp(module.get()));
std::vector<MicrophoneDynamicInfo> activeMics;
EXPECT_IS_OK(stream.get()->getActiveMicrophones(&activeMics));
+ EXPECT_FALSE(activeMics.empty());
for (const auto& mic : activeMics) {
EXPECT_NE(micInfos.end(),
std::find_if(micInfos.begin(), micInfos.end(),
@@ -2787,7 +2808,7 @@
TEST_P(AudioStreamIn, MicrophoneDirection) {
using MD = IStreamIn::MicrophoneDirection;
- const auto ports = moduleConfig->getInputMixPorts(true /*attachedOnly*/);
+ const auto ports = moduleConfig->getInputMixPorts(true /*connectedOnly*/);
if (ports.empty()) {
GTEST_SKIP() << "No input mix ports for attached devices";
}
@@ -2810,7 +2831,7 @@
}
TEST_P(AudioStreamIn, MicrophoneFieldDimension) {
- const auto ports = moduleConfig->getInputMixPorts(true /*attachedOnly*/);
+ const auto ports = moduleConfig->getInputMixPorts(true /*connectedOnly*/);
if (ports.empty()) {
GTEST_SKIP() << "No input mix ports for attached devices";
}
@@ -2842,7 +2863,7 @@
TEST_P(AudioStreamOut, OpenTwicePrimary) {
const auto mixPorts =
- moduleConfig->getPrimaryMixPorts(true /*attachedOnly*/, true /*singlePort*/);
+ moduleConfig->getPrimaryMixPorts(true /*connectedOnly*/, true /*singlePort*/);
if (mixPorts.empty()) {
GTEST_SKIP() << "No primary mix port which could be routed to attached devices";
}
@@ -2853,7 +2874,7 @@
TEST_P(AudioStreamOut, RequireOffloadInfo) {
const auto offloadMixPorts =
- moduleConfig->getOffloadMixPorts(true /*attachedOnly*/, true /*singlePort*/);
+ moduleConfig->getOffloadMixPorts(true /*connectedOnly*/, true /*singlePort*/);
if (offloadMixPorts.empty()) {
GTEST_SKIP()
<< "No mix port for compressed offload that could be routed to attached devices";
@@ -2875,7 +2896,7 @@
TEST_P(AudioStreamOut, RequireAsyncCallback) {
const auto nonBlockingMixPorts =
- moduleConfig->getNonBlockingMixPorts(true /*attachedOnly*/, true /*singlePort*/);
+ moduleConfig->getNonBlockingMixPorts(true /*connectedOnly*/, true /*singlePort*/);
if (nonBlockingMixPorts.empty()) {
GTEST_SKIP()
<< "No mix port for non-blocking output that could be routed to attached devices";
@@ -2898,7 +2919,7 @@
}
TEST_P(AudioStreamOut, AudioDescriptionMixLevel) {
- const auto ports = moduleConfig->getOutputMixPorts(true /*attachedOnly*/);
+ const auto ports = moduleConfig->getOutputMixPorts(true /*connectedOnly*/);
if (ports.empty()) {
GTEST_SKIP() << "No output mix ports";
}
@@ -2926,7 +2947,7 @@
}
TEST_P(AudioStreamOut, DualMonoMode) {
- const auto ports = moduleConfig->getOutputMixPorts(true /*attachedOnly*/);
+ const auto ports = moduleConfig->getOutputMixPorts(true /*connectedOnly*/);
if (ports.empty()) {
GTEST_SKIP() << "No output mix ports";
}
@@ -2950,7 +2971,7 @@
}
TEST_P(AudioStreamOut, LatencyMode) {
- const auto ports = moduleConfig->getOutputMixPorts(true /*attachedOnly*/);
+ const auto ports = moduleConfig->getOutputMixPorts(true /*connectedOnly*/);
if (ports.empty()) {
GTEST_SKIP() << "No output mix ports";
}
@@ -2992,7 +3013,7 @@
TEST_P(AudioStreamOut, PlaybackRate) {
static const auto kStatuses = {EX_NONE, EX_UNSUPPORTED_OPERATION};
const auto offloadMixPorts =
- moduleConfig->getOffloadMixPorts(true /*attachedOnly*/, false /*singlePort*/);
+ moduleConfig->getOffloadMixPorts(true /*connectedOnly*/, false /*singlePort*/);
if (offloadMixPorts.empty()) {
GTEST_SKIP()
<< "No mix port for compressed offload that could be routed to attached devices";
@@ -3062,7 +3083,7 @@
TEST_P(AudioStreamOut, SelectPresentation) {
static const auto kStatuses = {EX_ILLEGAL_ARGUMENT, EX_UNSUPPORTED_OPERATION};
const auto offloadMixPorts =
- moduleConfig->getOffloadMixPorts(true /*attachedOnly*/, false /*singlePort*/);
+ moduleConfig->getOffloadMixPorts(true /*connectedOnly*/, false /*singlePort*/);
if (offloadMixPorts.empty()) {
GTEST_SKIP()
<< "No mix port for compressed offload that could be routed to attached devices";
@@ -3084,7 +3105,7 @@
TEST_P(AudioStreamOut, UpdateOffloadMetadata) {
const auto offloadMixPorts =
- moduleConfig->getOffloadMixPorts(true /*attachedOnly*/, false /*singlePort*/);
+ moduleConfig->getOffloadMixPorts(true /*connectedOnly*/, false /*singlePort*/);
if (offloadMixPorts.empty()) {
GTEST_SKIP()
<< "No mix port for compressed offload that could be routed to attached devices";
@@ -3188,10 +3209,17 @@
std::string mUnexpectedTransition;
};
-enum { NAMED_CMD_NAME, NAMED_CMD_DELAY_MS, NAMED_CMD_STREAM_TYPE, NAMED_CMD_CMDS };
+enum {
+ NAMED_CMD_NAME,
+ NAMED_CMD_DELAY_MS,
+ NAMED_CMD_STREAM_TYPE,
+ NAMED_CMD_CMDS,
+ NAMED_CMD_VALIDATE_POS_INCREASE
+};
enum class StreamTypeFilter { ANY, SYNC, ASYNC };
using NamedCommandSequence =
- std::tuple<std::string, int, StreamTypeFilter, std::shared_ptr<StateSequence>>;
+ std::tuple<std::string, int /*cmdDelayMs*/, StreamTypeFilter,
+ std::shared_ptr<StateSequence>, bool /*validatePositionIncrease*/>;
enum { PARAM_MODULE_NAME, PARAM_CMD_SEQ, PARAM_SETUP_SEQ };
using StreamIoTestParameters =
std::tuple<std::string /*moduleName*/, NamedCommandSequence, bool /*useSetupSequence2*/>;
@@ -3235,10 +3263,14 @@
ASSERT_NO_FATAL_FAILURE(delayTransientStates.SetUp(module.get()));
const auto& commandsAndStates =
std::get<NAMED_CMD_CMDS>(std::get<PARAM_CMD_SEQ>(GetParam()));
+ const bool validatePositionIncrease =
+ std::get<NAMED_CMD_VALIDATE_POS_INCREASE>(std::get<PARAM_CMD_SEQ>(GetParam()));
if (!std::get<PARAM_SETUP_SEQ>(GetParam())) {
- ASSERT_NO_FATAL_FAILURE(RunStreamIoCommandsImplSeq1(portConfig, commandsAndStates));
+ ASSERT_NO_FATAL_FAILURE(RunStreamIoCommandsImplSeq1(portConfig, commandsAndStates,
+ validatePositionIncrease));
} else {
- ASSERT_NO_FATAL_FAILURE(RunStreamIoCommandsImplSeq2(portConfig, commandsAndStates));
+ ASSERT_NO_FATAL_FAILURE(RunStreamIoCommandsImplSeq2(portConfig, commandsAndStates,
+ validatePositionIncrease));
}
if (isNonBlocking) {
// Also try running the same sequence with "aosp.forceTransientBurst" set.
@@ -3249,11 +3281,11 @@
if (forceTransientBurst.SetUpNoChecks(module.get(), true /*failureExpected*/)
.isOk()) {
if (!std::get<PARAM_SETUP_SEQ>(GetParam())) {
- ASSERT_NO_FATAL_FAILURE(
- RunStreamIoCommandsImplSeq1(portConfig, commandsAndStates));
+ ASSERT_NO_FATAL_FAILURE(RunStreamIoCommandsImplSeq1(
+ portConfig, commandsAndStates, validatePositionIncrease));
} else {
- ASSERT_NO_FATAL_FAILURE(
- RunStreamIoCommandsImplSeq2(portConfig, commandsAndStates));
+ ASSERT_NO_FATAL_FAILURE(RunStreamIoCommandsImplSeq2(
+ portConfig, commandsAndStates, validatePositionIncrease));
}
}
} else if (!IOTraits<Stream>::is_input) {
@@ -3266,11 +3298,11 @@
if (forceSynchronousDrain.SetUpNoChecks(module.get(), true /*failureExpected*/)
.isOk()) {
if (!std::get<PARAM_SETUP_SEQ>(GetParam())) {
- ASSERT_NO_FATAL_FAILURE(
- RunStreamIoCommandsImplSeq1(portConfig, commandsAndStates));
+ ASSERT_NO_FATAL_FAILURE(RunStreamIoCommandsImplSeq1(
+ portConfig, commandsAndStates, validatePositionIncrease));
} else {
- ASSERT_NO_FATAL_FAILURE(
- RunStreamIoCommandsImplSeq2(portConfig, commandsAndStates));
+ ASSERT_NO_FATAL_FAILURE(RunStreamIoCommandsImplSeq2(
+ portConfig, commandsAndStates, validatePositionIncrease));
}
}
}
@@ -3284,11 +3316,13 @@
// Set up a patch first, then open a stream.
void RunStreamIoCommandsImplSeq1(const AudioPortConfig& portConfig,
- std::shared_ptr<StateSequence> commandsAndStates) {
- auto devicePorts = moduleConfig->getAttachedDevicesPortsForMixPort(
+ std::shared_ptr<StateSequence> commandsAndStates,
+ bool validatePositionIncrease) {
+ auto devicePorts = moduleConfig->getConnectedDevicesPortsForMixPort(
IOTraits<Stream>::is_input, portConfig);
ASSERT_FALSE(devicePorts.empty());
auto devicePortConfig = moduleConfig->getSingleConfigForDevicePort(devicePorts[0]);
+ SCOPED_TRACE(devicePortConfig.toString());
WithAudioPatch patch(IOTraits<Stream>::is_input, portConfig, devicePortConfig);
ASSERT_NO_FATAL_FAILURE(patch.SetUp(module.get()));
@@ -3306,14 +3340,17 @@
EXPECT_FALSE(worker.hasError()) << worker.getError();
EXPECT_EQ("", driver.getUnexpectedStateTransition());
if (ValidateObservablePosition(devicePortConfig)) {
- EXPECT_TRUE(driver.hasObservablePositionIncrease());
+ if (validatePositionIncrease) {
+ EXPECT_TRUE(driver.hasObservablePositionIncrease());
+ }
EXPECT_FALSE(driver.hasRetrogradeObservablePosition());
}
}
// Open a stream, then set up a patch for it.
void RunStreamIoCommandsImplSeq2(const AudioPortConfig& portConfig,
- std::shared_ptr<StateSequence> commandsAndStates) {
+ std::shared_ptr<StateSequence> commandsAndStates,
+ bool validatePositionIncrease) {
WithStream<Stream> stream(portConfig);
ASSERT_NO_FATAL_FAILURE(stream.SetUp(module.get(), kDefaultBufferSizeFrames));
StreamLogicDefaultDriver driver(commandsAndStates,
@@ -3321,10 +3358,11 @@
typename IOTraits<Stream>::Worker worker(*stream.getContext(), &driver,
stream.getEventReceiver());
- auto devicePorts = moduleConfig->getAttachedDevicesPortsForMixPort(
+ auto devicePorts = moduleConfig->getConnectedDevicesPortsForMixPort(
IOTraits<Stream>::is_input, portConfig);
ASSERT_FALSE(devicePorts.empty());
auto devicePortConfig = moduleConfig->getSingleConfigForDevicePort(devicePorts[0]);
+ SCOPED_TRACE(devicePortConfig.toString());
WithAudioPatch patch(IOTraits<Stream>::is_input, stream.getPortConfig(), devicePortConfig);
ASSERT_NO_FATAL_FAILURE(patch.SetUp(module.get()));
@@ -3335,7 +3373,9 @@
EXPECT_FALSE(worker.hasError()) << worker.getError();
EXPECT_EQ("", driver.getUnexpectedStateTransition());
if (ValidateObservablePosition(devicePortConfig)) {
- EXPECT_TRUE(driver.hasObservablePositionIncrease());
+ if (validatePositionIncrease) {
+ EXPECT_TRUE(driver.hasObservablePositionIncrease());
+ }
EXPECT_FALSE(driver.hasRetrogradeObservablePosition());
}
}
@@ -3672,22 +3712,28 @@
using State = StreamDescriptor::State;
auto d = std::make_unique<StateDag>();
StateDag::Node last = d->makeFinalNode(State::ACTIVE);
- StateDag::Node active = d->makeNode(State::ACTIVE, kBurstCommand, last);
+ // Use a couple of bursts to ensure that the driver starts reporting the position.
+ StateDag::Node active2 = d->makeNode(State::ACTIVE, kBurstCommand, last);
+ StateDag::Node active = d->makeNode(State::ACTIVE, kBurstCommand, active2);
StateDag::Node idle = d->makeNode(State::IDLE, kBurstCommand, active);
if (!isSync) {
// Allow optional routing via the TRANSFERRING state on bursts.
- active.children().push_back(d->makeNode(State::TRANSFERRING, kTransferReadyEvent, last));
+ active2.children().push_back(d->makeNode(State::TRANSFERRING, kTransferReadyEvent, last));
+ active.children().push_back(d->makeNode(State::TRANSFERRING, kTransferReadyEvent, active2));
idle.children().push_back(d->makeNode(State::TRANSFERRING, kTransferReadyEvent, active));
}
d->makeNode(State::STANDBY, kStartCommand, idle);
return std::make_shared<StateSequenceFollower>(std::move(d));
}
static const NamedCommandSequence kReadSeq =
- std::make_tuple(std::string("Read"), 0, StreamTypeFilter::ANY, makeBurstCommands(true));
+ std::make_tuple(std::string("Read"), 0, StreamTypeFilter::ANY, makeBurstCommands(true),
+ true /*validatePositionIncrease*/);
static const NamedCommandSequence kWriteSyncSeq =
- std::make_tuple(std::string("Write"), 0, StreamTypeFilter::SYNC, makeBurstCommands(true));
+ std::make_tuple(std::string("Write"), 0, StreamTypeFilter::SYNC, makeBurstCommands(true),
+ true /*validatePositionIncrease*/);
static const NamedCommandSequence kWriteAsyncSeq =
- std::make_tuple(std::string("Write"), 0, StreamTypeFilter::ASYNC, makeBurstCommands(false));
+ std::make_tuple(std::string("Write"), 0, StreamTypeFilter::ASYNC, makeBurstCommands(false),
+ true /*validatePositionIncrease*/);
std::shared_ptr<StateSequence> makeAsyncDrainCommands(bool isInput) {
using State = StreamDescriptor::State;
@@ -3715,11 +3761,12 @@
}
return std::make_shared<StateSequenceFollower>(std::move(d));
}
-static const NamedCommandSequence kWriteDrainAsyncSeq =
- std::make_tuple(std::string("WriteDrain"), kStreamTransientStateTransitionDelayMs,
- StreamTypeFilter::ASYNC, makeAsyncDrainCommands(false));
-static const NamedCommandSequence kDrainInSeq = std::make_tuple(
- std::string("Drain"), 0, StreamTypeFilter::ANY, makeAsyncDrainCommands(true));
+static const NamedCommandSequence kWriteDrainAsyncSeq = std::make_tuple(
+ std::string("WriteDrain"), kStreamTransientStateTransitionDelayMs, StreamTypeFilter::ASYNC,
+ makeAsyncDrainCommands(false), false /*validatePositionIncrease*/);
+static const NamedCommandSequence kDrainInSeq =
+ std::make_tuple(std::string("Drain"), 0, StreamTypeFilter::ANY,
+ makeAsyncDrainCommands(true), false /*validatePositionIncrease*/);
std::shared_ptr<StateSequence> makeDrainOutCommands(bool isSync) {
using State = StreamDescriptor::State;
@@ -3739,10 +3786,12 @@
d->makeNode(State::STANDBY, kStartCommand, idle);
return std::make_shared<StateSequenceFollower>(std::move(d));
}
-static const NamedCommandSequence kDrainOutSyncSeq = std::make_tuple(
- std::string("Drain"), 0, StreamTypeFilter::SYNC, makeDrainOutCommands(true));
-static const NamedCommandSequence kDrainOutAsyncSeq = std::make_tuple(
- std::string("Drain"), 0, StreamTypeFilter::ASYNC, makeDrainOutCommands(false));
+static const NamedCommandSequence kDrainOutSyncSeq =
+ std::make_tuple(std::string("Drain"), 0, StreamTypeFilter::SYNC, makeDrainOutCommands(true),
+ false /*validatePositionIncrease*/);
+static const NamedCommandSequence kDrainOutAsyncSeq =
+ std::make_tuple(std::string("Drain"), 0, StreamTypeFilter::ASYNC,
+ makeDrainOutCommands(false), false /*validatePositionIncrease*/);
std::shared_ptr<StateSequence> makeDrainPauseOutCommands(bool isSync) {
using State = StreamDescriptor::State;
@@ -3763,12 +3812,12 @@
d->makeNode(State::STANDBY, kStartCommand, idle);
return std::make_shared<StateSequenceFollower>(std::move(d));
}
-static const NamedCommandSequence kDrainPauseOutSyncSeq =
- std::make_tuple(std::string("DrainPause"), kStreamTransientStateTransitionDelayMs,
- StreamTypeFilter::SYNC, makeDrainPauseOutCommands(true));
-static const NamedCommandSequence kDrainPauseOutAsyncSeq =
- std::make_tuple(std::string("DrainPause"), kStreamTransientStateTransitionDelayMs,
- StreamTypeFilter::ASYNC, makeDrainPauseOutCommands(false));
+static const NamedCommandSequence kDrainPauseOutSyncSeq = std::make_tuple(
+ std::string("DrainPause"), kStreamTransientStateTransitionDelayMs, StreamTypeFilter::SYNC,
+ makeDrainPauseOutCommands(true), false /*validatePositionIncrease*/);
+static const NamedCommandSequence kDrainPauseOutAsyncSeq = std::make_tuple(
+ std::string("DrainPause"), kStreamTransientStateTransitionDelayMs, StreamTypeFilter::ASYNC,
+ makeDrainPauseOutCommands(false), false /*validatePositionIncrease*/);
// This sequence also verifies that the capture / presentation position is not reset on standby.
std::shared_ptr<StateSequence> makeStandbyCommands(bool isInput, bool isSync) {
@@ -3809,13 +3858,15 @@
}
return std::make_shared<StateSequenceFollower>(std::move(d));
}
-static const NamedCommandSequence kStandbyInSeq = std::make_tuple(
- std::string("Standby"), 0, StreamTypeFilter::ANY, makeStandbyCommands(true, false));
-static const NamedCommandSequence kStandbyOutSyncSeq = std::make_tuple(
- std::string("Standby"), 0, StreamTypeFilter::SYNC, makeStandbyCommands(false, true));
-static const NamedCommandSequence kStandbyOutAsyncSeq =
- std::make_tuple(std::string("Standby"), kStreamTransientStateTransitionDelayMs,
- StreamTypeFilter::ASYNC, makeStandbyCommands(false, false));
+static const NamedCommandSequence kStandbyInSeq =
+ std::make_tuple(std::string("Standby"), 0, StreamTypeFilter::ANY,
+ makeStandbyCommands(true, false), false /*validatePositionIncrease*/);
+static const NamedCommandSequence kStandbyOutSyncSeq =
+ std::make_tuple(std::string("Standby"), 0, StreamTypeFilter::SYNC,
+ makeStandbyCommands(false, true), false /*validatePositionIncrease*/);
+static const NamedCommandSequence kStandbyOutAsyncSeq = std::make_tuple(
+ std::string("Standby"), kStreamTransientStateTransitionDelayMs, StreamTypeFilter::ASYNC,
+ makeStandbyCommands(false, false), false /*validatePositionIncrease*/);
std::shared_ptr<StateSequence> makePauseCommands(bool isInput, bool isSync) {
using State = StreamDescriptor::State;
@@ -3850,13 +3901,15 @@
}
return std::make_shared<StateSequenceFollower>(std::move(d));
}
-static const NamedCommandSequence kPauseInSeq = std::make_tuple(
- std::string("Pause"), 0, StreamTypeFilter::ANY, makePauseCommands(true, false));
-static const NamedCommandSequence kPauseOutSyncSeq = std::make_tuple(
- std::string("Pause"), 0, StreamTypeFilter::SYNC, makePauseCommands(false, true));
-static const NamedCommandSequence kPauseOutAsyncSeq =
- std::make_tuple(std::string("Pause"), kStreamTransientStateTransitionDelayMs,
- StreamTypeFilter::ASYNC, makePauseCommands(false, false));
+static const NamedCommandSequence kPauseInSeq =
+ std::make_tuple(std::string("Pause"), 0, StreamTypeFilter::ANY,
+ makePauseCommands(true, false), false /*validatePositionIncrease*/);
+static const NamedCommandSequence kPauseOutSyncSeq =
+ std::make_tuple(std::string("Pause"), 0, StreamTypeFilter::SYNC,
+ makePauseCommands(false, true), false /*validatePositionIncrease*/);
+static const NamedCommandSequence kPauseOutAsyncSeq = std::make_tuple(
+ std::string("Pause"), kStreamTransientStateTransitionDelayMs, StreamTypeFilter::ASYNC,
+ makePauseCommands(false, false), false /*validatePositionIncrease*/);
std::shared_ptr<StateSequence> makeFlushCommands(bool isInput, bool isSync) {
using State = StreamDescriptor::State;
@@ -3883,13 +3936,15 @@
}
return std::make_shared<StateSequenceFollower>(std::move(d));
}
-static const NamedCommandSequence kFlushInSeq = std::make_tuple(
- std::string("Flush"), 0, StreamTypeFilter::ANY, makeFlushCommands(true, false));
-static const NamedCommandSequence kFlushOutSyncSeq = std::make_tuple(
- std::string("Flush"), 0, StreamTypeFilter::SYNC, makeFlushCommands(false, true));
-static const NamedCommandSequence kFlushOutAsyncSeq =
- std::make_tuple(std::string("Flush"), kStreamTransientStateTransitionDelayMs,
- StreamTypeFilter::ASYNC, makeFlushCommands(false, false));
+static const NamedCommandSequence kFlushInSeq =
+ std::make_tuple(std::string("Flush"), 0, StreamTypeFilter::ANY,
+ makeFlushCommands(true, false), false /*validatePositionIncrease*/);
+static const NamedCommandSequence kFlushOutSyncSeq =
+ std::make_tuple(std::string("Flush"), 0, StreamTypeFilter::SYNC,
+ makeFlushCommands(false, true), false /*validatePositionIncrease*/);
+static const NamedCommandSequence kFlushOutAsyncSeq = std::make_tuple(
+ std::string("Flush"), kStreamTransientStateTransitionDelayMs, StreamTypeFilter::ASYNC,
+ makeFlushCommands(false, false), false /*validatePositionIncrease*/);
std::shared_ptr<StateSequence> makeDrainPauseFlushOutCommands(bool isSync) {
using State = StreamDescriptor::State;
@@ -3910,10 +3965,12 @@
}
static const NamedCommandSequence kDrainPauseFlushOutSyncSeq =
std::make_tuple(std::string("DrainPauseFlush"), kStreamTransientStateTransitionDelayMs,
- StreamTypeFilter::SYNC, makeDrainPauseFlushOutCommands(true));
+ StreamTypeFilter::SYNC, makeDrainPauseFlushOutCommands(true),
+ false /*validatePositionIncrease*/);
static const NamedCommandSequence kDrainPauseFlushOutAsyncSeq =
std::make_tuple(std::string("DrainPauseFlush"), kStreamTransientStateTransitionDelayMs,
- StreamTypeFilter::ASYNC, makeDrainPauseFlushOutCommands(false));
+ StreamTypeFilter::ASYNC, makeDrainPauseFlushOutCommands(false),
+ false /*validatePositionIncrease*/);
// Note, this isn't the "official" enum printer, it is only used to make the test name suffix.
std::string PrintStreamFilterToString(StreamTypeFilter filter) {
@@ -3966,6 +4023,172 @@
android::PrintInstanceNameToString);
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AudioModulePatch);
+static std::vector<std::string> getRemoteSubmixModuleInstance() {
+ auto instances = android::getAidlHalInstanceNames(IModule::descriptor);
+ for (auto instance : instances) {
+ if (instance.find("r_submix") != std::string::npos)
+ return (std::vector<std::string>{instance});
+ }
+ return {};
+}
+
+template <typename Stream>
+class WithRemoteSubmix {
+ public:
+ WithRemoteSubmix() = default;
+ WithRemoteSubmix(AudioDeviceAddress address) : mAddress(address) {}
+ WithRemoteSubmix(const WithRemoteSubmix&) = delete;
+ WithRemoteSubmix& operator=(const WithRemoteSubmix&) = delete;
+ std::optional<AudioPort> getAudioPort() {
+ AudioDeviceType deviceType = IOTraits<Stream>::is_input ? AudioDeviceType::IN_SUBMIX
+ : AudioDeviceType::OUT_SUBMIX;
+ auto ports = mModuleConfig->getAudioPortsForDeviceTypes(
+ std::vector<AudioDeviceType>{deviceType},
+ AudioDeviceDescription::CONNECTION_VIRTUAL);
+ if (!ports.empty()) return ports.front();
+ return {};
+ }
+ /* Connect remote submix external device */
+ void SetUpPortConnection() {
+ auto port = getAudioPort();
+ ASSERT_TRUE(port.has_value()) << "Device AudioPort for remote submix not found";
+ if (mAddress.has_value()) {
+ port.value().ext.template get<AudioPortExt::Tag::device>().device.address =
+ mAddress.value();
+ } else {
+ port = GenerateUniqueDeviceAddress(port.value());
+ }
+ mConnectedPort = std::make_unique<WithDevicePortConnectedState>(port.value());
+ ASSERT_NO_FATAL_FAILURE(mConnectedPort->SetUp(mModule, mModuleConfig));
+ }
+ AudioDeviceAddress getAudioDeviceAddress() {
+ if (!mAddress.has_value()) {
+ mAddress = mConnectedPort->get()
+ .ext.template get<AudioPortExt::Tag::device>()
+ .device.address;
+ }
+ return mAddress.value();
+ }
+ /* Get mix port config for stream and setup patch for it. */
+ void SetupPatch() {
+ const auto portConfig =
+ mModuleConfig->getSingleConfigForMixPort(IOTraits<Stream>::is_input);
+ if (!portConfig.has_value()) {
+ LOG(DEBUG) << __func__ << ": portConfig not found";
+ mSkipTest = true;
+ return;
+ }
+ auto devicePortConfig = mModuleConfig->getSingleConfigForDevicePort(mConnectedPort->get());
+ mPatch = std::make_unique<WithAudioPatch>(IOTraits<Stream>::is_input, portConfig.value(),
+ devicePortConfig);
+ ASSERT_NO_FATAL_FAILURE(mPatch->SetUp(mModule));
+ }
+ void SetUp(IModule* module, ModuleConfig* moduleConfig) {
+ mModule = module;
+ mModuleConfig = moduleConfig;
+ ASSERT_NO_FATAL_FAILURE(SetUpPortConnection());
+ ASSERT_NO_FATAL_FAILURE(SetupPatch());
+ if (!mSkipTest) {
+ // open stream
+ mStream = std::make_unique<WithStream<Stream>>(
+ mPatch->getPortConfig(IOTraits<Stream>::is_input));
+ ASSERT_NO_FATAL_FAILURE(
+ mStream->SetUp(mModule, AudioCoreModuleBase::kDefaultBufferSizeFrames));
+ }
+ }
+ void sendBurstCommands() {
+ const StreamContext* context = mStream->getContext();
+ StreamLogicDefaultDriver driver(makeBurstCommands(true), context->getFrameSizeBytes());
+ typename IOTraits<Stream>::Worker worker(*context, &driver, mStream->getEventReceiver());
+
+ LOG(DEBUG) << __func__ << ": starting worker...";
+ ASSERT_TRUE(worker.start());
+ LOG(DEBUG) << __func__ << ": joining worker...";
+ worker.join();
+ EXPECT_FALSE(worker.hasError()) << worker.getError();
+ EXPECT_EQ("", driver.getUnexpectedStateTransition());
+ if (IOTraits<Stream>::is_input) {
+ EXPECT_TRUE(driver.hasObservablePositionIncrease());
+ }
+ EXPECT_FALSE(driver.hasRetrogradeObservablePosition());
+ }
+ bool skipTest() { return mSkipTest; }
+
+ private:
+ bool mSkipTest = false;
+ IModule* mModule = nullptr;
+ ModuleConfig* mModuleConfig = nullptr;
+ std::optional<AudioDeviceAddress> mAddress;
+ std::unique_ptr<WithDevicePortConnectedState> mConnectedPort;
+ std::unique_ptr<WithAudioPatch> mPatch;
+ std::unique_ptr<WithStream<Stream>> mStream;
+};
+
+class AudioModuleRemoteSubmix : public AudioCoreModule {
+ public:
+ void SetUp() override {
+ ASSERT_NO_FATAL_FAILURE(AudioCoreModule::SetUp());
+ ASSERT_NO_FATAL_FAILURE(SetUpModuleConfig());
+ }
+
+ void TearDown() override { ASSERT_NO_FATAL_FAILURE(TearDownImpl()); }
+};
+
+TEST_P(AudioModuleRemoteSubmix, OutputDoesNotBlockWhenNoInput) {
+ // open output stream
+ WithRemoteSubmix<IStreamOut> streamOut;
+ ASSERT_NO_FATAL_FAILURE(streamOut.SetUp(module.get(), moduleConfig.get()));
+ if (streamOut.skipTest()) {
+ GTEST_SKIP() << "No mix port for attached devices";
+ }
+ // write something to stream
+ ASSERT_NO_FATAL_FAILURE(streamOut.sendBurstCommands());
+}
+
+TEST_P(AudioModuleRemoteSubmix, OutputDoesNotBlockWhenInputStuck) {
+ // open output stream
+ WithRemoteSubmix<IStreamOut> streamOut;
+ ASSERT_NO_FATAL_FAILURE(streamOut.SetUp(module.get(), moduleConfig.get()));
+ if (streamOut.skipTest()) {
+ GTEST_SKIP() << "No mix port for attached devices";
+ }
+
+ // open input stream
+ WithRemoteSubmix<IStreamIn> streamIn(streamOut.getAudioDeviceAddress());
+ ASSERT_NO_FATAL_FAILURE(streamIn.SetUp(module.get(), moduleConfig.get()));
+ if (streamIn.skipTest()) {
+ GTEST_SKIP() << "No mix port for attached devices";
+ }
+
+ // write something to stream
+ ASSERT_NO_FATAL_FAILURE(streamOut.sendBurstCommands());
+}
+
+TEST_P(AudioModuleRemoteSubmix, OutputAndInput) {
+ // open output stream
+ WithRemoteSubmix<IStreamOut> streamOut;
+ ASSERT_NO_FATAL_FAILURE(streamOut.SetUp(module.get(), moduleConfig.get()));
+ if (streamOut.skipTest()) {
+ GTEST_SKIP() << "No mix port for attached devices";
+ }
+
+ // open input stream
+ WithRemoteSubmix<IStreamIn> streamIn(streamOut.getAudioDeviceAddress());
+ ASSERT_NO_FATAL_FAILURE(streamIn.SetUp(module.get(), moduleConfig.get()));
+ if (streamIn.skipTest()) {
+ GTEST_SKIP() << "No mix port for attached devices";
+ }
+
+ // write something to stream
+ ASSERT_NO_FATAL_FAILURE(streamOut.sendBurstCommands());
+ // read from input stream
+ ASSERT_NO_FATAL_FAILURE(streamIn.sendBurstCommands());
+}
+
+INSTANTIATE_TEST_SUITE_P(AudioModuleRemoteSubmixTest, AudioModuleRemoteSubmix,
+ ::testing::ValuesIn(getRemoteSubmixModuleInstance()));
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AudioModuleRemoteSubmix);
+
class TestExecutionTracer : public ::testing::EmptyTestEventListener {
public:
void OnTestStart(const ::testing::TestInfo& test_info) override {
diff --git a/audio/aidl/vts/VtsHalAudioCoreTargetTest.xml b/audio/aidl/vts/VtsHalAudioCoreTargetTest.xml
index dfc1039..9d3adc1 100644
--- a/audio/aidl/vts/VtsHalAudioCoreTargetTest.xml
+++ b/audio/aidl/vts/VtsHalAudioCoreTargetTest.xml
@@ -25,6 +25,11 @@
<option name="teardown-command" value="setprop vts.native_server.on 0"/>
</target_preparer>
+ <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+ <option name="cleanup" value="true" />
+ <option name="push" value="VtsHalAudioCoreTargetTest->/data/local/tmp/VtsHalAudioCoreTargetTest" />
+ </target_preparer>
+
<test class="com.android.tradefed.testtype.GTest" >
<option name="native-test-device-path" value="/data/local/tmp" />
<option name="module-name" value="VtsHalAudioCoreTargetTest" />
diff --git a/audio/aidl/vts/VtsHalAudioEffectFactoryTargetTest.cpp b/audio/aidl/vts/VtsHalAudioEffectFactoryTargetTest.cpp
index 9cd6c22..225640e 100644
--- a/audio/aidl/vts/VtsHalAudioEffectFactoryTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioEffectFactoryTargetTest.cpp
@@ -36,6 +36,11 @@
#include "EffectFactoryHelper.h"
#include "TestUtils.h"
+#include <system/audio_aidl_utils.h>
+
+using namespace android;
+using ::android::audio::utils::toString;
+
using namespace android;
using aidl::android::hardware::audio::effect::Descriptor;
@@ -93,7 +98,7 @@
std::shared_ptr<IEffect> effect;
EXPECT_STATUS(expectStatus, mEffectFactory->createEffect(uuid, &effect));
if (expectStatus == EX_NONE) {
- EXPECT_NE(effect, nullptr) << " null effect with uuid: " << uuid.toString();
+ EXPECT_NE(effect, nullptr) << " null effect with uuid: " << toString(uuid);
effects.push_back(std::move(effect));
}
}
@@ -129,17 +134,18 @@
/**
* @brief Check at least support list of effect must be supported by aosp:
* https://developer.android.com/reference/android/media/audiofx/AudioEffect
+ *
+ * For Android 13, they are: Equalizer, LoudnessEnhancer, Visualizer, and DynamicsProcessing.
+ * https://source.android.com/docs/compatibility/13/android-13-cdd#552_audio_effects
*/
-TEST_P(EffectFactoryTest, ExpectAllAospEffectTypes) {
+TEST_P(EffectFactoryTest, SupportMandatoryEffectTypes) {
std::vector<Descriptor> descs;
- std::set<AudioUuid> typeUuidSet(
- {aidl::android::hardware::audio::effect::getEffectTypeUuidBassBoost(),
- aidl::android::hardware::audio::effect::getEffectTypeUuidEqualizer(),
- aidl::android::hardware::audio::effect::getEffectTypeUuidEnvReverb(),
- aidl::android::hardware::audio::effect::getEffectTypeUuidPresetReverb(),
- aidl::android::hardware::audio::effect::getEffectTypeUuidDynamicsProcessing(),
- aidl::android::hardware::audio::effect::getEffectTypeUuidHapticGenerator(),
- aidl::android::hardware::audio::effect::getEffectTypeUuidVirtualizer()});
+ std::set<AudioUuid> typeUuidSet({
+ aidl::android::hardware::audio::effect::getEffectTypeUuidEqualizer(),
+ aidl::android::hardware::audio::effect::getEffectTypeUuidDynamicsProcessing(),
+ aidl::android::hardware::audio::effect::getEffectTypeUuidLoudnessEnhancer(),
+ aidl::android::hardware::audio::effect::getEffectTypeUuidVisualizer(),
+ });
EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &descs));
EXPECT_TRUE(descs.size() >= typeUuidSet.size());
@@ -148,7 +154,7 @@
}
std::string msg = " missing type UUID:\n";
for (const auto& uuid : typeUuidSet) {
- msg += (uuid.toString() + "\n");
+ msg += (toString(uuid) + "\n");
}
SCOPED_TRACE(msg);
EXPECT_EQ(0UL, typeUuidSet.size());
@@ -300,4 +306,4 @@
ABinderProcess_setThreadPoolMaxThreadCount(1);
ABinderProcess_startThreadPool();
return RUN_ALL_TESTS();
-}
\ No newline at end of file
+}
diff --git a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
index 436f2a3..1876756 100644
--- a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
@@ -42,6 +42,7 @@
using aidl::android::hardware::audio::effect::CommandId;
using aidl::android::hardware::audio::effect::Descriptor;
+using aidl::android::hardware::audio::effect::Flags;
using aidl::android::hardware::audio::effect::IEffect;
using aidl::android::hardware::audio::effect::IFactory;
using aidl::android::hardware::audio::effect::Parameter;
@@ -85,6 +86,14 @@
}
};
+class AudioEffectDataPathTest : public AudioEffectTest {
+ public:
+ void SetUp() override {
+ AudioEffectTest::SetUp();
+ SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
+ }
+};
+
TEST_P(AudioEffectTest, SetupAndTearDown) {
// Intentionally empty test body.
}
@@ -495,6 +504,11 @@
// Set and get AudioDeviceDescription in Parameter
TEST_P(AudioEffectTest, SetAndGetParameterDeviceDescription) {
+ if (!mDescriptor.common.flags.deviceIndication) {
+ GTEST_SKIP() << "Skipping test as effect does not support deviceIndication"
+ << mDescriptor.common.flags.toString();
+ }
+
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
ASSERT_NO_FATAL_FAILURE(open(mEffect));
@@ -518,6 +532,11 @@
// Set and get AudioMode in Parameter
TEST_P(AudioEffectTest, SetAndGetParameterAudioMode) {
+ if (!mDescriptor.common.flags.audioModeIndication) {
+ GTEST_SKIP() << "Skipping test as effect does not support audioModeIndication"
+ << mDescriptor.common.flags.toString();
+ }
+
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
ASSERT_NO_FATAL_FAILURE(open(mEffect));
@@ -538,6 +557,11 @@
// Set and get AudioSource in Parameter
TEST_P(AudioEffectTest, SetAndGetParameterAudioSource) {
+ if (!mDescriptor.common.flags.audioSourceIndication) {
+ GTEST_SKIP() << "Skipping test as effect does not support audioSourceIndication"
+ << mDescriptor.common.flags.toString();
+ }
+
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
ASSERT_NO_FATAL_FAILURE(open(mEffect));
@@ -558,6 +582,11 @@
// Set and get VolumeStereo in Parameter
TEST_P(AudioEffectTest, SetAndGetParameterVolume) {
+ if (mDescriptor.common.flags.volume == Flags::Volume::NONE) {
+ GTEST_SKIP() << "Skipping test as effect does not support volume"
+ << mDescriptor.common.flags.toString();
+ }
+
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
ASSERT_NO_FATAL_FAILURE(open(mEffect));
@@ -577,7 +606,8 @@
/// Data processing test
// Send data to effects and expect it to be consumed by checking statusMQ.
-TEST_P(AudioEffectTest, ConsumeDataInProcessingState) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ConsumeDataInProcessingState) {
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
Parameter::Common common = EffectHelper::createParamCommon(
@@ -610,7 +640,8 @@
}
// Send data to effects and expect it to be consumed after effect restart.
-TEST_P(AudioEffectTest, ConsumeDataAfterRestart) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ConsumeDataAfterRestart) {
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
Parameter::Common common = EffectHelper::createParamCommon(
@@ -649,7 +680,8 @@
}
// Send data to IDLE effects and expect it to be consumed after effect start.
-TEST_P(AudioEffectTest, SendDataAtIdleAndConsumeDataInProcessing) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, SendDataAtIdleAndConsumeDataInProcessing) {
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
Parameter::Common common = EffectHelper::createParamCommon(
@@ -682,7 +714,8 @@
}
// Send data multiple times.
-TEST_P(AudioEffectTest, ProcessDataMultipleTimes) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ProcessDataMultipleTimes) {
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
Parameter::Common common = EffectHelper::createParamCommon(
@@ -721,7 +754,8 @@
}
// Send data to processing state effects, stop, and restart.
-TEST_P(AudioEffectTest, ConsumeDataAndRestart) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ConsumeDataAndRestart) {
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
Parameter::Common common = EffectHelper::createParamCommon(
@@ -762,7 +796,8 @@
}
// Send data to closed effects and expect it not be consumed.
-TEST_P(AudioEffectTest, NotConsumeDataByClosedEffect) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, NotConsumeDataByClosedEffect) {
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
Parameter::Common common = EffectHelper::createParamCommon(
@@ -788,7 +823,8 @@
}
// Send data to multiple effects.
-TEST_P(AudioEffectTest, ConsumeDataMultipleEffects) {
+// Effects exposing bypass flags or operating in offload mode will be skipped.
+TEST_P(AudioEffectDataPathTest, ConsumeDataMultipleEffects) {
std::shared_ptr<IEffect> effect1, effect2;
ASSERT_NO_FATAL_FAILURE(create(mFactory, effect1, mDescriptor));
ASSERT_NO_FATAL_FAILURE(create(mFactory, effect2, mDescriptor));
@@ -848,16 +884,27 @@
EffectFactoryHelper::getAllEffectDescriptors(IFactory::descriptor))),
[](const testing::TestParamInfo<AudioEffectTest::ParamType>& info) {
auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_TYPE_" +
- descriptor.common.id.type.toString() + "_UUID_" +
- descriptor.common.id.uuid.toString();
+ std::string name = getPrefix(descriptor);
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
});
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AudioEffectTest);
+INSTANTIATE_TEST_SUITE_P(
+ SingleEffectInstanceTest, AudioEffectDataPathTest,
+ ::testing::Combine(testing::ValuesIn(
+ EffectFactoryHelper::getAllEffectDescriptors(IFactory::descriptor))),
+ [](const testing::TestParamInfo<AudioEffectDataPathTest::ParamType>& info) {
+ auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
+ std::string name = getPrefix(descriptor);
+ std::replace_if(
+ name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
+ return name;
+ });
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AudioEffectDataPathTest);
+
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
ABinderProcess_setThreadPoolMaxThreadCount(1);
diff --git a/audio/aidl/vts/VtsHalBassBoostTargetTest.cpp b/audio/aidl/vts/VtsHalBassBoostTargetTest.cpp
index 9cfdc50..afddb84 100644
--- a/audio/aidl/vts/VtsHalBassBoostTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalBassBoostTargetTest.cpp
@@ -145,9 +145,7 @@
[](const testing::TestParamInfo<BassBoostParamTest::ParamType>& info) {
auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
std::string strength = std::to_string(std::get<PARAM_STRENGTH>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_strength_" + strength;
+ std::string name = getPrefix(descriptor) + "_strength_" + strength;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalDownmixTargetTest.cpp b/audio/aidl/vts/VtsHalDownmixTargetTest.cpp
index 5aeebde..7a2f31b 100644
--- a/audio/aidl/vts/VtsHalDownmixTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalDownmixTargetTest.cpp
@@ -126,9 +126,7 @@
[](const testing::TestParamInfo<DownmixParamTest::ParamType>& info) {
auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
std::string type = std::to_string(static_cast<int>(std::get<PARAM_TYPE>(info.param)));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_type" + type;
+ std::string name = getPrefix(descriptor) + "_type" + type;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalDynamicsProcessingTest.cpp b/audio/aidl/vts/VtsHalDynamicsProcessingTest.cpp
index 033e3b5..5509c76 100644
--- a/audio/aidl/vts/VtsHalDynamicsProcessingTest.cpp
+++ b/audio/aidl/vts/VtsHalDynamicsProcessingTest.cpp
@@ -513,9 +513,7 @@
auto descriptor = std::get<ENGINE_TEST_INSTANCE_NAME>(info.param).second;
DynamicsProcessing::EngineArchitecture cfg;
fillEngineArchConfig(cfg, info.param);
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_Cfg_" + cfg.toString();
+ std::string name = getPrefix(descriptor) + "_Cfg_" + cfg.toString();
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalEnvironmentalReverbTargetTest.cpp b/audio/aidl/vts/VtsHalEnvironmentalReverbTargetTest.cpp
index 05c2c5b..f2ef185 100644
--- a/audio/aidl/vts/VtsHalEnvironmentalReverbTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalEnvironmentalReverbTargetTest.cpp
@@ -209,9 +209,7 @@
auto descriptor = std::get<0>(info.param).second;
std::string roomLevel = std::to_string(std::get<1>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_roomLevel" + roomLevel;
+ std::string name = getPrefix(descriptor) + "_roomLevel" + roomLevel;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalEqualizerTargetTest.cpp b/audio/aidl/vts/VtsHalEqualizerTargetTest.cpp
index 716a2c6..37e7c0a 100644
--- a/audio/aidl/vts/VtsHalEqualizerTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalEqualizerTargetTest.cpp
@@ -209,9 +209,7 @@
auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
std::string bandLevel =
::android::internal::ToString(std::get<PARAM_BAND_LEVEL>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_preset_" +
+ std::string name = getPrefix(descriptor) + "_preset_" +
std::to_string(std::get<PARAM_PRESET>(info.param)) + "_bandLevel_" +
bandLevel;
std::replace_if(
diff --git a/audio/aidl/vts/VtsHalHapticGeneratorTargetTest.cpp b/audio/aidl/vts/VtsHalHapticGeneratorTargetTest.cpp
index 7c79d1b..b33234b 100644
--- a/audio/aidl/vts/VtsHalHapticGeneratorTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalHapticGeneratorTargetTest.cpp
@@ -195,12 +195,10 @@
std::to_string(std::get<PARAM_VIBRATION_INFORMATION_Q_FACTOR>(info.param));
std::string maxAmplitude =
std::to_string(std::get<PARAM_VIBRATION_INFORMATION_MAX_AMPLITUDE>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_hapticScaleId" +
- hapticScaleID + "_hapticScaleVibScale" + hapticScaleVibScale +
- "_resonantFrequency" + resonantFrequency + "_qFactor" + qFactor +
- "_maxAmplitude" + maxAmplitude;
+ std::string name = getPrefix(descriptor) + "_hapticScaleId" + hapticScaleID +
+ "_hapticScaleVibScale" + hapticScaleVibScale + "_resonantFrequency" +
+ resonantFrequency + "_qFactor" + qFactor + "_maxAmplitude" +
+ maxAmplitude;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
@@ -210,7 +208,7 @@
HapticGeneratorInvalidTest, HapticGeneratorParamTest,
::testing::Combine(testing::ValuesIn(EffectFactoryHelper::getAllEffectDescriptors(
IFactory::descriptor, getEffectTypeUuidHapticGenerator())),
- testing::Values(MIN_ID - 1),
+ testing::Values(MIN_ID),
testing::Values(HapticGenerator::VibratorScale::NONE),
testing::Values(MIN_FLOAT), testing::Values(MIN_FLOAT),
testing::Values(MIN_FLOAT)),
diff --git a/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp b/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp
index 96b048e..cbb80a9 100644
--- a/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp
@@ -131,9 +131,7 @@
[](const testing::TestParamInfo<LoudnessEnhancerParamTest::ParamType>& info) {
auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
std::string gainMb = std::to_string(std::get<PARAM_GAIN_MB>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_gainMb_" + gainMb;
+ std::string name = getPrefix(descriptor) + "_gainMb_" + gainMb;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalNSTargetTest.cpp b/audio/aidl/vts/VtsHalNSTargetTest.cpp
index 5525c80..624d5d2 100644
--- a/audio/aidl/vts/VtsHalNSTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalNSTargetTest.cpp
@@ -48,7 +48,7 @@
ASSERT_NE(nullptr, mFactory);
ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
- Parameter::Specific specific = getDefaultParamSpecific();
+ std::optional<Parameter::Specific> specific = getDefaultParamSpecific();
Parameter::Common common = EffectHelper::createParamCommon(
0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
@@ -62,9 +62,13 @@
ASSERT_NO_FATAL_FAILURE(destroy(mFactory, mEffect));
}
- Parameter::Specific getDefaultParamSpecific() {
+ std::optional<Parameter::Specific> getDefaultParamSpecific() {
NoiseSuppression ns =
NoiseSuppression::make<NoiseSuppression::level>(NoiseSuppression::Level::MEDIUM);
+ if (!isParameterValid<NoiseSuppression, Range::noiseSuppression>(ns, mDescriptor)) {
+ return std::nullopt;
+ }
+
Parameter::Specific specific =
Parameter::Specific::make<Parameter::Specific::noiseSuppression>(ns);
return specific;
@@ -85,7 +89,9 @@
// validate parameter
Descriptor desc;
ASSERT_STATUS(EX_NONE, mEffect->getDescriptor(&desc));
- const binder_exception_t expected = EX_NONE;
+ const bool valid =
+ isParameterValid<NoiseSuppression, Range::noiseSuppression>(ns, desc);
+ const binder_exception_t expected = valid ? EX_NONE : EX_ILLEGAL_ARGUMENT;
// set parameter
Parameter expectParam;
@@ -155,10 +161,7 @@
std::get<PARAM_LEVEL>(info.param));
std::string type = aidl::android::hardware::audio::effect::toString(
std::get<PARAM_TYPE>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_level_" + level + "_type_" +
- type;
+ std::string name = getPrefix(descriptor) + "_level_" + level + "_type_" + type;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalPresetReverbTargetTest.cpp b/audio/aidl/vts/VtsHalPresetReverbTargetTest.cpp
index 8fb4ebf..3056c6c 100644
--- a/audio/aidl/vts/VtsHalPresetReverbTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalPresetReverbTargetTest.cpp
@@ -137,9 +137,7 @@
auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
std::string preset =
std::to_string(static_cast<int>(std::get<PARAM_PRESETS>(info.param)));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_preset" + preset;
+ std::string name = getPrefix(descriptor) + "_preset" + preset;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalVirtualizerTargetTest.cpp b/audio/aidl/vts/VtsHalVirtualizerTargetTest.cpp
index 6b1da63..07a9fa4 100644
--- a/audio/aidl/vts/VtsHalVirtualizerTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalVirtualizerTargetTest.cpp
@@ -141,9 +141,7 @@
[](const testing::TestParamInfo<VirtualizerParamTest::ParamType>& info) {
auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
std::string strength = std::to_string(std::get<PARAM_STRENGTH>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_strength" + strength;
+ std::string name = getPrefix(descriptor) + "_strength" + strength;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/aidl/vts/VtsHalVisualizerTargetTest.cpp b/audio/aidl/vts/VtsHalVisualizerTargetTest.cpp
index f41ba30..903ba69 100644
--- a/audio/aidl/vts/VtsHalVisualizerTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalVisualizerTargetTest.cpp
@@ -195,9 +195,7 @@
std::get<PARAM_MEASUREMENT_MODE>(info.param));
std::string latency = std::to_string(std::get<PARAM_LATENCY>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_captureSize" + captureSize +
+ std::string name = getPrefix(descriptor) + "_captureSize" + captureSize +
"_scalingMode" + scalingMode + "_measurementMode" + measurementMode +
"_latency" + latency;
std::replace_if(
diff --git a/audio/aidl/vts/VtsHalVolumeTargetTest.cpp b/audio/aidl/vts/VtsHalVolumeTargetTest.cpp
index 90b7f37..0b5b9fc 100644
--- a/audio/aidl/vts/VtsHalVolumeTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalVolumeTargetTest.cpp
@@ -149,10 +149,7 @@
auto descriptor = std::get<PARAM_INSTANCE_NAME>(info.param).second;
std::string level = std::to_string(std::get<PARAM_LEVEL>(info.param));
std::string mute = std::to_string(std::get<PARAM_MUTE>(info.param));
- std::string name = "Implementor_" + descriptor.common.implementor + "_name_" +
- descriptor.common.name + "_UUID_" +
- descriptor.common.id.uuid.toString() + "_level" + level + "_mute" +
- mute;
+ std::string name = getPrefix(descriptor) + "_level" + level + "_mute" + mute;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/automotive/vehicle/aidl/impl/fake_impl/GeneratorHub/include/LinearFakeValueGenerator.h b/automotive/vehicle/aidl/impl/fake_impl/GeneratorHub/include/LinearFakeValueGenerator.h
index d2b701d..2378676 100644
--- a/automotive/vehicle/aidl/impl/fake_impl/GeneratorHub/include/LinearFakeValueGenerator.h
+++ b/automotive/vehicle/aidl/impl/fake_impl/GeneratorHub/include/LinearFakeValueGenerator.h
@@ -57,7 +57,7 @@
float dispersion; // Defines minimum and maximum value based on initial value.
float increment; // Value that we will be added to currentValue with each timer tick.
int64_t interval;
- long lastEventTimestamp;
+ int64_t lastEventTimestamp;
};
GeneratorCfg mGenCfg;
diff --git a/automotive/vehicle/aidl/impl/fake_impl/GeneratorHub/src/LinearFakeValueGenerator.cpp b/automotive/vehicle/aidl/impl/fake_impl/GeneratorHub/src/LinearFakeValueGenerator.cpp
index 9133144..fe08dcf 100644
--- a/automotive/vehicle/aidl/impl/fake_impl/GeneratorHub/src/LinearFakeValueGenerator.cpp
+++ b/automotive/vehicle/aidl/impl/fake_impl/GeneratorHub/src/LinearFakeValueGenerator.cpp
@@ -86,7 +86,7 @@
if (mGenCfg.lastEventTimestamp == 0) {
mGenCfg.lastEventTimestamp = elapsedRealtimeNano();
} else {
- long nextEventTime = mGenCfg.lastEventTimestamp + mGenCfg.interval;
+ int64_t nextEventTime = mGenCfg.lastEventTimestamp + mGenCfg.interval;
// Prevent overflow.
assert(nextEventTime > mGenCfg.lastEventTimestamp);
mGenCfg.lastEventTimestamp = nextEventTime;
diff --git a/automotive/vehicle/aidl/impl/fake_impl/hardware/src/FakeVehicleHardware.cpp b/automotive/vehicle/aidl/impl/fake_impl/hardware/src/FakeVehicleHardware.cpp
index 3f5e4c4..b5b325c 100644
--- a/automotive/vehicle/aidl/impl/fake_impl/hardware/src/FakeVehicleHardware.cpp
+++ b/automotive/vehicle/aidl/impl/fake_impl/hardware/src/FakeVehicleHardware.cpp
@@ -990,9 +990,11 @@
} else if (EqualsIgnoreCase(option, "--genTestVendorConfigs")) {
mAddExtraTestVendorConfigs = true;
result.refreshPropertyConfigs = true;
+ result.buffer = "successfully generated vendor configs";
} else if (EqualsIgnoreCase(option, "--restoreVendorConfigs")) {
mAddExtraTestVendorConfigs = false;
result.refreshPropertyConfigs = true;
+ result.buffer = "successfully restored vendor configs";
} else {
result.buffer = StringPrintf("Invalid option: %s\n", option.c_str());
}
@@ -1808,6 +1810,7 @@
void FakeVehicleHardware::registerOnPropertySetErrorEvent(
std::unique_ptr<const PropertySetErrorCallback> callback) {
+ // In FakeVehicleHardware, we will never use mOnPropertySetErrorCallback.
if (mOnPropertySetErrorCallback != nullptr) {
ALOGE("registerOnPropertySetErrorEvent must only be called once");
return;
diff --git a/automotive/vehicle/aidl/impl/vhal/include/ConnectedClient.h b/automotive/vehicle/aidl/impl/vhal/include/ConnectedClient.h
index 2e7298f..b3f4a0f 100644
--- a/automotive/vehicle/aidl/impl/vhal/include/ConnectedClient.h
+++ b/automotive/vehicle/aidl/impl/vhal/include/ConnectedClient.h
@@ -107,12 +107,18 @@
// Gets the callback to be called when the request for this client has finished.
std::shared_ptr<const IVehicleHardware::GetValuesCallback> getResultCallback();
- // Marshals the updated values into largeParcelable and sents it through {@code onPropertyEvent}
+ // Marshals the updated values into largeParcelable and sends it through {@code onPropertyEvent}
// callback.
static void sendUpdatedValues(
CallbackType callback,
std::vector<aidl::android::hardware::automotive::vehicle::VehiclePropValue>&&
updatedValues);
+ // Marshals the set property error events into largeParcelable and sends it through
+ // {@code onPropertySetError} callback.
+ static void sendPropertySetErrors(
+ CallbackType callback,
+ std::vector<aidl::android::hardware::automotive::vehicle::VehiclePropError>&&
+ vehiclePropErrors);
protected:
// Gets the callback to be called when the request for this client has timeout.
diff --git a/automotive/vehicle/aidl/impl/vhal/include/DefaultVehicleHal.h b/automotive/vehicle/aidl/impl/vhal/include/DefaultVehicleHal.h
index 2c2cf1a..74ad7ea 100644
--- a/automotive/vehicle/aidl/impl/vhal/include/DefaultVehicleHal.h
+++ b/automotive/vehicle/aidl/impl/vhal/include/DefaultVehicleHal.h
@@ -249,10 +249,14 @@
const CallbackType& callback, std::shared_ptr<PendingRequestPool> pendingRequestPool);
static void onPropertyChangeEvent(
- std::weak_ptr<SubscriptionManager> subscriptionManager,
+ const std::weak_ptr<SubscriptionManager>& subscriptionManager,
const std::vector<aidl::android::hardware::automotive::vehicle::VehiclePropValue>&
updatedValues);
+ static void onPropertySetErrorEvent(
+ const std::weak_ptr<SubscriptionManager>& subscriptionManager,
+ const std::vector<SetValueErrorEvent>& errorEvents);
+
static void checkHealth(IVehicleHardware* hardware,
std::weak_ptr<SubscriptionManager> subscriptionManager);
diff --git a/automotive/vehicle/aidl/impl/vhal/include/SubscriptionManager.h b/automotive/vehicle/aidl/impl/vhal/include/SubscriptionManager.h
index 14799d9..301d56c 100644
--- a/automotive/vehicle/aidl/impl/vhal/include/SubscriptionManager.h
+++ b/automotive/vehicle/aidl/impl/vhal/include/SubscriptionManager.h
@@ -99,6 +99,12 @@
const std::vector<aidl::android::hardware::automotive::vehicle::VehiclePropValue>&
updatedValues);
+ // For a list of set property error events, returns a map that maps clients subscribing to the
+ // properties to a list of errors for each client.
+ std::unordered_map<CallbackType,
+ std::vector<aidl::android::hardware::automotive::vehicle::VehiclePropError>>
+ getSubscribedClientsForErrorEvents(const std::vector<SetValueErrorEvent>& errorEvents);
+
// Checks whether the sample rate is valid.
static bool checkSampleRateHz(float sampleRateHz);
diff --git a/automotive/vehicle/aidl/impl/vhal/src/ConnectedClient.cpp b/automotive/vehicle/aidl/impl/vhal/src/ConnectedClient.cpp
index 81d231c..fb23a25 100644
--- a/automotive/vehicle/aidl/impl/vhal/src/ConnectedClient.cpp
+++ b/automotive/vehicle/aidl/impl/vhal/src/ConnectedClient.cpp
@@ -38,6 +38,8 @@
using ::aidl::android::hardware::automotive::vehicle::SetValueResult;
using ::aidl::android::hardware::automotive::vehicle::SetValueResults;
using ::aidl::android::hardware::automotive::vehicle::StatusCode;
+using ::aidl::android::hardware::automotive::vehicle::VehiclePropError;
+using ::aidl::android::hardware::automotive::vehicle::VehiclePropErrors;
using ::aidl::android::hardware::automotive::vehicle::VehiclePropValue;
using ::aidl::android::hardware::automotive::vehicle::VehiclePropValues;
using ::android::base::Result;
@@ -300,7 +302,34 @@
if (ScopedAStatus callbackStatus =
callback->onPropertyEvent(vehiclePropValues, sharedMemoryFileCount);
!callbackStatus.isOk()) {
- ALOGE("subscribe: failed to call UpdateValues callback, client ID: %p, error: %s, "
+ ALOGE("subscribe: failed to call onPropertyEvent callback, client ID: %p, error: %s, "
+ "exception: %d, service specific error: %d",
+ callback->asBinder().get(), callbackStatus.getMessage(),
+ callbackStatus.getExceptionCode(), callbackStatus.getServiceSpecificError());
+ }
+}
+
+void SubscriptionClient::sendPropertySetErrors(std::shared_ptr<IVehicleCallback> callback,
+ std::vector<VehiclePropError>&& vehiclePropErrors) {
+ if (vehiclePropErrors.empty()) {
+ return;
+ }
+
+ VehiclePropErrors vehiclePropErrorsLargeParcelable;
+ ScopedAStatus status = vectorToStableLargeParcelable(std::move(vehiclePropErrors),
+ &vehiclePropErrorsLargeParcelable);
+ if (!status.isOk()) {
+ int statusCode = status.getServiceSpecificError();
+ ALOGE("subscribe: failed to marshal result into large parcelable, error: "
+ "%s, code: %d",
+ status.getMessage(), statusCode);
+ return;
+ }
+
+ if (ScopedAStatus callbackStatus =
+ callback->onPropertySetError(vehiclePropErrorsLargeParcelable);
+ !callbackStatus.isOk()) {
+ ALOGE("subscribe: failed to call onPropertySetError callback, client ID: %p, error: %s, "
"exception: %d, service specific error: %d",
callback->asBinder().get(), callbackStatus.getMessage(),
callbackStatus.getExceptionCode(), callbackStatus.getServiceSpecificError());
diff --git a/automotive/vehicle/aidl/impl/vhal/src/DefaultVehicleHal.cpp b/automotive/vehicle/aidl/impl/vhal/src/DefaultVehicleHal.cpp
index 98cfc39..0d5c070 100644
--- a/automotive/vehicle/aidl/impl/vhal/src/DefaultVehicleHal.cpp
+++ b/automotive/vehicle/aidl/impl/vhal/src/DefaultVehicleHal.cpp
@@ -144,6 +144,11 @@
[subscriptionManagerCopy](std::vector<VehiclePropValue> updatedValues) {
onPropertyChangeEvent(subscriptionManagerCopy, updatedValues);
}));
+ mVehicleHardware->registerOnPropertySetErrorEvent(
+ std::make_unique<IVehicleHardware::PropertySetErrorCallback>(
+ [subscriptionManagerCopy](std::vector<SetValueErrorEvent> errorEvents) {
+ onPropertySetErrorEvent(subscriptionManagerCopy, errorEvents);
+ }));
// Register heartbeat event.
mRecurrentAction = std::make_shared<std::function<void()>>(
@@ -177,7 +182,7 @@
}
void DefaultVehicleHal::onPropertyChangeEvent(
- std::weak_ptr<SubscriptionManager> subscriptionManager,
+ const std::weak_ptr<SubscriptionManager>& subscriptionManager,
const std::vector<VehiclePropValue>& updatedValues) {
auto manager = subscriptionManager.lock();
if (manager == nullptr) {
@@ -194,6 +199,20 @@
}
}
+void DefaultVehicleHal::onPropertySetErrorEvent(
+ const std::weak_ptr<SubscriptionManager>& subscriptionManager,
+ const std::vector<SetValueErrorEvent>& errorEvents) {
+ auto manager = subscriptionManager.lock();
+ if (manager == nullptr) {
+ ALOGW("the SubscriptionManager is destroyed, DefaultVehicleHal is ending");
+ return;
+ }
+ auto vehiclePropErrorsByClient = manager->getSubscribedClientsForErrorEvents(errorEvents);
+ for (auto& [callback, vehiclePropErrors] : vehiclePropErrorsByClient) {
+ SubscriptionClient::sendPropertySetErrors(callback, std::move(vehiclePropErrors));
+ }
+}
+
template <class T>
std::shared_ptr<T> DefaultVehicleHal::getOrCreateClient(
std::unordered_map<const AIBinder*, std::shared_ptr<T>>* clients,
@@ -692,15 +711,19 @@
// Create a new SubscriptionClient if there isn't an existing one.
mSubscriptionClients->maybeAddClient(callback);
- // Since we have already check the sample rates, the following functions must succeed.
if (!onChangeSubscriptions.empty()) {
- return toScopedAStatus(mSubscriptionManager->subscribe(callback, onChangeSubscriptions,
- /*isContinuousProperty=*/false));
+ auto result = mSubscriptionManager->subscribe(callback, onChangeSubscriptions,
+ /*isContinuousProperty=*/false);
+ if (!result.ok()) {
+ return toScopedAStatus(result);
+ }
}
if (!continuousSubscriptions.empty()) {
- return toScopedAStatus(mSubscriptionManager->subscribe(callback,
- continuousSubscriptions,
- /*isContinuousProperty=*/true));
+ auto result = mSubscriptionManager->subscribe(callback, continuousSubscriptions,
+ /*isContinuousProperty=*/true);
+ if (!result.ok()) {
+ return toScopedAStatus(result);
+ }
}
}
return ScopedAStatus::ok();
diff --git a/automotive/vehicle/aidl/impl/vhal/src/SubscriptionManager.cpp b/automotive/vehicle/aidl/impl/vhal/src/SubscriptionManager.cpp
index bba730f..1f2690e 100644
--- a/automotive/vehicle/aidl/impl/vhal/src/SubscriptionManager.cpp
+++ b/automotive/vehicle/aidl/impl/vhal/src/SubscriptionManager.cpp
@@ -36,6 +36,7 @@
using ::aidl::android::hardware::automotive::vehicle::IVehicleCallback;
using ::aidl::android::hardware::automotive::vehicle::StatusCode;
using ::aidl::android::hardware::automotive::vehicle::SubscribeOptions;
+using ::aidl::android::hardware::automotive::vehicle::VehiclePropError;
using ::aidl::android::hardware::automotive::vehicle::VehiclePropValue;
using ::android::base::Error;
using ::android::base::Result;
@@ -269,6 +270,32 @@
return clients;
}
+std::unordered_map<std::shared_ptr<IVehicleCallback>, std::vector<VehiclePropError>>
+SubscriptionManager::getSubscribedClientsForErrorEvents(
+ const std::vector<SetValueErrorEvent>& errorEvents) {
+ std::scoped_lock<std::mutex> lockGuard(mLock);
+ std::unordered_map<std::shared_ptr<IVehicleCallback>, std::vector<VehiclePropError>> clients;
+
+ for (const auto& errorEvent : errorEvents) {
+ PropIdAreaId propIdAreaId{
+ .propId = errorEvent.propId,
+ .areaId = errorEvent.areaId,
+ };
+ if (mClientsByPropIdArea.find(propIdAreaId) == mClientsByPropIdArea.end()) {
+ continue;
+ }
+
+ for (const auto& [_, client] : mClientsByPropIdArea[propIdAreaId]) {
+ clients[client].push_back({
+ .propId = errorEvent.propId,
+ .areaId = errorEvent.areaId,
+ .errorCode = errorEvent.errorCode,
+ });
+ }
+ }
+ return clients;
+}
+
bool SubscriptionManager::isEmpty() {
std::scoped_lock<std::mutex> lockGuard(mLock);
return mSubscribedPropsByClient.empty() && mClientsByPropIdArea.empty();
diff --git a/automotive/vehicle/aidl/impl/vhal/test/DefaultVehicleHalTest.cpp b/automotive/vehicle/aidl/impl/vhal/test/DefaultVehicleHalTest.cpp
index 05e569a..96b71f0 100644
--- a/automotive/vehicle/aidl/impl/vhal/test/DefaultVehicleHalTest.cpp
+++ b/automotive/vehicle/aidl/impl/vhal/test/DefaultVehicleHalTest.cpp
@@ -62,6 +62,7 @@
using ::aidl::android::hardware::automotive::vehicle::VehicleAreaWindow;
using ::aidl::android::hardware::automotive::vehicle::VehiclePropConfig;
using ::aidl::android::hardware::automotive::vehicle::VehiclePropConfigs;
+using ::aidl::android::hardware::automotive::vehicle::VehiclePropError;
using ::aidl::android::hardware::automotive::vehicle::VehiclePropErrors;
using ::aidl::android::hardware::automotive::vehicle::VehicleProperty;
using ::aidl::android::hardware::automotive::vehicle::VehiclePropertyAccess;
@@ -1653,6 +1654,63 @@
ASSERT_EQ(msg.find("Vehicle HAL State: "), std::string::npos);
}
+TEST_F(DefaultVehicleHalTest, testOnPropertySetErrorEvent) {
+ std::vector<SubscribeOptions> options = {
+ {
+ .propId = GLOBAL_ON_CHANGE_PROP,
+ .areaIds = {0},
+ },
+ {
+ .propId = GLOBAL_CONTINUOUS_PROP,
+ .areaIds = {0},
+ .sampleRate = 1,
+ },
+ };
+ auto status = getClient()->subscribe(getCallbackClient(), options, 0);
+ ASSERT_TRUE(status.isOk()) << "subscribe failed: " << status.getMessage();
+ std::vector<SetValueErrorEvent> errorEvents = {
+ {
+ .propId = GLOBAL_ON_CHANGE_PROP,
+ .areaId = 0,
+ .errorCode = StatusCode::INTERNAL_ERROR,
+ },
+ {
+ .propId = GLOBAL_ON_CHANGE_PROP,
+ .areaId = 0,
+ .errorCode = StatusCode::ACCESS_DENIED,
+ },
+ {
+ .propId = GLOBAL_CONTINUOUS_PROP,
+ .areaId = 0,
+ .errorCode = StatusCode::INVALID_ARG,
+ },
+ };
+ std::vector<VehiclePropError> expectedResults = {
+ {
+ .propId = GLOBAL_ON_CHANGE_PROP,
+ .areaId = 0,
+ .errorCode = StatusCode::INTERNAL_ERROR,
+ },
+ {
+ .propId = GLOBAL_ON_CHANGE_PROP,
+ .areaId = 0,
+ .errorCode = StatusCode::ACCESS_DENIED,
+ },
+ {
+ .propId = GLOBAL_CONTINUOUS_PROP,
+ .areaId = 0,
+ .errorCode = StatusCode::INVALID_ARG,
+ },
+ };
+ getHardware()->sendOnPropertySetErrorEvent(errorEvents);
+
+ ASSERT_EQ(getCallback()->countOnPropertySetErrorResults(), 1u);
+ auto maybeVehiclePropErrors = getCallback()->nextOnPropertySetErrorResults();
+ ASSERT_TRUE(maybeVehiclePropErrors.has_value());
+ const auto& vehiclePropErrors = maybeVehiclePropErrors.value();
+ ASSERT_THAT(vehiclePropErrors.payloads, UnorderedElementsAreArray(expectedResults));
+}
+
} // namespace vehicle
} // namespace automotive
} // namespace hardware
diff --git a/automotive/vehicle/aidl/impl/vhal/test/MockVehicleCallback.cpp b/automotive/vehicle/aidl/impl/vhal/test/MockVehicleCallback.cpp
index f51ce5c..54fede1 100644
--- a/automotive/vehicle/aidl/impl/vhal/test/MockVehicleCallback.cpp
+++ b/automotive/vehicle/aidl/impl/vhal/test/MockVehicleCallback.cpp
@@ -81,8 +81,14 @@
return result;
}
-ScopedAStatus MockVehicleCallback::onPropertySetError(const VehiclePropErrors&) {
- return ScopedAStatus::ok();
+ScopedAStatus MockVehicleCallback::onPropertySetError(const VehiclePropErrors& results) {
+ ScopedAStatus result;
+ {
+ std::scoped_lock<std::mutex> lockGuard(mLock);
+ result = storeResults(results, &mOnPropertySetErrorResults);
+ }
+ mCond.notify_all();
+ return result;
}
std::optional<GetValueResults> MockVehicleCallback::nextGetValueResults() {
@@ -105,6 +111,16 @@
return mOnPropertyEventResults.size();
}
+std::optional<VehiclePropErrors> MockVehicleCallback::nextOnPropertySetErrorResults() {
+ std::scoped_lock<std::mutex> lockGuard(mLock);
+ return pop(mOnPropertySetErrorResults);
+}
+
+size_t MockVehicleCallback::countOnPropertySetErrorResults() {
+ std::scoped_lock<std::mutex> lockGuard(mLock);
+ return mOnPropertySetErrorResults.size();
+}
+
bool MockVehicleCallback::waitForSetValueResults(size_t size, size_t timeoutInNano) {
std::unique_lock lk(mLock);
return mCond.wait_for(lk, std::chrono::nanoseconds(timeoutInNano), [this, size] {
diff --git a/automotive/vehicle/aidl/impl/vhal/test/MockVehicleCallback.h b/automotive/vehicle/aidl/impl/vhal/test/MockVehicleCallback.h
index f17b273..1545eae 100644
--- a/automotive/vehicle/aidl/impl/vhal/test/MockVehicleCallback.h
+++ b/automotive/vehicle/aidl/impl/vhal/test/MockVehicleCallback.h
@@ -63,6 +63,9 @@
nextSetValueResults();
std::optional<aidl::android::hardware::automotive::vehicle::VehiclePropValues>
nextOnPropertyEventResults();
+ size_t countOnPropertySetErrorResults();
+ std::optional<aidl::android::hardware::automotive::vehicle::VehiclePropErrors>
+ nextOnPropertySetErrorResults();
size_t countOnPropertyEventResults();
bool waitForSetValueResults(size_t size, size_t timeoutInNano);
bool waitForGetValueResults(size_t size, size_t timeoutInNano);
@@ -77,6 +80,8 @@
std::list<aidl::android::hardware::automotive::vehicle::VehiclePropValues>
mOnPropertyEventResults GUARDED_BY(mLock);
int32_t mSharedMemoryFileCount GUARDED_BY(mLock);
+ std::list<aidl::android::hardware::automotive::vehicle::VehiclePropErrors>
+ mOnPropertySetErrorResults GUARDED_BY(mLock);
};
} // namespace vehicle
diff --git a/automotive/vehicle/aidl/impl/vhal/test/MockVehicleHardware.cpp b/automotive/vehicle/aidl/impl/vhal/test/MockVehicleHardware.cpp
index 4df4e1a..ba0d33d 100644
--- a/automotive/vehicle/aidl/impl/vhal/test/MockVehicleHardware.cpp
+++ b/automotive/vehicle/aidl/impl/vhal/test/MockVehicleHardware.cpp
@@ -131,8 +131,9 @@
}
void MockVehicleHardware::registerOnPropertySetErrorEvent(
- std::unique_ptr<const PropertySetErrorCallback>) {
- // TODO(b/200737967): mock this.
+ std::unique_ptr<const PropertySetErrorCallback> callback) {
+ std::scoped_lock<std::mutex> lockGuard(mLock);
+ mPropertySetErrorCallback = std::move(callback);
}
void MockVehicleHardware::setPropertyConfigs(const std::vector<VehiclePropConfig>& configs) {
@@ -254,6 +255,12 @@
std::list<std::vector<SetValueRequest>>* storedRequests,
std::list<std::vector<SetValueResult>>* storedResponses) const;
+void MockVehicleHardware::sendOnPropertySetErrorEvent(
+ const std::vector<SetValueErrorEvent>& errorEvents) {
+ std::scoped_lock<std::mutex> lockGuard(mLock);
+ (*mPropertySetErrorCallback)(errorEvents);
+}
+
} // namespace vehicle
} // namespace automotive
} // namespace hardware
diff --git a/automotive/vehicle/aidl/impl/vhal/test/MockVehicleHardware.h b/automotive/vehicle/aidl/impl/vhal/test/MockVehicleHardware.h
index 743841c..46b30b9 100644
--- a/automotive/vehicle/aidl/impl/vhal/test/MockVehicleHardware.h
+++ b/automotive/vehicle/aidl/impl/vhal/test/MockVehicleHardware.h
@@ -85,6 +85,7 @@
aidl::android::hardware::automotive::vehicle::StatusCode status);
void setSleepTime(int64_t timeInNano);
void setDumpResult(DumpResult result);
+ void sendOnPropertySetErrorEvent(const std::vector<SetValueErrorEvent>& errorEvents);
private:
mutable std::mutex mLock;
@@ -104,6 +105,7 @@
mStatusByFunctions GUARDED_BY(mLock);
int64_t mSleepTime GUARDED_BY(mLock) = 0;
std::unique_ptr<const PropertyChangeCallback> mPropertyChangeCallback GUARDED_BY(mLock);
+ std::unique_ptr<const PropertySetErrorCallback> mPropertySetErrorCallback GUARDED_BY(mLock);
std::function<aidl::android::hardware::automotive::vehicle::StatusCode(
std::shared_ptr<const GetValuesCallback>,
const std::vector<aidl::android::hardware::automotive::vehicle::GetValueRequest>&)>
diff --git a/biometrics/fingerprint/aidl/default/FakeFingerprintEngine.cpp b/biometrics/fingerprint/aidl/default/FakeFingerprintEngine.cpp
index 90ec8f2..54076c8 100644
--- a/biometrics/fingerprint/aidl/default/FakeFingerprintEngine.cpp
+++ b/biometrics/fingerprint/aidl/default/FakeFingerprintEngine.cpp
@@ -31,6 +31,9 @@
namespace aidl::android::hardware::biometrics::fingerprint {
+FakeFingerprintEngine::FakeFingerprintEngine()
+ : mRandom(std::mt19937::default_seed), mWorkMode(WorkMode::kIdle) {}
+
void FakeFingerprintEngine::generateChallengeImpl(ISessionCallback* cb) {
BEGIN_OP(0);
std::uniform_int_distribution<int64_t> dist;
@@ -48,7 +51,7 @@
void FakeFingerprintEngine::enrollImpl(ISessionCallback* cb,
const keymaster::HardwareAuthToken& hat,
const std::future<void>& cancel) {
- BEGIN_OP(getLatency(FingerprintHalProperties::operation_enroll_latency()));
+ BEGIN_OP(0);
// Do proper HAT verification in the real implementation.
if (hat.mac.empty()) {
@@ -57,13 +60,77 @@
return;
}
+ updateContext(WorkMode::kEnroll, cb, const_cast<std::future<void>&>(cancel), 0, hat);
+}
+
+void FakeFingerprintEngine::authenticateImpl(ISessionCallback* cb, int64_t operationId,
+ const std::future<void>& cancel) {
+ BEGIN_OP(0);
+ updateContext(WorkMode::kAuthenticate, cb, const_cast<std::future<void>&>(cancel), operationId,
+ keymaster::HardwareAuthToken());
+}
+
+void FakeFingerprintEngine::detectInteractionImpl(ISessionCallback* cb,
+ const std::future<void>& cancel) {
+ BEGIN_OP(0);
+
+ auto detectInteractionSupported =
+ FingerprintHalProperties::detect_interaction().value_or(false);
+ if (!detectInteractionSupported) {
+ LOG(ERROR) << "Detect interaction is not supported";
+ cb->onError(Error::UNABLE_TO_PROCESS, 0 /* vendorError */);
+ return;
+ }
+
+ updateContext(WorkMode::kDetectInteract, cb, const_cast<std::future<void>&>(cancel), 0,
+ keymaster::HardwareAuthToken());
+}
+
+void FakeFingerprintEngine::updateContext(WorkMode mode, ISessionCallback* cb,
+ std::future<void>& cancel, int64_t operationId,
+ const keymaster::HardwareAuthToken& hat) {
+ mCancel = std::move(cancel);
+ mWorkMode = mode;
+ mCb = cb;
+ mOperationId = operationId;
+ mHat = hat;
+}
+
+void FakeFingerprintEngine::fingerDownAction() {
+ bool isTerminal = false;
+ LOG(INFO) << __func__;
+ switch (mWorkMode) {
+ case WorkMode::kAuthenticate:
+ isTerminal = onAuthenticateFingerDown(mCb, mOperationId, mCancel);
+ break;
+ case WorkMode::kEnroll:
+ isTerminal = onEnrollFingerDown(mCb, mHat, mCancel);
+ break;
+ case WorkMode::kDetectInteract:
+ isTerminal = onDetectInteractFingerDown(mCb, mCancel);
+ break;
+ default:
+ LOG(WARNING) << "unexpected mode: on fingerDownAction(), " << (int)mWorkMode;
+ break;
+ }
+
+ if (isTerminal) {
+ mWorkMode = WorkMode::kIdle;
+ }
+}
+
+bool FakeFingerprintEngine::onEnrollFingerDown(ISessionCallback* cb,
+ const keymaster::HardwareAuthToken&,
+ const std::future<void>& cancel) {
+ BEGIN_OP(getLatency(FingerprintHalProperties::operation_enroll_latency()));
+
// Force error-out
auto err = FingerprintHalProperties::operation_enroll_error().value_or(0);
if (err != 0) {
LOG(ERROR) << "Fail: operation_enroll_error";
auto ec = convertError(err);
cb->onError(ec.first, ec.second);
- return;
+ return true;
}
// Format is "<id>:<progress_ms-[acquiredInfo..]>,...:<result>
@@ -72,7 +139,7 @@
if (parts.size() != 3) {
LOG(ERROR) << "Fail: invalid next_enrollment:" << nextEnroll;
cb->onError(Error::VENDOR, 0 /* vendorError */);
- return;
+ return true;
}
auto enrollmentId = std::stoi(parts[0]);
auto progress = parseEnrollmentCapture(parts[1]);
@@ -88,7 +155,7 @@
if (shouldCancel(cancel)) {
LOG(ERROR) << "Fail: cancel";
cb->onError(Error::CANCELED, 0 /* vendorCode */);
- return;
+ return true;
}
auto ac = convertAcquiredInfo(acquired[j]);
cb->onAcquired(ac.first, ac.second);
@@ -114,10 +181,13 @@
cb->onEnrollmentProgress(enrollmentId, left);
}
}
+
+ return true;
}
-void FakeFingerprintEngine::authenticateImpl(ISessionCallback* cb, int64_t /* operationId */,
- const std::future<void>& cancel) {
+bool FakeFingerprintEngine::onAuthenticateFingerDown(ISessionCallback* cb,
+ int64_t /* operationId */,
+ const std::future<void>& cancel) {
BEGIN_OP(getLatency(FingerprintHalProperties::operation_authenticate_latency()));
int64_t now = Util::getSystemNanoTime();
@@ -129,19 +199,12 @@
if (N == 0) {
LOG(ERROR) << "Fail to parse authentiate acquired info: " + acquired;
cb->onError(Error::UNABLE_TO_PROCESS, 0 /* vendorError */);
- return;
+ return true;
}
// got lockout?
- FakeLockoutTracker::LockoutMode lockoutMode = mLockoutTracker.getMode();
- if (lockoutMode == FakeLockoutTracker::LockoutMode::kPermanent) {
- LOG(ERROR) << "Fail: lockout permanent";
- cb->onLockoutPermanent();
- return;
- } else if (lockoutMode == FakeLockoutTracker::LockoutMode::kTimed) {
- int64_t timeLeft = mLockoutTracker.getLockoutTimeLeft();
- LOG(ERROR) << "Fail: lockout timed " << timeLeft;
- cb->onLockoutTimed(timeLeft);
+ if (checkSensorLockout(cb)) {
+ return FakeLockoutTracker::LockoutMode::kPermanent == mLockoutTracker.getMode();
}
int i = 0;
@@ -150,7 +213,7 @@
LOG(ERROR) << "Fail: operation_authenticate_fails";
mLockoutTracker.addFailedAttempt();
cb->onAuthenticationFailed();
- return;
+ return false;
}
auto err = FingerprintHalProperties::operation_authenticate_error().value_or(0);
@@ -158,20 +221,21 @@
LOG(ERROR) << "Fail: operation_authenticate_error";
auto ec = convertError(err);
cb->onError(ec.first, ec.second);
- return;
+ return true; /* simply terminating current operation for any user inserted error,
+ revisit if tests need*/
}
if (FingerprintHalProperties::lockout().value_or(false)) {
LOG(ERROR) << "Fail: lockout";
cb->onLockoutPermanent();
cb->onError(Error::HW_UNAVAILABLE, 0 /* vendorError */);
- return;
+ return true;
}
if (shouldCancel(cancel)) {
LOG(ERROR) << "Fail: cancel";
cb->onError(Error::CANCELED, 0 /* vendorCode */);
- return;
+ return true;
}
if (i < N) {
@@ -189,29 +253,23 @@
if (id > 0 && isEnrolled) {
cb->onAuthenticationSucceeded(id, {} /* hat */);
mLockoutTracker.reset();
- return;
+ return true;
} else {
LOG(ERROR) << "Fail: fingerprint not enrolled";
cb->onAuthenticationFailed();
mLockoutTracker.addFailedAttempt();
+ checkSensorLockout(cb);
+ return false;
}
}
-void FakeFingerprintEngine::detectInteractionImpl(ISessionCallback* cb,
- const std::future<void>& cancel) {
+bool FakeFingerprintEngine::onDetectInteractFingerDown(ISessionCallback* cb,
+ const std::future<void>& cancel) {
BEGIN_OP(getLatency(FingerprintHalProperties::operation_detect_interaction_latency()));
int64_t duration =
FingerprintHalProperties::operation_detect_interaction_duration().value_or(10);
- auto detectInteractionSupported =
- FingerprintHalProperties::detect_interaction().value_or(false);
- if (!detectInteractionSupported) {
- LOG(ERROR) << "Detect interaction is not supported";
- cb->onError(Error::UNABLE_TO_PROCESS, 0 /* vendorError */);
- return;
- }
-
auto acquired = FingerprintHalProperties::operation_detect_interaction_acquired().value_or("1");
auto acquiredInfos = parseIntSequence(acquired);
int N = acquiredInfos.size();
@@ -220,7 +278,7 @@
if (N == 0) {
LOG(ERROR) << "Fail to parse detect interaction acquired info: " + acquired;
cb->onError(Error::UNABLE_TO_PROCESS, 0 /* vendorError */);
- return;
+ return true;
}
int i = 0;
@@ -230,13 +288,13 @@
LOG(ERROR) << "Fail: operation_detect_interaction_error";
auto ec = convertError(err);
cb->onError(ec.first, ec.second);
- return;
+ return true;
}
if (shouldCancel(cancel)) {
LOG(ERROR) << "Fail: cancel";
cb->onError(Error::CANCELED, 0 /* vendorCode */);
- return;
+ return true;
}
if (i < N) {
@@ -253,21 +311,18 @@
if (id <= 0 || !isEnrolled) {
LOG(ERROR) << "Fail: not enrolled";
cb->onError(Error::UNABLE_TO_PROCESS, 0 /* vendorError */);
- return;
+ return true;
}
cb->onInteractionDetected();
+
+ return true;
}
void FakeFingerprintEngine::enumerateEnrollmentsImpl(ISessionCallback* cb) {
BEGIN_OP(0);
std::vector<int32_t> ids;
- // There are some enrollment sync issue with framework, which results in
- // a single template removal during the very firt sync command after reboot.
- // This is a workaround for now. TODO(b/243129174)
- ids.push_back(-1);
-
for (auto& enrollment : FingerprintHalProperties::enrollments()) {
auto id = enrollment.value_or(0);
if (id > 0) {
@@ -330,6 +385,11 @@
cb->onError(Error::UNABLE_TO_PROCESS, 0 /* vendorError */);
return;
}
+ clearLockout(cb);
+ isLockoutTimerAborted = true;
+}
+
+void FakeFingerprintEngine::clearLockout(ISessionCallback* cb) {
FingerprintHalProperties::lockout(false);
cb->onLockoutCleared();
mLockoutTracker.reset();
@@ -339,6 +399,7 @@
int32_t /*y*/, float /*minor*/,
float /*major*/) {
BEGIN_OP(0);
+ fingerDownAction();
return ndk::ScopedAStatus::ok();
}
@@ -369,7 +430,8 @@
if (dim.size() >= 4) {
d = dim[3];
}
- if (isValidStr) out = {0, x, y, r, d};
+ if (isValidStr)
+ out = {.sensorLocationX = x, .sensorLocationY = y, .sensorRadius = r, .display = d};
return isValidStr;
}
@@ -385,8 +447,7 @@
}
SensorLocation FakeFingerprintEngine::defaultSensorLocation() {
- return {0 /* displayId (not used) */, 0 /* sensorLocationX */, 0 /* sensorLocationY */,
- 0 /* sensorRadius */, "" /* display */};
+ return SensorLocation();
}
std::vector<int32_t> FakeFingerprintEngine::parseIntSequence(const std::string& str,
@@ -513,4 +574,39 @@
return dist(mRandom);
}
+bool FakeFingerprintEngine::checkSensorLockout(ISessionCallback* cb) {
+ FakeLockoutTracker::LockoutMode lockoutMode = mLockoutTracker.getMode();
+ if (lockoutMode == FakeLockoutTracker::LockoutMode::kPermanent) {
+ LOG(ERROR) << "Fail: lockout permanent";
+ cb->onLockoutPermanent();
+ isLockoutTimerAborted = true;
+ return true;
+ } else if (lockoutMode == FakeLockoutTracker::LockoutMode::kTimed) {
+ int64_t timeLeft = mLockoutTracker.getLockoutTimeLeft();
+ LOG(ERROR) << "Fail: lockout timed " << timeLeft;
+ cb->onLockoutTimed(timeLeft);
+ if (isLockoutTimerSupported && !isLockoutTimerStarted) startLockoutTimer(timeLeft, cb);
+ return true;
+ }
+ return false;
+}
+
+void FakeFingerprintEngine::startLockoutTimer(int64_t timeout, ISessionCallback* cb) {
+ BEGIN_OP(0);
+ std::function<void(ISessionCallback*)> action =
+ std::bind(&FakeFingerprintEngine::lockoutTimerExpired, this, std::placeholders::_1);
+ std::thread([timeout, action, cb]() {
+ std::this_thread::sleep_for(std::chrono::milliseconds(timeout));
+ action(cb);
+ }).detach();
+
+ isLockoutTimerStarted = true;
+}
+void FakeFingerprintEngine::lockoutTimerExpired(ISessionCallback* cb) {
+ if (!isLockoutTimerAborted) {
+ clearLockout(cb);
+ }
+ isLockoutTimerStarted = false;
+ isLockoutTimerAborted = false;
+}
} // namespace aidl::android::hardware::biometrics::fingerprint
diff --git a/biometrics/fingerprint/aidl/default/FakeFingerprintEngineSide.cpp b/biometrics/fingerprint/aidl/default/FakeFingerprintEngineSide.cpp
index 9f736e7..a78cdcd 100644
--- a/biometrics/fingerprint/aidl/default/FakeFingerprintEngineSide.cpp
+++ b/biometrics/fingerprint/aidl/default/FakeFingerprintEngineSide.cpp
@@ -27,11 +27,13 @@
namespace aidl::android::hardware::biometrics::fingerprint {
-SensorLocation FakeFingerprintEngineSide::defaultSensorLocation() {
- SensorLocation location;
+FakeFingerprintEngineSide::FakeFingerprintEngineSide() : FakeFingerprintEngine() {
+ isLockoutTimerSupported = true;
+}
- return {0 /* displayId (not used) */, defaultSensorLocationX /* sensorLocationX */,
- defaultSensorLocationY /* sensorLocationY */, defaultSensorRadius /* sensorRadius */,
- "" /* display */};
+SensorLocation FakeFingerprintEngineSide::defaultSensorLocation() {
+ return SensorLocation{.sensorLocationX = defaultSensorLocationX,
+ .sensorLocationY = defaultSensorLocationY,
+ .sensorRadius = defaultSensorRadius};
}
} // namespace aidl::android::hardware::biometrics::fingerprint
diff --git a/biometrics/fingerprint/aidl/default/FakeFingerprintEngineUdfps.cpp b/biometrics/fingerprint/aidl/default/FakeFingerprintEngineUdfps.cpp
index 3cdfc70..68b0f0d 100644
--- a/biometrics/fingerprint/aidl/default/FakeFingerprintEngineUdfps.cpp
+++ b/biometrics/fingerprint/aidl/default/FakeFingerprintEngineUdfps.cpp
@@ -31,12 +31,12 @@
namespace aidl::android::hardware::biometrics::fingerprint {
FakeFingerprintEngineUdfps::FakeFingerprintEngineUdfps()
- : FakeFingerprintEngine(), mWorkMode(WorkMode::kIdle), mPointerDownTime(0), mUiReadyTime(0) {}
+ : FakeFingerprintEngine(), mPointerDownTime(0), mUiReadyTime(0) {}
SensorLocation FakeFingerprintEngineUdfps::defaultSensorLocation() {
- return {0 /* displayId (not used) */, defaultSensorLocationX /* sensorLocationX */,
- defaultSensorLocationY /* sensorLocationY */, defaultSensorRadius /* sensorRadius */,
- "" /* display */};
+ return SensorLocation{.sensorLocationX = defaultSensorLocationX,
+ .sensorLocationY = defaultSensorLocationY,
+ .sensorRadius = defaultSensorRadius};
}
ndk::ScopedAStatus FakeFingerprintEngineUdfps::onPointerDownImpl(int32_t /*pointerId*/,
@@ -70,68 +70,17 @@
}
void FakeFingerprintEngineUdfps::fingerDownAction() {
- switch (mWorkMode) {
- case WorkMode::kAuthenticate:
- onAuthenticateFingerDown();
- break;
- case WorkMode::kEnroll:
- onEnrollFingerDown();
- break;
- case WorkMode::kDetectInteract:
- onDetectInteractFingerDown();
- break;
- default:
- LOG(WARNING) << "unexpected call: onUiReady()";
- break;
- }
-
+ FakeFingerprintEngine::fingerDownAction();
mUiReadyTime = 0;
mPointerDownTime = 0;
}
-void FakeFingerprintEngineUdfps::onAuthenticateFingerDown() {
- FakeFingerprintEngine::authenticateImpl(mCb, mOperationId, mCancelVec[0]);
-}
-
-void FakeFingerprintEngineUdfps::onEnrollFingerDown() {
- // Any use case to emulate display touch for each capture during enrollment?
- FakeFingerprintEngine::enrollImpl(mCb, mHat, mCancelVec[0]);
-}
-
-void FakeFingerprintEngineUdfps::onDetectInteractFingerDown() {
- FakeFingerprintEngine::detectInteractionImpl(mCb, mCancelVec[0]);
-}
-
-void FakeFingerprintEngineUdfps::enrollImpl(ISessionCallback* cb,
- const keymaster::HardwareAuthToken& hat,
- const std::future<void>& cancel) {
- updateContext(WorkMode::kEnroll, cb, const_cast<std::future<void>&>(cancel), 0, hat);
-}
-
-void FakeFingerprintEngineUdfps::authenticateImpl(ISessionCallback* cb, int64_t operationId,
- const std::future<void>& cancel) {
- updateContext(WorkMode::kAuthenticate, cb, const_cast<std::future<void>&>(cancel), operationId,
- keymaster::HardwareAuthToken());
-}
-
-void FakeFingerprintEngineUdfps::detectInteractionImpl(ISessionCallback* cb,
- const std::future<void>& cancel) {
- updateContext(WorkMode::kDetectInteract, cb, const_cast<std::future<void>&>(cancel), 0,
- keymaster::HardwareAuthToken());
-}
-
void FakeFingerprintEngineUdfps::updateContext(WorkMode mode, ISessionCallback* cb,
std::future<void>& cancel, int64_t operationId,
const keymaster::HardwareAuthToken& hat) {
+ FakeFingerprintEngine::updateContext(mode, cb, cancel, operationId, hat);
mPointerDownTime = 0;
mUiReadyTime = 0;
- mCancelVec.clear();
-
- mCancelVec.push_back(std::move(cancel));
- mWorkMode = mode;
- mCb = cb;
- mOperationId = operationId;
- mHat = hat;
}
} // namespace aidl::android::hardware::biometrics::fingerprint
diff --git a/biometrics/fingerprint/aidl/default/FakeLockoutTracker.cpp b/biometrics/fingerprint/aidl/default/FakeLockoutTracker.cpp
index 5996406..b0163ee 100644
--- a/biometrics/fingerprint/aidl/default/FakeLockoutTracker.cpp
+++ b/biometrics/fingerprint/aidl/default/FakeLockoutTracker.cpp
@@ -67,9 +67,13 @@
int64_t res = 0;
if (mLockoutTimedStart > 0) {
+ int32_t lockoutTimedDuration =
+ FingerprintHalProperties::lockout_timed_duration().value_or(10 * 100);
auto now = Util::getSystemNanoTime();
- auto left = now - mLockoutTimedStart;
- res = (left > 0) ? (left / 1000000LL) : 0;
+ auto elapsed = (now - mLockoutTimedStart) / 1000000LL;
+ res = lockoutTimedDuration - elapsed;
+ LOG(INFO) << "xxxxxx: elapsed=" << elapsed << " now = " << now
+ << " mLockoutTimedStart=" << mLockoutTimedStart << " res=" << res;
}
return res;
diff --git a/biometrics/fingerprint/aidl/default/Fingerprint.cpp b/biometrics/fingerprint/aidl/default/Fingerprint.cpp
index f00a49d..79b563e 100644
--- a/biometrics/fingerprint/aidl/default/Fingerprint.cpp
+++ b/biometrics/fingerprint/aidl/default/Fingerprint.cpp
@@ -17,6 +17,7 @@
#include "Fingerprint.h"
#include "Session.h"
+#include <android-base/properties.h>
#include <fingerprint.sysprop.h>
#include <android-base/file.h>
@@ -59,6 +60,7 @@
<< sensorTypeProp;
}
LOG(INFO) << "sensorTypeProp:" << sensorTypeProp;
+ LOG(INFO) << "ro.product.name=" << ::android::base::GetProperty("ro.product.name", "UNKNOWN");
}
ndk::ScopedAStatus Fingerprint::getSensorProps(std::vector<SensorProps>* out) {
@@ -105,16 +107,16 @@
mSession->linkToDeath(cb->asBinder().get());
- LOG(INFO) << "createSession: sensorId:" << sensorId << " userId:" << userId;
+ LOG(INFO) << __func__ << ": sensorId:" << sensorId << " userId:" << userId;
return ndk::ScopedAStatus::ok();
}
binder_status_t Fingerprint::dump(int fd, const char** /*args*/, uint32_t numArgs) {
if (fd < 0) {
- LOG(ERROR) << "Fingerprint::dump fd invalid: " << fd;
+ LOG(ERROR) << __func__ << "fd invalid: " << fd;
return STATUS_BAD_VALUE;
} else {
- LOG(INFO) << "Fingerprint::dump fd:" << fd << "numArgs:" << numArgs;
+ LOG(INFO) << __func__ << " fd:" << fd << "numArgs:" << numArgs;
}
dprintf(fd, "----- FingerprintVirtualHal::dump -----\n");
@@ -131,11 +133,11 @@
binder_status_t Fingerprint::handleShellCommand(int in, int out, int err, const char** args,
uint32_t numArgs) {
- LOG(INFO) << "Fingerprint::handleShellCommand in:" << in << " out:" << out << " err:" << err
+ LOG(INFO) << __func__ << " in:" << in << " out:" << out << " err:" << err
<< " numArgs:" << numArgs;
if (numArgs == 0) {
- LOG(INFO) << "Fingerprint::handleShellCommand: available commands";
+ LOG(INFO) << __func__ << ": available commands";
onHelp(out);
return STATUS_OK;
}
@@ -163,7 +165,7 @@
}
void Fingerprint::resetConfigToDefault() {
- LOG(INFO) << "reset virtual HAL configuration to default";
+ LOG(INFO) << __func__ << ": reset virtual HAL configuration to default";
#define RESET_CONFIG_O(__NAME__) \
if (FingerprintHalProperties::__NAME__()) FingerprintHalProperties::__NAME__(std::nullopt)
#define RESET_CONFIG_V(__NAME__) \
diff --git a/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngine.h b/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngine.h
index 1279cd9..2450115 100644
--- a/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngine.h
+++ b/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngine.h
@@ -38,7 +38,7 @@
// A fake engine that is backed by system properties instead of hardware.
class FakeFingerprintEngine {
public:
- FakeFingerprintEngine() : mRandom(std::mt19937::default_seed) {}
+ FakeFingerprintEngine();
virtual ~FakeFingerprintEngine() {}
void generateChallengeImpl(ISessionCallback* cb);
@@ -66,6 +66,8 @@
virtual SensorLocation defaultSensorLocation();
+ virtual void fingerDownAction();
+
std::vector<int32_t> parseIntSequence(const std::string& str, const std::string& sep = ",");
std::vector<std::vector<int32_t>> parseEnrollmentCapture(const std::string& str);
@@ -74,15 +76,35 @@
std::mt19937 mRandom;
+ enum class WorkMode : int8_t { kIdle = 0, kAuthenticate, kEnroll, kDetectInteract };
+
+ WorkMode getWorkMode() { return mWorkMode; }
+
virtual std::string toString() const {
std::ostringstream os;
os << "----- FakeFingerprintEngine:: -----" << std::endl;
+ os << "mWorkMode:" << (int)mWorkMode;
os << "acquiredVendorInfoBase:" << FINGERPRINT_ACQUIRED_VENDOR_BASE;
os << ", errorVendorBase:" << FINGERPRINT_ERROR_VENDOR_BASE << std::endl;
os << mLockoutTracker.toString();
return os.str();
}
+ protected:
+ virtual void updateContext(WorkMode mode, ISessionCallback* cb, std::future<void>& cancel,
+ int64_t operationId, const keymaster::HardwareAuthToken& hat);
+
+ bool onEnrollFingerDown(ISessionCallback* cb, const keymaster::HardwareAuthToken& hat,
+ const std::future<void>& cancel);
+ bool onAuthenticateFingerDown(ISessionCallback* cb, int64_t, const std::future<void>& cancel);
+ bool onDetectInteractFingerDown(ISessionCallback* cb, const std::future<void>& cancel);
+
+ WorkMode mWorkMode;
+ ISessionCallback* mCb;
+ keymaster::HardwareAuthToken mHat;
+ std::future<void> mCancel;
+ int64_t mOperationId;
+
private:
static constexpr int32_t FINGERPRINT_ACQUIRED_VENDOR_BASE = 1000;
static constexpr int32_t FINGERPRINT_ERROR_VENDOR_BASE = 1000;
@@ -91,8 +113,21 @@
bool parseEnrollmentCaptureSingle(const std::string& str,
std::vector<std::vector<int32_t>>& res);
int32_t getRandomInRange(int32_t bound1, int32_t bound2);
+ bool checkSensorLockout(ISessionCallback*);
+ void clearLockout(ISessionCallback* cb);
FakeLockoutTracker mLockoutTracker;
+
+ protected:
+ // lockout timer
+ void lockoutTimerExpired(ISessionCallback* cb);
+ bool isLockoutTimerSupported;
+ bool isLockoutTimerStarted;
+ bool isLockoutTimerAborted;
+
+ public:
+ void startLockoutTimer(int64_t timeout, ISessionCallback* cb);
+ bool getLockoutTimerStarted() { return isLockoutTimerStarted; }
};
} // namespace aidl::android::hardware::biometrics::fingerprint
diff --git a/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngineSide.h b/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngineSide.h
index c2fc005..67a3ebc 100644
--- a/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngineSide.h
+++ b/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngineSide.h
@@ -28,7 +28,7 @@
static constexpr int32_t defaultSensorLocationY = 600;
static constexpr int32_t defaultSensorRadius = 150;
- FakeFingerprintEngineSide() : FakeFingerprintEngine() {}
+ FakeFingerprintEngineSide();
~FakeFingerprintEngineSide() {}
virtual SensorLocation defaultSensorLocation() override;
diff --git a/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngineUdfps.h b/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngineUdfps.h
index c5e93e7..2270eca 100644
--- a/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngineUdfps.h
+++ b/biometrics/fingerprint/aidl/default/include/FakeFingerprintEngineUdfps.h
@@ -42,39 +42,20 @@
SensorLocation defaultSensorLocation() override;
- void enrollImpl(ISessionCallback* cb, const keymaster::HardwareAuthToken& hat,
- const std::future<void>& cancel);
- void authenticateImpl(ISessionCallback* cb, int64_t operationId,
- const std::future<void>& cancel);
- void detectInteractionImpl(ISessionCallback* cb, const std::future<void>& cancel);
-
- enum class WorkMode : int8_t { kIdle = 0, kAuthenticate, kEnroll, kDetectInteract };
-
- WorkMode getWorkMode() { return mWorkMode; }
+ void updateContext(WorkMode mode, ISessionCallback* cb, std::future<void>& cancel,
+ int64_t operationId, const keymaster::HardwareAuthToken& hat);
+ void fingerDownAction();
std::string toString() const {
std::ostringstream os;
os << FakeFingerprintEngine::toString();
os << "----- FakeFingerprintEngineUdfps -----" << std::endl;
- os << "mWorkMode:" << (int)mWorkMode;
os << ", mUiReadyTime:" << mUiReadyTime;
os << ", mPointerDownTime:" << mPointerDownTime << std::endl;
return os.str();
}
private:
- void onAuthenticateFingerDown();
- void onEnrollFingerDown();
- void onDetectInteractFingerDown();
- void fingerDownAction();
- void updateContext(WorkMode mode, ISessionCallback* cb, std::future<void>& cancel,
- int64_t operationId, const keymaster::HardwareAuthToken& hat);
-
- WorkMode mWorkMode;
- ISessionCallback* mCb;
- keymaster::HardwareAuthToken mHat;
- std::vector<std::future<void>> mCancelVec;
- int64_t mOperationId;
int64_t mPointerDownTime;
int64_t mUiReadyTime;
};
diff --git a/biometrics/fingerprint/aidl/default/include/Fingerprint.h b/biometrics/fingerprint/aidl/default/include/Fingerprint.h
index fc4fb8d..2bd66d4 100644
--- a/biometrics/fingerprint/aidl/default/include/Fingerprint.h
+++ b/biometrics/fingerprint/aidl/default/include/Fingerprint.h
@@ -43,6 +43,7 @@
private:
void resetConfigToDefault();
void onHelp(int);
+ void onSimFingerDown();
std::unique_ptr<FakeFingerprintEngine> mEngine;
WorkerThread mWorker;
diff --git a/biometrics/fingerprint/aidl/default/tests/FakeFingerprintEngineTest.cpp b/biometrics/fingerprint/aidl/default/tests/FakeFingerprintEngineTest.cpp
index a200b39..fe405f4 100644
--- a/biometrics/fingerprint/aidl/default/tests/FakeFingerprintEngineTest.cpp
+++ b/biometrics/fingerprint/aidl/default/tests/FakeFingerprintEngineTest.cpp
@@ -93,9 +93,13 @@
return ndk::ScopedAStatus::ok();
};
ndk::ScopedAStatus onLockoutTimed(int64_t /* timeout */) override {
+ mLockoutTimed = true;
return ndk::ScopedAStatus::ok();
}
- ndk::ScopedAStatus onLockoutCleared() override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus onLockoutCleared() override {
+ mLockoutCleared = true;
+ return ndk::ScopedAStatus::ok();
+ }
ndk::ScopedAStatus onSessionClosed() override { return ndk::ScopedAStatus::ok(); }
Error mError = Error::UNKNOWN;
@@ -110,6 +114,8 @@
bool mAuthenticateFailed = false;
bool mAuthenticatorIdInvalidated = false;
bool mLockoutPermanent = false;
+ bool mLockoutTimed = false;
+ bool mLockoutCleared = false;
int mInteractionDetectedCount = 0;
int32_t mLastAcquiredInfo = -1;
int32_t mLastAcquiredVendorCode = -1;
@@ -132,6 +138,8 @@
FingerprintHalProperties::operation_enroll_latency({});
FingerprintHalProperties::operation_authenticate_latency({});
FingerprintHalProperties::operation_detect_interaction_latency({});
+ FingerprintHalProperties::operation_authenticate_fails(false);
+ FingerprintHalProperties::operation_detect_interaction_latency({});
}
FakeFingerprintEngine mEngine;
@@ -178,11 +186,14 @@
FingerprintHalProperties::next_enrollment("4:0,0:true");
keymaster::HardwareAuthToken hat{.mac = {2, 4}};
mEngine.enrollImpl(mCallback.get(), hat, mCancel.get_future());
+ ASSERT_EQ(mEngine.getWorkMode(), FakeFingerprintEngine::WorkMode::kEnroll);
+ mEngine.fingerDownAction();
ASSERT_FALSE(FingerprintHalProperties::next_enrollment().has_value());
ASSERT_EQ(1, FingerprintHalProperties::enrollments().size());
ASSERT_EQ(4, FingerprintHalProperties::enrollments()[0].value());
ASSERT_EQ(4, mCallback->mLastEnrolled);
ASSERT_EQ(1, mCallback->mLastAcquiredInfo);
+ ASSERT_EQ(mEngine.getWorkMode(), FakeFingerprintEngine::WorkMode::kIdle);
}
TEST_F(FakeFingerprintEngineTest, EnrollCancel) {
@@ -192,6 +203,7 @@
keymaster::HardwareAuthToken hat{.mac = {2, 4}};
mCancel.set_value();
mEngine.enrollImpl(mCallback.get(), hat, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(Error::CANCELED, mCallback->mError);
ASSERT_EQ(-1, mCallback->mLastEnrolled);
ASSERT_EQ(0, FingerprintHalProperties::enrollments().size());
@@ -204,6 +216,7 @@
FingerprintHalProperties::next_enrollment(next);
keymaster::HardwareAuthToken hat{.mac = {2, 4}};
mEngine.enrollImpl(mCallback.get(), hat, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(Error::UNABLE_TO_PROCESS, mCallback->mError);
ASSERT_EQ(-1, mCallback->mLastEnrolled);
ASSERT_EQ(0, FingerprintHalProperties::enrollments().size());
@@ -216,6 +229,7 @@
keymaster::HardwareAuthToken hat{.mac = {2, 4}};
int32_t prevCnt = mCallback->mLastAcquiredCount;
mEngine.enrollImpl(mCallback.get(), hat, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_FALSE(FingerprintHalProperties::next_enrollment().has_value());
ASSERT_EQ(1, FingerprintHalProperties::enrollments().size());
ASSERT_EQ(4, FingerprintHalProperties::enrollments()[0].value());
@@ -229,9 +243,12 @@
FingerprintHalProperties::enrollments({1, 2});
FingerprintHalProperties::enrollment_hit(2);
mEngine.authenticateImpl(mCallback.get(), 0, mCancel.get_future());
+ ASSERT_EQ(mEngine.getWorkMode(), FakeFingerprintEngine::WorkMode::kAuthenticate);
+ mEngine.fingerDownAction();
ASSERT_FALSE(mCallback->mAuthenticateFailed);
ASSERT_EQ(2, mCallback->mLastAuthenticated);
ASSERT_EQ(1, mCallback->mLastAcquiredInfo);
+ ASSERT_EQ(mEngine.getWorkMode(), FakeFingerprintEngine::WorkMode::kIdle);
}
TEST_F(FakeFingerprintEngineTest, AuthenticateCancel) {
@@ -239,6 +256,7 @@
FingerprintHalProperties::enrollment_hit(2);
mCancel.set_value();
mEngine.authenticateImpl(mCallback.get(), 0, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(Error::CANCELED, mCallback->mError);
ASSERT_EQ(-1, mCallback->mLastAuthenticated);
}
@@ -247,6 +265,7 @@
FingerprintHalProperties::enrollments({1, 2});
FingerprintHalProperties::enrollment_hit({});
mEngine.authenticateImpl(mCallback.get(), 0, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_TRUE(mCallback->mAuthenticateFailed);
}
@@ -254,7 +273,9 @@
FingerprintHalProperties::enrollments({1, 2});
FingerprintHalProperties::enrollment_hit(3);
mEngine.authenticateImpl(mCallback.get(), 0, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_TRUE(mCallback->mAuthenticateFailed);
+ ASSERT_EQ(mEngine.getWorkMode(), FakeFingerprintEngine::WorkMode::kAuthenticate);
}
TEST_F(FakeFingerprintEngineTest, AuthenticateLockout) {
@@ -262,6 +283,7 @@
FingerprintHalProperties::enrollment_hit(2);
FingerprintHalProperties::lockout(true);
mEngine.authenticateImpl(mCallback.get(), 0, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_TRUE(mCallback->mLockoutPermanent);
ASSERT_NE(mCallback->mError, Error::UNKNOWN);
}
@@ -269,6 +291,7 @@
TEST_F(FakeFingerprintEngineTest, AuthenticateError8) {
FingerprintHalProperties::operation_authenticate_error(8);
mEngine.authenticateImpl(mCallback.get(), 0, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(mCallback->mError, (Error)8);
ASSERT_EQ(mCallback->mErrorVendorCode, 0);
}
@@ -276,10 +299,19 @@
TEST_F(FakeFingerprintEngineTest, AuthenticateError9) {
FingerprintHalProperties::operation_authenticate_error(1009);
mEngine.authenticateImpl(mCallback.get(), 0, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(mCallback->mError, (Error)7);
ASSERT_EQ(mCallback->mErrorVendorCode, 9);
}
+TEST_F(FakeFingerprintEngineTest, AuthenticateFails) {
+ FingerprintHalProperties::operation_authenticate_fails(true);
+ mEngine.authenticateImpl(mCallback.get(), 0, mCancel.get_future());
+ mEngine.fingerDownAction();
+ ASSERT_TRUE(mCallback->mAuthenticateFailed);
+ ASSERT_EQ(mEngine.getWorkMode(), FakeFingerprintEngine::WorkMode::kAuthenticate);
+}
+
TEST_F(FakeFingerprintEngineTest, AuthenticateAcquired) {
FingerprintHalProperties::lockout(false);
FingerprintHalProperties::enrollments({1, 2});
@@ -287,6 +319,7 @@
FingerprintHalProperties::operation_authenticate_acquired("4,1009");
int32_t prevCount = mCallback->mLastAcquiredCount;
mEngine.authenticateImpl(mCallback.get(), 0, mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_FALSE(mCallback->mAuthenticateFailed);
ASSERT_EQ(2, mCallback->mLastAuthenticated);
ASSERT_EQ(prevCount + 2, mCallback->mLastAcquiredCount);
@@ -300,8 +333,11 @@
FingerprintHalProperties::enrollment_hit(2);
FingerprintHalProperties::operation_detect_interaction_acquired("");
mEngine.detectInteractionImpl(mCallback.get(), mCancel.get_future());
+ ASSERT_EQ(mEngine.getWorkMode(), FakeFingerprintEngine::WorkMode::kDetectInteract);
+ mEngine.fingerDownAction();
ASSERT_EQ(1, mCallback->mInteractionDetectedCount);
ASSERT_EQ(1, mCallback->mLastAcquiredInfo);
+ ASSERT_EQ(mEngine.getWorkMode(), FakeFingerprintEngine::WorkMode::kIdle);
}
TEST_F(FakeFingerprintEngineTest, InteractionDetectCancel) {
@@ -310,6 +346,7 @@
FingerprintHalProperties::enrollment_hit(2);
mCancel.set_value();
mEngine.detectInteractionImpl(mCallback.get(), mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(Error::CANCELED, mCallback->mError);
ASSERT_EQ(0, mCallback->mInteractionDetectedCount);
}
@@ -319,6 +356,7 @@
FingerprintHalProperties::enrollments({1, 2});
FingerprintHalProperties::enrollment_hit({});
mEngine.detectInteractionImpl(mCallback.get(), mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(0, mCallback->mInteractionDetectedCount);
}
@@ -326,6 +364,7 @@
FingerprintHalProperties::enrollments({1, 2});
FingerprintHalProperties::enrollment_hit(25);
mEngine.detectInteractionImpl(mCallback.get(), mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(0, mCallback->mInteractionDetectedCount);
}
@@ -333,6 +372,7 @@
FingerprintHalProperties::detect_interaction(true);
FingerprintHalProperties::operation_detect_interaction_error(8);
mEngine.detectInteractionImpl(mCallback.get(), mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(0, mCallback->mInteractionDetectedCount);
ASSERT_EQ(mCallback->mError, (Error)8);
ASSERT_EQ(mCallback->mErrorVendorCode, 0);
@@ -345,6 +385,7 @@
FingerprintHalProperties::operation_detect_interaction_acquired("4,1013");
int32_t prevCount = mCallback->mLastAcquiredCount;
mEngine.detectInteractionImpl(mCallback.get(), mCancel.get_future());
+ mEngine.fingerDownAction();
ASSERT_EQ(1, mCallback->mInteractionDetectedCount);
ASSERT_EQ(prevCount + 2, mCallback->mLastAcquiredCount);
ASSERT_EQ(7, mCallback->mLastAcquiredInfo);
@@ -354,9 +395,7 @@
TEST_F(FakeFingerprintEngineTest, EnumerateEnrolled) {
FingerprintHalProperties::enrollments({2, 4, 8});
mEngine.enumerateEnrollmentsImpl(mCallback.get());
- ASSERT_EQ(
- 4,
- mCallback->mLastEnrollmentEnumerated.size()); // Due to workaround. TODO (b/243129174)
+ ASSERT_EQ(3, mCallback->mLastEnrollmentEnumerated.size());
for (auto id : FingerprintHalProperties::enrollments()) {
ASSERT_TRUE(std::find(mCallback->mLastEnrollmentEnumerated.begin(),
mCallback->mLastEnrollmentEnumerated.end(),
@@ -464,9 +503,15 @@
FingerprintHalProperties::operation_detect_interaction_latency()));
}
ASSERT_TRUE(latencySet.size() > 95);
- FingerprintHalProperties::operation_detect_interaction_latency({});
}
+TEST_F(FakeFingerprintEngineTest, lockoutTimer) {
+ mEngine.startLockoutTimer(200, mCallback.get());
+ ASSERT_TRUE(mEngine.getLockoutTimerStarted());
+ std::this_thread::sleep_for(std::chrono::milliseconds(210));
+ ASSERT_FALSE(mEngine.getLockoutTimerStarted());
+ ASSERT_TRUE(mCallback->mLockoutCleared);
+}
} // namespace aidl::android::hardware::biometrics::fingerprint
int main(int argc, char** argv) {
diff --git a/biometrics/fingerprint/aidl/default/tests/FakeLockoutTrackerTest.cpp b/biometrics/fingerprint/aidl/default/tests/FakeLockoutTrackerTest.cpp
index 1b071ee..93c6f84 100644
--- a/biometrics/fingerprint/aidl/default/tests/FakeLockoutTrackerTest.cpp
+++ b/biometrics/fingerprint/aidl/default/tests/FakeLockoutTrackerTest.cpp
@@ -65,11 +65,11 @@
ASSERT_EQ(mLockoutTracker.getMode(), FakeLockoutTracker::LockoutMode::kTimed);
// time left
int N = 5;
- int64_t prevTimeLeft = INT_MIN;
+ int64_t prevTimeLeft = INT_MAX;
for (int i = 0; i < N; i++) {
SLEEP_MS(LOCKOUT_TIMED_DURATION / N + 1);
int64_t currTimeLeft = mLockoutTracker.getLockoutTimeLeft();
- ASSERT_TRUE(currTimeLeft > prevTimeLeft);
+ ASSERT_TRUE(currTimeLeft < prevTimeLeft);
prevTimeLeft = currTimeLeft;
}
ASSERT_EQ(mLockoutTracker.getMode(), FakeLockoutTracker::LockoutMode::kNone);
diff --git a/bluetooth/audio/aidl/Android.bp b/bluetooth/audio/aidl/Android.bp
index 32f8cca..1028fae 100644
--- a/bluetooth/audio/aidl/Android.bp
+++ b/bluetooth/audio/aidl/Android.bp
@@ -24,12 +24,13 @@
aidl_interface {
name: "android.hardware.bluetooth.audio",
vendor_available: true,
+ host_supported: true,
srcs: ["android/hardware/bluetooth/audio/*.aidl"],
stability: "vintf",
imports: [
"android.hardware.common-V2",
"android.hardware.common.fmq-V1",
- "android.hardware.audio.common-V1",
+ "android.hardware.audio.common-V2",
],
backend: {
cpp: {
@@ -69,7 +70,7 @@
imports: [
"android.hardware.common-V2",
"android.hardware.common.fmq-V1",
- "android.hardware.audio.common-V1",
+ "android.hardware.audio.common-V2",
],
},
diff --git a/bluetooth/audio/aidl/default/BluetoothAudioProvider.cpp b/bluetooth/audio/aidl/default/BluetoothAudioProvider.cpp
index 2a88959..9c72e19 100644
--- a/bluetooth/audio/aidl/default/BluetoothAudioProvider.cpp
+++ b/bluetooth/audio/aidl/default/BluetoothAudioProvider.cpp
@@ -27,9 +27,31 @@
namespace bluetooth {
namespace audio {
+struct BluetoothAudioProviderContext {
+ SessionType session_type;
+};
+
+static void binderUnlinkedCallbackAidl(void* cookie) {
+ LOG(INFO) << __func__;
+ BluetoothAudioProviderContext* ctx =
+ static_cast<BluetoothAudioProviderContext*>(cookie);
+ delete ctx;
+}
+
+static void binderDiedCallbackAidl(void* cookie) {
+ LOG(INFO) << __func__;
+ BluetoothAudioProviderContext* ctx =
+ static_cast<BluetoothAudioProviderContext*>(cookie);
+ CHECK_NE(ctx, nullptr);
+
+ BluetoothAudioSessionReport::OnSessionEnded(ctx->session_type);
+}
+
BluetoothAudioProvider::BluetoothAudioProvider() {
death_recipient_ = ::ndk::ScopedAIBinder_DeathRecipient(
AIBinder_DeathRecipient_new(binderDiedCallbackAidl));
+ AIBinder_DeathRecipient_setOnUnlinked(death_recipient_.get(),
+ binderUnlinkedCallbackAidl);
}
ndk::ScopedAStatus BluetoothAudioProvider::startSession(
@@ -39,17 +61,21 @@
DataMQDesc* _aidl_return) {
if (host_if == nullptr) {
*_aidl_return = DataMQDesc();
+ LOG(ERROR) << __func__ << " - SessionType=" << toString(session_type_)
+ << " Illegal argument";
return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
}
latency_modes_ = latencyModes;
audio_config_ = std::make_unique<AudioConfiguration>(audio_config);
stack_iface_ = host_if;
- is_binder_died = false;
+ BluetoothAudioProviderContext* cookie =
+ new BluetoothAudioProviderContext{session_type_};
AIBinder_linkToDeath(stack_iface_->asBinder().get(), death_recipient_.get(),
- this);
+ cookie);
+ LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_);
onSessionReady(_aidl_return);
return ndk::ScopedAStatus::ok();
}
@@ -60,10 +86,8 @@
if (stack_iface_ != nullptr) {
BluetoothAudioSessionReport::OnSessionEnded(session_type_);
- if (!is_binder_died) {
- AIBinder_unlinkToDeath(stack_iface_->asBinder().get(),
- death_recipient_.get(), this);
- }
+ AIBinder_unlinkToDeath(stack_iface_->asBinder().get(),
+ death_recipient_.get(), this);
} else {
LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_)
<< " has NO session";
@@ -77,10 +101,9 @@
ndk::ScopedAStatus BluetoothAudioProvider::streamStarted(
BluetoothAudioStatus status) {
- LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_)
- << ", status=" << toString(status);
-
if (stack_iface_ != nullptr) {
+ LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_)
+ << ", status=" << toString(status);
BluetoothAudioSessionReport::ReportControlStatus(session_type_, true,
status);
} else {
@@ -108,8 +131,6 @@
ndk::ScopedAStatus BluetoothAudioProvider::updateAudioConfiguration(
const AudioConfiguration& audio_config) {
- LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_);
-
if (stack_iface_ == nullptr || audio_config_ == nullptr) {
LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_)
<< " has NO session";
@@ -125,13 +146,13 @@
audio_config_ = std::make_unique<AudioConfiguration>(audio_config);
BluetoothAudioSessionReport::ReportAudioConfigChanged(session_type_,
*audio_config_);
+ LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_)
+ << " | audio_config=" << audio_config.toString();
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus BluetoothAudioProvider::setLowLatencyModeAllowed(
bool allowed) {
- LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_);
-
if (stack_iface_ == nullptr) {
LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_)
<< " has NO session";
@@ -143,17 +164,6 @@
return ndk::ScopedAStatus::ok();
}
-void BluetoothAudioProvider::binderDiedCallbackAidl(void* ptr) {
- LOG(ERROR) << __func__ << " - BluetoothAudio Service died";
- auto provider = static_cast<BluetoothAudioProvider*>(ptr);
- if (provider == nullptr) {
- LOG(ERROR) << __func__ << ": Null AudioProvider HAL died";
- return;
- }
- provider->is_binder_died = true;
- provider->endSession();
-}
-
} // namespace audio
} // namespace bluetooth
} // namespace hardware
diff --git a/bluetooth/audio/aidl/default/BluetoothAudioProvider.h b/bluetooth/audio/aidl/default/BluetoothAudioProvider.h
index dbfff7d..b6e07a1 100644
--- a/bluetooth/audio/aidl/default/BluetoothAudioProvider.h
+++ b/bluetooth/audio/aidl/default/BluetoothAudioProvider.h
@@ -54,7 +54,6 @@
protected:
virtual ndk::ScopedAStatus onSessionReady(DataMQDesc* _aidl_return) = 0;
- static void binderDiedCallbackAidl(void* cookie_ptr);
::ndk::ScopedAIBinder_DeathRecipient death_recipient_;
@@ -62,9 +61,7 @@
std::unique_ptr<AudioConfiguration> audio_config_ = nullptr;
SessionType session_type_;
std::vector<LatencyMode> latency_modes_;
- bool is_binder_died = false;
};
-
} // namespace audio
} // namespace bluetooth
} // namespace hardware
diff --git a/bluetooth/audio/aidl/vts/Android.bp b/bluetooth/audio/aidl/vts/Android.bp
index 3e6953f..fa85fa8 100644
--- a/bluetooth/audio/aidl/vts/Android.bp
+++ b/bluetooth/audio/aidl/vts/Android.bp
@@ -16,7 +16,7 @@
tidy_timeout_srcs: ["VtsHalBluetoothAudioTargetTest.cpp"],
srcs: ["VtsHalBluetoothAudioTargetTest.cpp"],
static_libs: [
- "android.hardware.audio.common-V1-ndk",
+ "android.hardware.audio.common-V2-ndk",
"android.hardware.bluetooth.audio-V3-ndk",
"android.hardware.common-V2-ndk",
"android.hardware.common.fmq-V1-ndk",
diff --git a/bluetooth/audio/utils/Android.bp b/bluetooth/audio/utils/Android.bp
index 914d2b2..8cafb47 100644
--- a/bluetooth/audio/utils/Android.bp
+++ b/bluetooth/audio/utils/Android.bp
@@ -36,6 +36,7 @@
cc_library_shared {
name: "libbluetooth_audio_session_aidl",
vendor: true,
+ host_supported: true,
srcs: [
"aidl_session/BluetoothAudioCodecs.cpp",
"aidl_session/BluetoothAudioSession.cpp",
diff --git a/bluetooth/audio/utils/aidl_session/BluetoothAudioSession.cpp b/bluetooth/audio/utils/aidl_session/BluetoothAudioSession.cpp
index 57a01c9..0bcafa3 100644
--- a/bluetooth/audio/utils/aidl_session/BluetoothAudioSession.cpp
+++ b/bluetooth/audio/utils/aidl_session/BluetoothAudioSession.cpp
@@ -20,6 +20,7 @@
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include <android/binder_manager.h>
+#include <hardware/audio.h>
#include "BluetoothAudioSession.h"
@@ -486,23 +487,9 @@
void BluetoothAudioSession::UpdateSourceMetadata(
const struct source_metadata& source_metadata) {
- std::lock_guard<std::recursive_mutex> guard(mutex_);
- if (!IsSessionReady()) {
- LOG(DEBUG) << __func__ << " - SessionType=" << toString(session_type_)
- << " has NO session";
- return;
- }
-
ssize_t track_count = source_metadata.track_count;
LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_) << ","
<< track_count << " track(s)";
- if (session_type_ == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH ||
- session_type_ == SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH ||
- session_type_ == SessionType::A2DP_SOFTWARE_DECODING_DATAPATH ||
- session_type_ == SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH) {
- return;
- }
-
SourceMetadata hal_source_metadata;
hal_source_metadata.tracks.resize(track_count);
for (int i = 0; i < track_count; i++) {
@@ -519,33 +506,14 @@
<< toString(hal_source_metadata.tracks[i].contentType)
<< ", gain=" << hal_source_metadata.tracks[i].gain;
}
-
- auto hal_retval = stack_iface_->updateSourceMetadata(hal_source_metadata);
- if (!hal_retval.isOk()) {
- LOG(WARNING) << __func__ << " - IBluetoothAudioPort SessionType="
- << toString(session_type_) << " failed";
- }
+ UpdateSourceMetadata(hal_source_metadata);
}
void BluetoothAudioSession::UpdateSinkMetadata(
const struct sink_metadata& sink_metadata) {
- std::lock_guard<std::recursive_mutex> guard(mutex_);
- if (!IsSessionReady()) {
- LOG(DEBUG) << __func__ << " - SessionType=" << toString(session_type_)
- << " has NO session";
- return;
- }
-
ssize_t track_count = sink_metadata.track_count;
LOG(INFO) << __func__ << " - SessionType=" << toString(session_type_) << ","
<< track_count << " track(s)";
- if (session_type_ == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH ||
- session_type_ == SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH ||
- session_type_ == SessionType::A2DP_SOFTWARE_DECODING_DATAPATH ||
- session_type_ == SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH) {
- return;
- }
-
SinkMetadata hal_sink_metadata;
hal_sink_metadata.tracks.resize(track_count);
for (int i = 0; i < track_count; i++) {
@@ -560,12 +528,57 @@
<< ", dest_device_address="
<< sink_metadata.tracks[i].dest_device_address;
}
+ UpdateSinkMetadata(hal_sink_metadata);
+}
+
+bool BluetoothAudioSession::UpdateSourceMetadata(
+ const SourceMetadata& hal_source_metadata) {
+ std::lock_guard<std::recursive_mutex> guard(mutex_);
+ if (!IsSessionReady()) {
+ LOG(DEBUG) << __func__ << " - SessionType=" << toString(session_type_)
+ << " has NO session";
+ return false;
+ }
+
+ if (session_type_ == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH ||
+ session_type_ == SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH ||
+ session_type_ == SessionType::A2DP_SOFTWARE_DECODING_DATAPATH ||
+ session_type_ == SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH) {
+ return false;
+ }
+
+ auto hal_retval = stack_iface_->updateSourceMetadata(hal_source_metadata);
+ if (!hal_retval.isOk()) {
+ LOG(WARNING) << __func__ << " - IBluetoothAudioPort SessionType="
+ << toString(session_type_) << " failed";
+ return false;
+ }
+ return true;
+}
+
+bool BluetoothAudioSession::UpdateSinkMetadata(
+ const SinkMetadata& hal_sink_metadata) {
+ std::lock_guard<std::recursive_mutex> guard(mutex_);
+ if (!IsSessionReady()) {
+ LOG(DEBUG) << __func__ << " - SessionType=" << toString(session_type_)
+ << " has NO session";
+ return false;
+ }
+
+ if (session_type_ == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH ||
+ session_type_ == SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH ||
+ session_type_ == SessionType::A2DP_SOFTWARE_DECODING_DATAPATH ||
+ session_type_ == SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH) {
+ return false;
+ }
auto hal_retval = stack_iface_->updateSinkMetadata(hal_sink_metadata);
if (!hal_retval.isOk()) {
LOG(WARNING) << __func__ << " - IBluetoothAudioPort SessionType="
<< toString(session_type_) << " failed";
+ return false;
}
+ return true;
}
std::vector<LatencyMode> BluetoothAudioSession::GetSupportedLatencyModes() {
diff --git a/bluetooth/audio/utils/aidl_session/BluetoothAudioSession.h b/bluetooth/audio/utils/aidl_session/BluetoothAudioSession.h
index 5bf17bd..103a9ea 100644
--- a/bluetooth/audio/utils/aidl_session/BluetoothAudioSession.h
+++ b/bluetooth/audio/utils/aidl_session/BluetoothAudioSession.h
@@ -23,12 +23,15 @@
#include <aidl/android/hardware/bluetooth/audio/LatencyMode.h>
#include <aidl/android/hardware/bluetooth/audio/SessionType.h>
#include <fmq/AidlMessageQueue.h>
-#include <hardware/audio.h>
#include <mutex>
#include <unordered_map>
#include <vector>
+// To avoid inclusion of hardware/audio.h
+struct sink_metadata;
+struct source_metadata;
+
namespace aidl {
namespace android {
namespace hardware {
@@ -183,6 +186,9 @@
bool GetPresentationPosition(PresentationPosition& presentation_position);
void UpdateSourceMetadata(const struct source_metadata& source_metadata);
void UpdateSinkMetadata(const struct sink_metadata& sink_metadata);
+ // New versions for AIDL-only clients.
+ bool UpdateSourceMetadata(const SourceMetadata& hal_source_metadata);
+ bool UpdateSinkMetadata(const SinkMetadata& hal_sink_metadata);
std::vector<LatencyMode> GetSupportedLatencyModes();
void SetLatencyMode(const LatencyMode& latency_mode);
diff --git a/bluetooth/audio/utils/aidl_session/BluetoothAudioSessionControl.h b/bluetooth/audio/utils/aidl_session/BluetoothAudioSessionControl.h
index 0782c82..7ae0353 100644
--- a/bluetooth/audio/utils/aidl_session/BluetoothAudioSessionControl.h
+++ b/bluetooth/audio/utils/aidl_session/BluetoothAudioSessionControl.h
@@ -156,6 +156,26 @@
}
}
+ static bool UpdateSourceMetadata(const SessionType& session_type,
+ const SourceMetadata& source_metadata) {
+ std::shared_ptr<BluetoothAudioSession> session_ptr =
+ BluetoothAudioSessionInstance::GetSessionInstance(session_type);
+ if (session_ptr != nullptr) {
+ return session_ptr->UpdateSourceMetadata(source_metadata);
+ }
+ return false;
+ }
+
+ static bool UpdateSinkMetadata(const SessionType& session_type,
+ const SinkMetadata& sink_metadata) {
+ std::shared_ptr<BluetoothAudioSession> session_ptr =
+ BluetoothAudioSessionInstance::GetSessionInstance(session_type);
+ if (session_ptr != nullptr) {
+ return session_ptr->UpdateSinkMetadata(sink_metadata);
+ }
+ return false;
+ }
+
static std::vector<LatencyMode> GetSupportedLatencyModes(
const SessionType& session_type) {
std::shared_ptr<BluetoothAudioSession> session_ptr =
diff --git a/bluetooth/audio/utils/aidl_session/HidlToAidlMiddleware.cpp b/bluetooth/audio/utils/aidl_session/HidlToAidlMiddleware.cpp
index a4664f1..3d92ee7 100644
--- a/bluetooth/audio/utils/aidl_session/HidlToAidlMiddleware.cpp
+++ b/bluetooth/audio/utils/aidl_session/HidlToAidlMiddleware.cpp
@@ -583,7 +583,7 @@
*total_bytes_readed = presentation_position.transmittedOctets;
if (data_position)
*data_position = {
- .tv_sec = static_cast<__kernel_old_time_t>(
+ .tv_sec = static_cast<long>(
presentation_position.transmittedOctetsTimestamp.tvSec),
.tv_nsec = static_cast<long>(
presentation_position.transmittedOctetsTimestamp.tvNSec)};
diff --git a/broadcastradio/aidl/android/hardware/broadcastradio/Metadata.aidl b/broadcastradio/aidl/android/hardware/broadcastradio/Metadata.aidl
index 3298cac..7769b8c 100644
--- a/broadcastradio/aidl/android/hardware/broadcastradio/Metadata.aidl
+++ b/broadcastradio/aidl/android/hardware/broadcastradio/Metadata.aidl
@@ -70,9 +70,9 @@
/**
* Station name.
*
- * This is a generic field to cover any radio technology.
+ * <p>This is a generic field to cover any radio technology.
*
- * If the PROGRAM_NAME has the same content as DAB_*_NAME or RDS_PS,
+ * <p>Note: If the program name has the same content as dab*Name or ({@link Metadata#rdsPs},
* it may not be present, to preserve space - framework must repopulate
* it on the client side.
*/
@@ -86,10 +86,10 @@
/**
* DAB ensemble name abbreviated (string).
*
- * The string must be up to 8 characters long.
+ * <p>Note: The string must be up to 8 characters long.
*
- * If the short variant is present, the long (DAB_ENSEMBLE_NAME) one must be
- * present as well.
+ * <p>Note: If the short variant is present, the long ({@link Metadata#dabEnsembleName})
+ * one must be present as well.
*/
String dabEnsembleNameShort;
@@ -99,7 +99,9 @@
String dabServiceName;
/**
- * DAB service name abbreviated (see DAB_ENSEMBLE_NAME_SHORT) (string)
+ * DAB service name abbreviated (string)
+ *
+ * <p>Note: The string must be up to 8 characters long.
*/
String dabServiceNameShort;
@@ -109,7 +111,9 @@
String dabComponentName;
/**
- * DAB component name abbreviated (see DAB_ENSEMBLE_NAME_SHORT) (string)
+ * DAB component name abbreviated (string)
+ *
+ * <p>Note: The string must be up to 8 characters long.
*/
String dabComponentNameShort;
}
diff --git a/broadcastradio/aidl/android/hardware/broadcastradio/ProgramIdentifier.aidl b/broadcastradio/aidl/android/hardware/broadcastradio/ProgramIdentifier.aidl
index 2057d97..a2de5d6 100644
--- a/broadcastradio/aidl/android/hardware/broadcastradio/ProgramIdentifier.aidl
+++ b/broadcastradio/aidl/android/hardware/broadcastradio/ProgramIdentifier.aidl
@@ -30,8 +30,10 @@
IdentifierType type = IdentifierType.INVALID;
/**
- * The uint64_t value field holds the value in format described in comments
- * for IdentifierType enum.
+ * The value field holds the value in format described in comments for IdentifierType enum.
+ *
+ * The value should be 64-bit unsigned integer, but is represented as 64-bit signed integer
+ * in AIDL.
*/
long value;
}
diff --git a/broadcastradio/aidl/default/VirtualRadio.cpp b/broadcastradio/aidl/default/VirtualRadio.cpp
index 126bcff..86c5a96 100644
--- a/broadcastradio/aidl/default/VirtualRadio.cpp
+++ b/broadcastradio/aidl/default/VirtualRadio.cpp
@@ -53,18 +53,18 @@
static VirtualRadio amFmRadioMock(
"AM/FM radio mock",
{
- {makeSelectorAmfm(/* frequency= */ 94900), "Wild 94.9", "Drake ft. Rihanna",
+ {makeSelectorAmfm(/* frequency= */ 94900u), "Wild 94.9", "Drake ft. Rihanna",
"Too Good"},
- {makeSelectorAmfm(/* frequency= */ 96500), "KOIT", "Celine Dion", "All By Myself"},
- {makeSelectorAmfm(/* frequency= */ 97300), "Alice@97.3", "Drops of Jupiter", "Train"},
- {makeSelectorAmfm(/* frequency= */ 99700), "99.7 Now!", "The Chainsmokers", "Closer"},
- {makeSelectorAmfm(/* frequency= */ 101300), "101-3 KISS-FM", "Justin Timberlake",
+ {makeSelectorAmfm(/* frequency= */ 96500u), "KOIT", "Celine Dion", "All By Myself"},
+ {makeSelectorAmfm(/* frequency= */ 97300u), "Alice@97.3", "Drops of Jupiter", "Train"},
+ {makeSelectorAmfm(/* frequency= */ 99700u), "99.7 Now!", "The Chainsmokers", "Closer"},
+ {makeSelectorAmfm(/* frequency= */ 101300u), "101-3 KISS-FM", "Justin Timberlake",
"Rock Your Body"},
- {makeSelectorAmfm(/* frequency= */ 103700), "iHeart80s @ 103.7", "Michael Jackson",
+ {makeSelectorAmfm(/* frequency= */ 103700u), "iHeart80s @ 103.7", "Michael Jackson",
"Billie Jean"},
- {makeSelectorAmfm(/* frequency= */ 106100), "106 KMEL", "Drake", "Marvins Room"},
- {makeSelectorAmfm(/* frequency= */ 700), "700 AM", "Artist700", "Title700"},
- {makeSelectorAmfm(/* frequency= */ 1700), "1700 AM", "Artist1700", "Title1700"},
+ {makeSelectorAmfm(/* frequency= */ 106100u), "106 KMEL", "Drake", "Marvins Room"},
+ {makeSelectorAmfm(/* frequency= */ 700u), "700 AM", "Artist700", "Title700"},
+ {makeSelectorAmfm(/* frequency= */ 1700u), "1700 AM", "Artist1700", "Title1700"},
});
// clang-format on
return amFmRadioMock;
@@ -77,13 +77,13 @@
"DAB radio mock",
{
{makeSelectorDab(/* sidExt= */ 0xA000000001u, /* ensemble= */ 0x0001u,
- /* freq= */ 225648), "BBC Radio 1", "Khalid", "Talk"},
+ /* freq= */ 225648u), "BBC Radio 1", "Khalid", "Talk"},
{makeSelectorDab(/* sidExt= */ 0xB000000001u, /* ensemble= */ 0x1001u,
- /* freq= */ 222064), "Classic FM", "Jean Sibelius", "Andante Festivo"},
+ /* freq= */ 222064u), "Classic FM", "Jean Sibelius", "Andante Festivo"},
{makeSelectorDab(/* sidExt= */ 0xB000000002u, /* ensemble= */ 0x1002u,
- /* freq= */ 227360), "Absolute Radio", "Coldplay", "Clocks"},
+ /* freq= */ 227360u), "Absolute Radio", "Coldplay", "Clocks"},
{makeSelectorDab(/* sidExt= */ 0xB000000002u, /* ensemble= */ 0x1002u,
- /* freq= */ 222064), "Absolute Radio", "Coldplay", "Clocks"},
+ /* freq= */ 222064u), "Absolute Radio", "Coldplay", "Clocks"},
});
// clang-format on
return dabRadioMock;
diff --git a/broadcastradio/common/utilsaidl/Utils.cpp b/broadcastradio/common/utilsaidl/Utils.cpp
index 0551bad..de4f529 100644
--- a/broadcastradio/common/utilsaidl/Utils.cpp
+++ b/broadcastradio/common/utilsaidl/Utils.cpp
@@ -204,7 +204,7 @@
}
bool isValid(const ProgramIdentifier& id) {
- int64_t val = id.value;
+ uint64_t val = static_cast<uint64_t>(id.value);
bool valid = true;
auto expect = [&valid](bool condition, const string& message) {
@@ -231,11 +231,11 @@
expect(val <= 0xFFFFu, "16bit id");
break;
case IdentifierType::HD_STATION_ID_EXT: {
- int64_t stationId = val & 0xFFFFFFFF; // 32bit
+ uint64_t stationId = val & 0xFFFFFFFF; // 32bit
val >>= 32;
- int64_t subchannel = val & 0xF; // 4bit
+ uint64_t subchannel = val & 0xF; // 4bit
val >>= 4;
- int64_t freq = val & 0x3FFFF; // 18bit
+ uint64_t freq = val & 0x3FFFF; // 18bit
expect(stationId != 0u, "HD station id != 0");
expect(subchannel < 8u, "HD subch < 8");
expect(freq > 100u, "f > 100kHz");
@@ -252,9 +252,9 @@
break;
}
case IdentifierType::DAB_SID_EXT: {
- int64_t sid = val & 0xFFFFFFFF; // 32bit
+ uint64_t sid = val & 0xFFFFFFFF; // 32bit
val >>= 32;
- int64_t ecc = val & 0xFF; // 8bit
+ uint64_t ecc = val & 0xFF; // 8bit
expect(sid != 0u, "DAB SId != 0");
expect(ecc >= 0xA0u && ecc <= 0xF6u, "Invalid ECC, see ETSI TS 101 756 V2.1.1");
break;
@@ -305,19 +305,19 @@
return {type, value};
}
-ProgramSelector makeSelectorAmfm(int32_t frequency) {
+ProgramSelector makeSelectorAmfm(uint32_t frequency) {
ProgramSelector sel = {};
sel.primaryId = makeIdentifier(IdentifierType::AMFM_FREQUENCY_KHZ, frequency);
return sel;
}
-ProgramSelector makeSelectorDab(int64_t sidExt) {
+ProgramSelector makeSelectorDab(uint64_t sidExt) {
ProgramSelector sel = {};
sel.primaryId = makeIdentifier(IdentifierType::DAB_SID_EXT, sidExt);
return sel;
}
-ProgramSelector makeSelectorDab(int64_t sidExt, int32_t ensemble, int64_t freq) {
+ProgramSelector makeSelectorDab(uint64_t sidExt, uint32_t ensemble, uint64_t freq) {
ProgramSelector sel = {};
sel.primaryId = makeIdentifier(IdentifierType::DAB_SID_EXT, sidExt);
vector<ProgramIdentifier> secondaryIds = {
diff --git a/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h b/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h
index ad075f2..ee85a17 100644
--- a/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h
+++ b/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h
@@ -137,9 +137,9 @@
bool isValid(const ProgramSelector& sel);
ProgramIdentifier makeIdentifier(IdentifierType type, int64_t value);
-ProgramSelector makeSelectorAmfm(int32_t frequency);
-ProgramSelector makeSelectorDab(int64_t sidExt);
-ProgramSelector makeSelectorDab(int64_t sidExt, int32_t ensemble, int64_t freq);
+ProgramSelector makeSelectorAmfm(uint32_t frequency);
+ProgramSelector makeSelectorDab(uint64_t sidExt);
+ProgramSelector makeSelectorDab(uint64_t sidExt, uint32_t ensemble, uint64_t freq);
bool satisfies(const ProgramFilter& filter, const ProgramSelector& sel);
diff --git a/drm/aidl/Android.bp b/drm/aidl/Android.bp
index fb04d84..afcb603 100644
--- a/drm/aidl/Android.bp
+++ b/drm/aidl/Android.bp
@@ -23,7 +23,7 @@
sdk_version: "module_current",
},
ndk: {
- min_sdk_version: "UpsideDownCake",
+ min_sdk_version: "34",
},
},
double_loadable: true,
diff --git a/gnss/aidl/vts/gnss_hal_test.cpp b/gnss/aidl/vts/gnss_hal_test.cpp
index 4f5e6a0..5e2cbe3 100644
--- a/gnss/aidl/vts/gnss_hal_test.cpp
+++ b/gnss/aidl/vts/gnss_hal_test.cpp
@@ -486,8 +486,6 @@
auto status = aidl_gnss_hal_->startSvStatus();
EXPECT_TRUE(status.isOk());
- ASSERT_TRUE(aidl_gnss_cb_->sv_info_list_timestamps_millis_cbq_.size() ==
- aidl_gnss_cb_->sv_info_list_cbq_.size());
long lastElapsedRealtimeMillis = 0;
for (int i = 0; i < numMeasurementEvents; i++) {
long timeStamp;
diff --git a/wifi/aidl/default/aidl_struct_util.cpp b/wifi/aidl/default/aidl_struct_util.cpp
index 7bc2eeb..83e1193 100644
--- a/wifi/aidl/default/aidl_struct_util.cpp
+++ b/wifi/aidl/default/aidl_struct_util.cpp
@@ -887,6 +887,15 @@
return true;
}
+StaLinkLayerLinkStats::StaLinkState convertLegacyMlLinkStateToAidl(wifi_link_state state) {
+ if (state == wifi_link_state::WIFI_LINK_STATE_NOT_IN_USE) {
+ return StaLinkLayerLinkStats::StaLinkState::NOT_IN_USE;
+ } else if (state == wifi_link_state::WIFI_LINK_STATE_IN_USE) {
+ return StaLinkLayerLinkStats::StaLinkState::IN_USE;
+ }
+ return StaLinkLayerLinkStats::StaLinkState::UNKNOWN;
+}
+
bool convertLegacyLinkLayerMlStatsToAidl(const legacy_hal::LinkLayerMlStats& legacy_ml_stats,
StaLinkLayerStats* aidl_stats) {
if (!aidl_stats) {
@@ -898,6 +907,7 @@
for (const auto& link : legacy_ml_stats.links) {
StaLinkLayerLinkStats linkStats = {};
linkStats.linkId = link.stat.link_id;
+ linkStats.state = convertLegacyMlLinkStateToAidl(link.stat.state);
linkStats.radioId = link.stat.radio;
linkStats.frequencyMhz = link.stat.frequency;
linkStats.beaconRx = link.stat.beacon_rx;
diff --git a/wifi/aidl/default/tests/aidl_struct_util_unit_tests.cpp b/wifi/aidl/default/tests/aidl_struct_util_unit_tests.cpp
index 5c334f8..995a13d 100644
--- a/wifi/aidl/default/tests/aidl_struct_util_unit_tests.cpp
+++ b/wifi/aidl/default/tests/aidl_struct_util_unit_tests.cpp
@@ -123,6 +123,9 @@
// Add two radio stats
legacy_ml_stats.radios.push_back(legacy_hal::LinkLayerRadioStats{});
legacy_ml_stats.radios.push_back(legacy_hal::LinkLayerRadioStats{});
+ wifi_link_state states[sizeof(wifi_link_state)] = {wifi_link_state::WIFI_LINK_STATE_UNKNOWN,
+ wifi_link_state::WIFI_LINK_STATE_NOT_IN_USE,
+ wifi_link_state::WIFI_LINK_STATE_IN_USE};
// Add two links.
legacy_ml_stats.links.push_back(legacy_hal::LinkStats{});
legacy_ml_stats.links.push_back(legacy_hal::LinkStats{});
@@ -133,6 +136,7 @@
link.stat.beacon_rx = rand();
// MLO link id: 0 - 15
link.stat.link_id = rand() % 16;
+ link.stat.state = states[rand() % sizeof(states)];
// Maximum number of radios is limited to 3 for testing.
link.stat.radio = rand() % 4;
link.stat.frequency = rand();
@@ -241,6 +245,18 @@
int l = 0;
for (legacy_hal::LinkStats& link : legacy_ml_stats.links) {
EXPECT_EQ(link.stat.link_id, (uint8_t)converted.iface.links[l].linkId);
+ StaLinkLayerLinkStats::StaLinkState expectedState;
+ switch (link.stat.state) {
+ case wifi_link_state::WIFI_LINK_STATE_NOT_IN_USE:
+ expectedState = StaLinkLayerLinkStats::StaLinkState::NOT_IN_USE;
+ break;
+ case wifi_link_state::WIFI_LINK_STATE_IN_USE:
+ expectedState = StaLinkLayerLinkStats::StaLinkState::IN_USE;
+ break;
+ default:
+ expectedState = StaLinkLayerLinkStats::StaLinkState::UNKNOWN;
+ }
+ EXPECT_EQ(expectedState, converted.iface.links[l].state);
EXPECT_EQ(link.stat.radio, converted.iface.links[l].radioId);
EXPECT_EQ(link.stat.frequency, (uint32_t)converted.iface.links[l].frequencyMhz);
EXPECT_EQ(link.stat.beacon_rx, (uint32_t)converted.iface.links[l].beaconRx);
diff --git a/wifi/aidl/default/wifi_chip.cpp b/wifi/aidl/default/wifi_chip.cpp
index 6dd9156..8265e5b 100644
--- a/wifi/aidl/default/wifi_chip.cpp
+++ b/wifi/aidl/default/wifi_chip.cpp
@@ -1452,14 +1452,24 @@
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
LOG(ERROR) << "Failed to get SupportedRadioCombinations matrix from legacy HAL: "
<< legacyErrorToString(legacy_status);
+ if (legacy_matrix != nullptr) {
+ free(legacy_matrix);
+ }
return {aidl_combinations, createWifiStatusFromLegacyError(legacy_status)};
}
if (!aidl_struct_util::convertLegacyRadioCombinationsMatrixToAidl(legacy_matrix,
&aidl_combinations)) {
LOG(ERROR) << "Failed convertLegacyRadioCombinationsMatrixToAidl() ";
+ if (legacy_matrix != nullptr) {
+ free(legacy_matrix);
+ }
return {aidl_combinations, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
}
+
+ if (legacy_matrix != nullptr) {
+ free(legacy_matrix);
+ }
return {aidl_combinations, ndk::ScopedAStatus::ok()};
}