Merge "audio: add feature flag for new headset profile and SCO audio management" into main
diff --git a/drm/mediadrm/plugins/clearkey/aidl/Android.bp b/drm/mediadrm/plugins/clearkey/aidl/Android.bp
index 0b0d46a..9a06bd2 100644
--- a/drm/mediadrm/plugins/clearkey/aidl/Android.bp
+++ b/drm/mediadrm/plugins/clearkey/aidl/Android.bp
@@ -107,6 +107,17 @@
installable: false, // installed in APEX
}
+cc_binary {
+ name: "android.hardware.drm-service-lazy.clearkey.apex",
+ stem: "android.hardware.drm-service-lazy.clearkey",
+ defaults: [
+ "aidl_clearkey_service_defaults",
+ "aidl_clearkey_service_defaults-use-static-deps",
+ ],
+ srcs: ["ServiceLazy.cpp"],
+ installable: false, // installed in APEX
+}
+
phony {
name: "android.hardware.drm@latest-service.clearkey",
required: [
@@ -183,17 +194,63 @@
"android.hardware.drm-service.clearkey.apex.rc",
"android.hardware.drm-service.clearkey.xml"
],
+ overrides: [
+ "android.hardware.drm-service.clearkey",
+ ],
}
prebuilt_etc {
name: "android.hardware.drm-service.clearkey.apex.rc",
- src: "android.hardware.drm-service.clearkey.apex.rc",
+ src: ":gen-android.hardware.drm-service.clearkey.apex.rc",
installable: false,
}
+genrule {
+ name: "gen-android.hardware.drm-service.clearkey.apex.rc",
+ srcs: ["android.hardware.drm-service.clearkey.rc"],
+ out: ["android.hardware.drm-service.clearkey.apex.rc"],
+ cmd: "sed -E 's%/vendor/bin/%/apex/com.android.hardware.drm.clearkey/bin/%' $(in) > $(out)",
+}
+
prebuilt_etc {
name: "android.hardware.drm-service.clearkey.xml",
src: "android.hardware.drm-service.clearkey.xml",
sub_dir: "vintf",
installable: false,
}
+
+apex {
+ name: "com.android.hardware.drm.clearkey.lazy",
+ manifest: "manifest.json",
+ file_contexts: "file_contexts",
+ key: "com.android.hardware.key",
+ certificate: ":com.android.hardware.certificate",
+ vendor: true,
+ updatable: false,
+
+ binaries: [
+ "android.hardware.drm-service-lazy.clearkey.apex",
+ ],
+ prebuilts: [
+ "android.hardware.drm-service-lazy.clearkey.apex.rc",
+ "android.hardware.drm-service.clearkey.xml"
+ ],
+ overrides: [
+ "android.hardware.drm-service.clearkey",
+ "android.hardware.drm-service-lazy.clearkey",
+ "com.android.hardware.drm.clearkey",
+ ],
+}
+
+prebuilt_etc {
+ name: "android.hardware.drm-service-lazy.clearkey.apex.rc",
+ src: ":gen-android.hardware.drm-service-lazy.clearkey.apex.rc",
+ installable: false,
+}
+
+genrule {
+ name: "gen-android.hardware.drm-service-lazy.clearkey.apex.rc",
+ srcs: ["android.hardware.drm-service-lazy.clearkey.rc"],
+ out: ["android.hardware.drm-service-lazy.clearkey.apex.rc"],
+ cmd: "sed -E 's%/vendor/bin/%/apex/com.android.hardware.drm.clearkey/bin/%' $(in) > $(out)",
+}
diff --git a/drm/mediadrm/plugins/clearkey/aidl/android.hardware.drm-service.clearkey.apex.rc b/drm/mediadrm/plugins/clearkey/aidl/android.hardware.drm-service.clearkey.apex.rc
deleted file mode 100644
index f4645b3..0000000
--- a/drm/mediadrm/plugins/clearkey/aidl/android.hardware.drm-service.clearkey.apex.rc
+++ /dev/null
@@ -1,7 +0,0 @@
-service vendor.drm-clearkey-service /apex/com.android.hardware.drm.clearkey/bin/hw/android.hardware.drm-service.clearkey
- class hal
- user media
- group mediadrm drmrpc
- ioprio rt 4
- task_profiles ProcessCapacityHigh
- interface aidl android.hardware.drm.IDrmFactory/clearkey
diff --git a/media/aconfig/codec_fwk.aconfig b/media/aconfig/codec_fwk.aconfig
index 3092091..a2b6a82 100644
--- a/media/aconfig/codec_fwk.aconfig
+++ b/media/aconfig/codec_fwk.aconfig
@@ -14,6 +14,7 @@
flag {
name: "dynamic_color_aspects"
+ is_exported: true
namespace: "codec_fwk"
description: "Feature flag for dynamic color aspect support"
bug: "297914560"
@@ -21,6 +22,7 @@
flag {
name: "hlg_editing"
+ is_exported: true
namespace: "codec_fwk"
description: "Feature flag for HLG editing support"
bug: "316397061"
@@ -28,6 +30,7 @@
flag {
name: "in_process_sw_audio_codec"
+ is_exported: true
namespace: "codec_fwk"
description: "Feature flag for in-process software audio codec API"
bug: "297922713"
@@ -48,7 +51,15 @@
}
flag {
+ name: "native_capabilites"
+ namespace: "codec_fwk"
+ description: "Feature flag for native codec capabilities"
+ bug: "306023029"
+}
+
+flag {
name: "null_output_surface"
+ is_exported: true
namespace: "codec_fwk"
description: "Feature flag for null output Surface API"
bug: "297920102"
@@ -63,6 +74,7 @@
flag {
name: "region_of_interest"
+ is_exported: true
namespace: "codec_fwk"
description: "Feature flag for region of interest API"
bug: "299191092"
@@ -74,3 +86,10 @@
description: "Feature flag for region of interest support"
bug: "325549730"
}
+
+flag {
+ name: "teamfood"
+ namespace: "codec_fwk"
+ description: "Feature flag to track teamfood population"
+ bug: "328770262"
+}
diff --git a/media/aconfig/mediacodec_flags.aconfig b/media/aconfig/mediacodec_flags.aconfig
index 4d1e5ca..3cc9a1a 100644
--- a/media/aconfig/mediacodec_flags.aconfig
+++ b/media/aconfig/mediacodec_flags.aconfig
@@ -7,22 +7,23 @@
# ******************************************************************
flag {
- name: "large_audio_frame"
+ name: "aidl_hal"
namespace: "codec_fwk"
- description: "Feature flags for large audio frame support"
- bug: "297219557"
+ description: "Feature flags for enabling AIDL HAL handling"
+ bug: "251850069"
}
flag {
name: "codec_importance"
+ is_exported: true
namespace: "codec_fwk"
description: "Feature flags for media codec importance"
bug: "297929011"
}
flag {
- name: "aidl_hal"
+ name: "large_audio_frame"
namespace: "codec_fwk"
- description: "Feature flags for enabling AIDL HAL handling"
- bug: "251850069"
+ description: "Feature flags for large audio frame support"
+ bug: "297219557"
}
diff --git a/media/audio/aconfig/audio_framework.aconfig b/media/audio/aconfig/audio_framework.aconfig
index 7191e20..b7ec093 100644
--- a/media/audio/aconfig/audio_framework.aconfig
+++ b/media/audio/aconfig/audio_framework.aconfig
@@ -4,6 +4,7 @@
# Please add flags in alphabetical order.
package: "android.media.audio"
+container: "system"
flag {
name: "auto_public_volume_api_hardening"
diff --git a/media/audioserver/main_audioserver.cpp b/media/audioserver/main_audioserver.cpp
index c7a1bfd..55847f4 100644
--- a/media/audioserver/main_audioserver.cpp
+++ b/media/audioserver/main_audioserver.cpp
@@ -169,6 +169,11 @@
"%s: AudioSystem already has an AudioFlinger instance!", __func__);
const auto aps = sp<AudioPolicyService>::make();
ALOGD("%s: AudioPolicy created", __func__);
+ ALOGW_IF(AudioSystem::setLocalAudioPolicyService(aps) != OK,
+ "%s: AudioSystem already has an AudioPolicyService instance!", __func__);
+
+ // Start initialization of internally managed audio objects such as Device Effects.
+ aps->onAudioSystemReady();
// Add AudioFlinger and AudioPolicy to ServiceManager.
sp<IServiceManager> sm = defaultServiceManager();
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/Android.bp b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/Android.bp
new file mode 100644
index 0000000..c4afffb
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/Android.bp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+cc_library {
+ name: "libaudiomockhal",
+
+ defaults: [
+ "latest_android_hardware_audio_core_ndk_shared",
+ "latest_android_hardware_audio_core_sounddose_ndk_shared",
+ "latest_android_hardware_audio_effect_ndk_shared",
+ ],
+ header_libs: [
+ "libbinder_headers",
+ ],
+ static_libs: [
+ "libbinder_random_parcel",
+ ],
+ shared_libs: [
+ "libbinder_ndk",
+ ],
+
+ host_supported: true,
+ srcs: [
+ "FactoryMock.cpp",
+ "ModuleMock.cpp",
+ "StreamInMock.cpp",
+ "StreamOutMock.cpp",
+ ],
+ target: {
+ darwin: {
+ enabled: false,
+ },
+ },
+ export_include_dirs: ["include"],
+}
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/FactoryMock.cpp b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/FactoryMock.cpp
new file mode 100644
index 0000000..ea07afc
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/FactoryMock.cpp
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2024 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 "effect-mock/FactoryMock.h"
+#include "effect-mock/EffectMock.h"
+
+namespace aidl::android::hardware::audio::effect {
+
+ndk::ScopedAStatus FactoryMock::createEffect(const AudioUuid&,
+ std::shared_ptr<IEffect>* _aidl_return) {
+ *_aidl_return = ndk::SharedRefBase::make<EffectMock>();
+ return ndk::ScopedAStatus::ok();
+}
+
+} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/ModuleMock.cpp b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/ModuleMock.cpp
new file mode 100644
index 0000000..711924f
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/ModuleMock.cpp
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2024 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 "core-mock/ModuleMock.h"
+#include "core-mock/BluetoothA2dpMock.h"
+#include "core-mock/BluetoothLeMock.h"
+#include "core-mock/BluetoothMock.h"
+#include "core-mock/StreamInMock.h"
+#include "core-mock/StreamOutMock.h"
+#include "core-mock/TelephonyMock.h"
+#include "sounddose-mock/SoundDoseMock.h"
+
+namespace aidl::android::hardware::audio::core {
+
+ModuleMock::ModuleMock() {
+ // Device ports
+ auto outDevice = createPort(/* PortId */ 0, /* Name */ "Default",
+ /* Flags */ 1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE,
+ /* isInput */ false,
+ createDeviceExt(
+ /* DeviceType */ AudioDeviceType::OUT_DEFAULT,
+ /* Flags */ AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE));
+ mPorts.push_back(outDevice);
+ auto inDevice = createPort(/* PortId */ 1, /* Name */ "Default",
+ /* Flags */ 1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE,
+ /* isInput */ true,
+ createDeviceExt(
+ /* DeviceType */ AudioDeviceType::IN_DEFAULT,
+ /* Flags */ 0));
+ mPorts.push_back(outDevice);
+}
+
+ndk::ScopedAStatus ModuleMock::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
+ *_aidl_return = ndk::SharedRefBase::make<TelephonyMock>();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
+ *_aidl_return = ndk::SharedRefBase::make<BluetoothMock>();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
+ *_aidl_return = ndk::SharedRefBase::make<BluetoothA2dpMock>();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
+ *_aidl_return = ndk::SharedRefBase::make<BluetoothLeMock>();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::openInputStream(const OpenInputStreamArguments&,
+ OpenInputStreamReturn* _aidl_return) {
+ _aidl_return->stream = ndk::SharedRefBase::make<StreamInMock>();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::openOutputStream(const OpenOutputStreamArguments&,
+ OpenOutputStreamReturn* _aidl_return) {
+ _aidl_return->stream = ndk::SharedRefBase::make<StreamOutMock>();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::getMasterMute(bool* _aidl_return) {
+ *_aidl_return = mMasterMute;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::setMasterMute(bool masterMute) {
+ mMasterMute = masterMute;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::getMasterVolume(float* _aidl_return) {
+ *_aidl_return = mMasterVolume;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::setMasterVolume(float masterVolume) {
+ mMasterVolume = masterVolume;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::getMicMute(bool* _aidl_return) {
+ *_aidl_return = mMicMute;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::setMicMute(bool micMute) {
+ mMicMute = micMute;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
+ *_aidl_return = ndk::SharedRefBase::make<SoundDoseMock>();
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::getMmapPolicyInfos(AudioMMapPolicyType,
+ std::vector<AudioMMapPolicyInfo>* _aidl_return) {
+ AudioMMapPolicyInfo never;
+ never.mmapPolicy = AudioMMapPolicy::NEVER;
+ _aidl_return->push_back(never);
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus ModuleMock::supportsVariableLatency(bool* _aidl_return) {
+ *_aidl_return = false;
+ return ndk::ScopedAStatus::ok();
+}
+
+AudioPortExt ModuleMock::createDeviceExt(AudioDeviceType devType, int32_t flags) {
+ AudioPortDeviceExt deviceExt;
+ deviceExt.device.type.type = devType;
+ deviceExt.flags = flags;
+ return AudioPortExt::make<AudioPortExt::Tag::device>(deviceExt);
+}
+
+AudioPort ModuleMock::createPort(int32_t id, const std::string& name, int32_t flags, bool isInput,
+ const AudioPortExt& ext) {
+ AudioPort port;
+ port.id = id;
+ port.name = name;
+ port.flags = isInput ? AudioIoFlags::make<AudioIoFlags::Tag::input>(flags)
+ : AudioIoFlags::make<AudioIoFlags::Tag::output>(flags);
+ port.ext = ext;
+ return port;
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/StreamInMock.cpp b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/StreamInMock.cpp
new file mode 100644
index 0000000..093a979
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/StreamInMock.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2024 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 "core-mock/StreamInMock.h"
+#include "core-mock/StreamCommonMock.h"
+
+namespace aidl::android::hardware::audio::core {
+
+ndk::ScopedAStatus StreamInMock::getStreamCommon(std::shared_ptr<IStreamCommon>* _aidl_return) {
+ if (!mStreamCommon) {
+ mStreamCommon = ndk::SharedRefBase::make<StreamCommonMock>();
+ }
+ *_aidl_return = mStreamCommon;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamInMock::getMicrophoneDirection(
+ IStreamIn::MicrophoneDirection* _aidl_return) {
+ *_aidl_return = mMicrophoneDirection;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamInMock::setMicrophoneDirection(
+ IStreamIn::MicrophoneDirection in_direction) {
+ mMicrophoneDirection = in_direction;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamInMock::getMicrophoneFieldDimension(float* _aidl_return) {
+ *_aidl_return = mMicrophoneFieldDimension;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamInMock::setMicrophoneFieldDimension(float in_zoom) {
+ mMicrophoneFieldDimension = in_zoom;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamInMock::getHwGain(std::vector<float>* _aidl_return) {
+ *_aidl_return = mHwGains;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamInMock::setHwGain(const std::vector<float>& in_channelGains) {
+ mHwGains = in_channelGains;
+ return ndk::ScopedAStatus::ok();
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/StreamOutMock.cpp b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/StreamOutMock.cpp
new file mode 100644
index 0000000..a71f954
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/StreamOutMock.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2024 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 "core-mock/StreamOutMock.h"
+#include "core-mock/StreamCommonMock.h"
+
+namespace aidl::android::hardware::audio::core {
+
+ndk::ScopedAStatus StreamOutMock::getStreamCommon(std::shared_ptr<IStreamCommon>* _aidl_return) {
+ if (!mStreamCommon) {
+ mStreamCommon = ndk::SharedRefBase::make<StreamCommonMock>();
+ }
+ *_aidl_return = mStreamCommon;
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus StreamOutMock::getHwVolume(std::vector<float>* _aidl_return) {
+ *_aidl_return = mHwVolume;
+ return ndk::ScopedAStatus::ok();
+}
+ndk::ScopedAStatus StreamOutMock::setHwVolume(const std::vector<float>& in_channelVolumes) {
+ mHwVolume = in_channelVolumes;
+ return ndk::ScopedAStatus::ok();
+}
+ndk::ScopedAStatus StreamOutMock::getAudioDescriptionMixLevel(float* _aidl_return) {
+ *_aidl_return = mAudioDescriptionMixLeveldB;
+ return ndk::ScopedAStatus::ok();
+}
+ndk::ScopedAStatus StreamOutMock::setAudioDescriptionMixLevel(float in_leveldB) {
+ mAudioDescriptionMixLeveldB = in_leveldB;
+ return ndk::ScopedAStatus::ok();
+}
+ndk::ScopedAStatus StreamOutMock::getDualMonoMode(AudioDualMonoMode* _aidl_return) {
+ *_aidl_return = mDualMonoMode;
+ return ndk::ScopedAStatus::ok();
+}
+ndk::ScopedAStatus StreamOutMock::setDualMonoMode(AudioDualMonoMode in_mode) {
+ mDualMonoMode = in_mode;
+ return ndk::ScopedAStatus::ok();
+}
+ndk::ScopedAStatus StreamOutMock::getPlaybackRateParameters(AudioPlaybackRate* _aidl_return) {
+ *_aidl_return = mPlaybackRateParameters;
+ return ndk::ScopedAStatus::ok();
+}
+ndk::ScopedAStatus StreamOutMock::setPlaybackRateParameters(
+ const AudioPlaybackRate& in_playbackRate) {
+ mPlaybackRateParameters = in_playbackRate;
+ return ndk::ScopedAStatus::ok();
+}
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/BluetoothA2dpMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/BluetoothA2dpMock.h
new file mode 100644
index 0000000..c4dd0d9
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/BluetoothA2dpMock.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/BnBluetoothA2dp.h>
+
+using namespace aidl::android::hardware::audio::core;
+
+namespace aidl::android::hardware::audio::core {
+
+class BluetoothA2dpMock : public BnBluetoothA2dp {
+ public:
+ ndk::ScopedAStatus isEnabled(bool* _aidl_return) override {
+ *_aidl_return = mEnabled;
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus setEnabled(bool enabled) override {
+ mEnabled = enabled;
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus supportsOffloadReconfiguration(bool* _aidl_return) override {
+ *_aidl_return = kSupportsOffloadReconfiguration;
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus reconfigureOffload(const std::vector<VendorParameter>&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+
+ private:
+ static constexpr bool kSupportsOffloadReconfiguration = true;
+ bool mEnabled = false;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/BluetoothLeMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/BluetoothLeMock.h
new file mode 100644
index 0000000..d58695a
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/BluetoothLeMock.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/BnBluetoothLe.h>
+
+using namespace aidl::android::hardware::audio::core;
+
+namespace aidl::android::hardware::audio::core {
+
+class BluetoothLeMock : public BnBluetoothLe {
+ public:
+ ndk::ScopedAStatus isEnabled(bool* _aidl_return) override {
+ *_aidl_return = mEnabled;
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus setEnabled(bool enabled) override {
+ mEnabled = enabled;
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus supportsOffloadReconfiguration(bool* _aidl_return) override {
+ *_aidl_return = kSupportsOffloadReconfiguration;
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus reconfigureOffload(const std::vector<VendorParameter>&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+
+ private:
+ static constexpr bool kSupportsOffloadReconfiguration = true;
+ bool mEnabled = false;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/BluetoothMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/BluetoothMock.h
new file mode 100644
index 0000000..e805840
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/BluetoothMock.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/BnBluetooth.h>
+
+using namespace aidl::android::hardware::audio::core;
+
+namespace aidl::android::hardware::audio::core {
+
+class BluetoothMock : public BnBluetooth {
+ public:
+ ndk::ScopedAStatus setScoConfig(const IBluetooth::ScoConfig&, IBluetooth::ScoConfig*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus setHfpConfig(const IBluetooth::HfpConfig&, IBluetooth::HfpConfig*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/ConfigMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/ConfigMock.h
new file mode 100644
index 0000000..f4031b5
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/ConfigMock.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/BnConfig.h>
+
+using namespace aidl::android::media::audio::common;
+using namespace aidl::android::hardware::audio::core;
+
+namespace aidl::android::hardware::audio::core {
+
+class ConfigMock : public BnConfig {
+ private:
+ ndk::ScopedAStatus getSurroundSoundConfig(SurroundSoundConfig*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getEngineConfig(AudioHalEngineConfig*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/ModuleMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/ModuleMock.h
new file mode 100644
index 0000000..d49203d
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/ModuleMock.h
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/BnModule.h>
+
+using namespace aidl::android::media::audio::common;
+using namespace aidl::android::hardware::audio::core;
+using namespace aidl::android::hardware::audio::core::sounddose;
+using namespace aidl::android::hardware::audio::effect;
+
+namespace aidl::android::hardware::audio::core {
+
+class ModuleMock : public BnModule {
+ public:
+ ModuleMock();
+
+ private:
+ ndk::ScopedAStatus getTelephony(std::shared_ptr<ITelephony>*) override;
+ ndk::ScopedAStatus getBluetooth(std::shared_ptr<IBluetooth>*) override;
+ ndk::ScopedAStatus getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>*) override;
+ ndk::ScopedAStatus getBluetoothLe(std::shared_ptr<IBluetoothLe>*) override;
+ ndk::ScopedAStatus openInputStream(const OpenInputStreamArguments&,
+ OpenInputStreamReturn*) override;
+ ndk::ScopedAStatus openOutputStream(const OpenOutputStreamArguments&,
+ OpenOutputStreamReturn*) override;
+ ndk::ScopedAStatus getMasterMute(bool*) override;
+ ndk::ScopedAStatus setMasterMute(bool) override;
+ ndk::ScopedAStatus getMasterVolume(float*) override;
+ ndk::ScopedAStatus setMasterVolume(float) override;
+ ndk::ScopedAStatus getMicMute(bool*) override;
+ ndk::ScopedAStatus setMicMute(bool) override;
+ ndk::ScopedAStatus getSoundDose(std::shared_ptr<ISoundDose>*) override;
+ ndk::ScopedAStatus getMmapPolicyInfos(AudioMMapPolicyType,
+ std::vector<AudioMMapPolicyInfo>*) override;
+ ndk::ScopedAStatus supportsVariableLatency(bool*) override;
+
+ ndk::ScopedAStatus setModuleDebug(const ModuleDebug&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus connectExternalDevice(const AudioPort&, AudioPort*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus disconnectExternalDevice(int32_t) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getAudioPatches(std::vector<AudioPatch>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getAudioPort(int32_t, AudioPort*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getAudioPortConfigs(std::vector<AudioPortConfig>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getAudioPorts(std::vector<AudioPort>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getAudioRoutes(std::vector<AudioRoute>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getAudioRoutesForAudioPort(int32_t, std::vector<AudioRoute>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getSupportedPlaybackRateFactors(SupportedPlaybackRateFactors*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus setAudioPatch(const AudioPatch&, AudioPatch*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus setAudioPortConfig(const AudioPortConfig&, AudioPortConfig*,
+ bool*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus resetAudioPatch(int32_t) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus resetAudioPortConfig(int32_t) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus getMicrophones(std::vector<MicrophoneInfo>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus updateAudioMode(AudioMode) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus updateScreenRotation(ScreenRotation) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus updateScreenState(bool) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus generateHwAvSyncId(int32_t*) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ ndk::ScopedAStatus getVendorParameters(const std::vector<std::string>&,
+ std::vector<VendorParameter>*) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ ndk::ScopedAStatus setVendorParameters(const std::vector<VendorParameter>&, bool) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ ndk::ScopedAStatus addDeviceEffect(int32_t, const std::shared_ptr<IEffect>&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus removeDeviceEffect(int32_t, const std::shared_ptr<IEffect>&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getAAudioMixerBurstCount(int32_t*) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ ndk::ScopedAStatus getAAudioHardwareBurstMinUsec(int32_t*) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ ndk::ScopedAStatus prepareToDisconnectExternalDevice(int32_t) override {
+ return ndk::ScopedAStatus::ok();
+ }
+
+ AudioPortExt createDeviceExt(AudioDeviceType devType, int32_t flags);
+ AudioPort createPort(int32_t id, const std::string& name, int32_t flags, bool isInput,
+ const AudioPortExt& ext);
+
+ bool mMasterMute;
+ float mMasterVolume;
+ bool mMicMute;
+ std::vector<AudioPort> mPorts;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/StreamCommonMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/StreamCommonMock.h
new file mode 100644
index 0000000..25d53f8
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/StreamCommonMock.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/BnStreamCommon.h>
+
+using namespace aidl::android::hardware::audio::core;
+using namespace aidl::android::hardware::audio::effect;
+
+namespace aidl::android::hardware::audio::core {
+
+class StreamCommonMock : public BnStreamCommon {
+ ndk::ScopedAStatus close() override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus prepareToClose() override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus updateHwAvSyncId(int32_t) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus getVendorParameters(const std::vector<std::string>&,
+ std::vector<VendorParameter>*) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ ndk::ScopedAStatus setVendorParameters(const std::vector<VendorParameter>&, bool) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ ndk::ScopedAStatus addEffect(const std::shared_ptr<IEffect>&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus removeEffect(const std::shared_ptr<IEffect>&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/StreamInMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/StreamInMock.h
new file mode 100644
index 0000000..5deab5b
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/StreamInMock.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/BnStreamIn.h>
+
+using namespace aidl::android::hardware::audio::common;
+using namespace aidl::android::hardware::audio::core;
+using namespace aidl::android::media::audio::common;
+
+namespace aidl::android::hardware::audio::core {
+
+class StreamInMock : public BnStreamIn {
+ ndk::ScopedAStatus getStreamCommon(std::shared_ptr<IStreamCommon>* _aidl_return) override;
+ ndk::ScopedAStatus getMicrophoneDirection(
+ IStreamIn::MicrophoneDirection* _aidl_return) override;
+ ndk::ScopedAStatus setMicrophoneDirection(IStreamIn::MicrophoneDirection in_direction) override;
+ ndk::ScopedAStatus getMicrophoneFieldDimension(float* _aidl_return) override;
+ ndk::ScopedAStatus setMicrophoneFieldDimension(float in_zoom) override;
+ ndk::ScopedAStatus getHwGain(std::vector<float>* _aidl_return) override;
+ ndk::ScopedAStatus setHwGain(const std::vector<float>& in_channelGains) override;
+
+ ndk::ScopedAStatus getActiveMicrophones(std::vector<MicrophoneDynamicInfo>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus updateMetadata(const SinkMetadata&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+
+ private:
+ IStreamIn::MicrophoneDirection mMicrophoneDirection;
+ float mMicrophoneFieldDimension;
+ std::vector<float> mHwGains;
+ std::shared_ptr<IStreamCommon> mStreamCommon;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/StreamOutMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/StreamOutMock.h
new file mode 100644
index 0000000..4d12815
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/StreamOutMock.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/BnStreamOut.h>
+
+using namespace aidl::android::hardware::audio::common;
+using namespace aidl::android::hardware::audio::core;
+using namespace aidl::android::media::audio::common;
+
+namespace aidl::android::hardware::audio::core {
+
+class StreamOutMock : public BnStreamOut {
+ ndk::ScopedAStatus getStreamCommon(std::shared_ptr<IStreamCommon>* _aidl_return) override;
+ ndk::ScopedAStatus getHwVolume(std::vector<float>* _aidl_return) override;
+ ndk::ScopedAStatus setHwVolume(const std::vector<float>& in_channelVolumes) override;
+ ndk::ScopedAStatus getAudioDescriptionMixLevel(float* _aidl_return) override;
+ ndk::ScopedAStatus setAudioDescriptionMixLevel(float in_leveldB) override;
+ ndk::ScopedAStatus getDualMonoMode(AudioDualMonoMode* _aidl_return) override;
+ ndk::ScopedAStatus setDualMonoMode(AudioDualMonoMode in_mode) override;
+ ndk::ScopedAStatus getPlaybackRateParameters(AudioPlaybackRate* _aidl_return) override;
+ ndk::ScopedAStatus setPlaybackRateParameters(const AudioPlaybackRate& in_playbackRate) override;
+
+ ndk::ScopedAStatus updateMetadata(const SourceMetadata&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus updateOffloadMetadata(const AudioOffloadMetadata&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getRecommendedLatencyModes(std::vector<AudioLatencyMode>*) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ ndk::ScopedAStatus setLatencyMode(AudioLatencyMode) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+ ndk::ScopedAStatus selectPresentation(int32_t, int32_t) override {
+ return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
+ }
+
+ private:
+ AudioPlaybackRate mPlaybackRateParameters;
+ AudioDualMonoMode mDualMonoMode;
+ float mAudioDescriptionMixLeveldB;
+ std::vector<float> mHwVolume;
+ std::shared_ptr<IStreamCommon> mStreamCommon;
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/TelephonyMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/TelephonyMock.h
new file mode 100644
index 0000000..d56dee6
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/core-mock/TelephonyMock.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/BnTelephony.h>
+
+using namespace aidl::android::hardware::audio::core;
+using namespace aidl::android::media::audio::common;
+
+namespace aidl::android::hardware::audio::core {
+
+class TelephonyMock : public BnTelephony {
+ public:
+ ndk::ScopedAStatus getSupportedAudioModes(std::vector<AudioMode>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus switchAudioMode(AudioMode) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus setTelecomConfig(const ITelephony::TelecomConfig&,
+ ITelephony::TelecomConfig*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+};
+
+} // namespace aidl::android::hardware::audio::core
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/effect-mock/EffectMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/effect-mock/EffectMock.h
new file mode 100644
index 0000000..db20cd8
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/effect-mock/EffectMock.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/effect/BnEffect.h>
+
+using namespace aidl::android::hardware::audio::effect;
+
+namespace aidl::android::hardware::audio::effect {
+
+class EffectMock : public BnEffect {
+ public:
+ ndk::ScopedAStatus open(const Parameter::Common&, const std::optional<Parameter::Specific>&,
+ IEffect::OpenEffectReturn*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus close() override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus command(CommandId) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus getState(State*) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus getDescriptor(Descriptor*) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus reopen(IEffect::OpenEffectReturn*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus setParameter(const Parameter&) override { return ndk::ScopedAStatus::ok(); }
+ ndk::ScopedAStatus getParameter(const Parameter::Id&, Parameter*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+};
+
+} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/effect-mock/FactoryMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/effect-mock/FactoryMock.h
new file mode 100644
index 0000000..57d58d5
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/effect-mock/FactoryMock.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/effect/BnFactory.h>
+
+using namespace aidl::android::media::audio::common;
+using namespace aidl::android::hardware::audio::effect;
+
+namespace aidl::android::hardware::audio::effect {
+
+class FactoryMock : public BnFactory {
+ ndk::ScopedAStatus queryEffects(const std::optional<AudioUuid>&,
+ const std::optional<AudioUuid>&,
+ const std::optional<AudioUuid>&,
+ std::vector<Descriptor>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus queryProcessing(const std::optional<Processing::Type>&,
+ std::vector<Processing>*) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus destroyEffect(const std::shared_ptr<IEffect>&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+
+ ndk::ScopedAStatus createEffect(const AudioUuid&, std::shared_ptr<IEffect>*) override;
+};
+
+} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/sounddose-mock/SoundDoseMock.h b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/sounddose-mock/SoundDoseMock.h
new file mode 100644
index 0000000..5557b10
--- /dev/null
+++ b/media/libaudioclient/aidl/fuzzer/libaudiomockhal/include/sounddose-mock/SoundDoseMock.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2024 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 <aidl/android/hardware/audio/core/sounddose/BnSoundDose.h>
+
+using namespace aidl::android::hardware::audio::core::sounddose;
+
+namespace aidl::android::hardware::audio::core::sounddose {
+
+class SoundDoseMock : public BnSoundDose {
+ ndk::ScopedAStatus setOutputRs2UpperBound(float in_rs2ValueDbA) override {
+ mOutputRs2UpperBound = in_rs2ValueDbA;
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus getOutputRs2UpperBound(float* _aidl_return) override {
+ *_aidl_return = mOutputRs2UpperBound;
+ return ndk::ScopedAStatus::ok();
+ }
+ ndk::ScopedAStatus registerSoundDoseCallback(
+ const std::shared_ptr<ISoundDose::IHalSoundDoseCallback>&) override {
+ return ndk::ScopedAStatus::ok();
+ }
+
+ private:
+ float mOutputRs2UpperBound;
+};
+
+} // namespace aidl::android::hardware::audio::core::sounddose
diff --git a/media/libaudioclient/include/media/EffectClientAsyncProxy.h b/media/libaudioclient/include/media/EffectClientAsyncProxy.h
new file mode 100644
index 0000000..e7d6d80
--- /dev/null
+++ b/media/libaudioclient/include/media/EffectClientAsyncProxy.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android/media/BnEffectClient.h>
+#include <audio_utils/CommandThread.h>
+
+namespace android::media {
+
+class EffectClientAsyncProxy : public IEffectClient {
+public:
+
+ /**
+ * Call this factory method to interpose a worker thread when a binder
+ * callback interface is invoked in-proc.
+ */
+ static sp<IEffectClient> makeIfNeeded(const sp<IEffectClient>& effectClient) {
+ if (isLocalBinder(effectClient)) {
+ return sp<EffectClientAsyncProxy>::make(effectClient);
+ }
+ return effectClient;
+ }
+
+ explicit EffectClientAsyncProxy(const sp<IEffectClient>& effectClient)
+ : mEffectClient(effectClient) {}
+
+ ::android::IBinder* onAsBinder() override {
+ return nullptr;
+ }
+
+ ::android::binder::Status controlStatusChanged(bool controlGranted) override {
+ getThread().add(__func__, [=, effectClient = mEffectClient]() {
+ effectClient->controlStatusChanged(controlGranted);
+ });
+ return ::android::binder::Status::fromStatusT(::android::NO_ERROR);
+ }
+
+ ::android::binder::Status enableStatusChanged(bool enabled) override {
+ getThread().add(__func__, [=, effectClient = mEffectClient]() {
+ effectClient->enableStatusChanged(enabled);
+ });
+ return ::android::binder::Status::fromStatusT(::android::NO_ERROR);
+ }
+
+ ::android::binder::Status commandExecuted(
+ int32_t cmdCode, const ::std::vector<uint8_t>& cmdData,
+ const ::std::vector<uint8_t>& replyData) override {
+ getThread().add(__func__, [=, effectClient = mEffectClient]() {
+ effectClient->commandExecuted(cmdCode, cmdData, replyData);
+ });
+ return ::android::binder::Status::fromStatusT(::android::NO_ERROR);
+ }
+
+ ::android::binder::Status framesProcessed(int32_t frames) override {
+ getThread().add(__func__, [=, effectClient = mEffectClient]() {
+ effectClient->framesProcessed(frames);
+ });
+ return ::android::binder::Status::fromStatusT(::android::NO_ERROR);
+ }
+
+ /**
+ * Returns true if the binder interface is local (in-proc).
+ *
+ * Move to a binder helper class?
+ */
+ static bool isLocalBinder(const sp<IInterface>& interface) {
+ const auto b = IInterface::asBinder(interface);
+ return b && b->localBinder();
+ }
+
+private:
+ const sp<IEffectClient> mEffectClient;
+
+ /**
+ * Returns the per-interface-descriptor CommandThread for in-proc binder transactions.
+ *
+ * Note: Remote RPC transactions to a given binder (kernel) node enter that node's
+ * async_todo list, which serializes all async operations to that binder node.
+ * Each transaction on the async_todo list must complete before the next one
+ * starts, even though there may be available threads in the process threadpool.
+ *
+ * For local transactions, we order all async requests entering
+ * the CommandThread. We do not maintain a threadpool, though a future implementation
+ * could use a shared ThreadPool.
+ *
+ * By using a static here, all in-proc binder interfaces made async with
+ * EffectClientAsyncProxy will get the same CommandThread.
+ *
+ * @return CommandThread to use.
+ */
+ static audio_utils::CommandThread& getThread() {
+ [[clang::no_destroy]] static audio_utils::CommandThread commandThread;
+ return commandThread;
+ }
+}; // class EffectClientAsyncProxy
+
+} // namespace android::media
diff --git a/media/libaudiohal/impl/DeviceHalAidl.cpp b/media/libaudiohal/impl/DeviceHalAidl.cpp
index 14765f6b..f865603 100644
--- a/media/libaudiohal/impl/DeviceHalAidl.cpp
+++ b/media/libaudiohal/impl/DeviceHalAidl.cpp
@@ -589,7 +589,6 @@
// that the HAL module uses `int32_t` for patch IDs. The following assert ensures
// that both the framework and the HAL use the same value for "no ID":
static_assert(AUDIO_PATCH_HANDLE_NONE == 0);
- int32_t aidlPatchId = static_cast<int32_t>(*patch);
// Upon conversion, mix port configs contain audio configuration, while
// device port configs contain device address. This data is used to find
@@ -611,11 +610,27 @@
::aidl::android::legacy2aidl_audio_port_config_AudioPortConfig(
sinks[i], isInput, 0)));
}
+ int32_t aidlPatchId = static_cast<int32_t>(*patch);
Hal2AidlMapper::Cleanups cleanups(mMapperAccessor);
{
std::lock_guard l(mLock);
- RETURN_STATUS_IF_ERROR(mMapper.createOrUpdatePatch(
- aidlSources, aidlSinks, &aidlPatchId, &cleanups));
+ // Check for patches that only exist for the framework, or have different HAL patch ID.
+ if (int32_t aidlHalPatchId = mMapper.findFwkPatch(aidlPatchId); aidlHalPatchId != 0) {
+ if (aidlHalPatchId == aidlPatchId) {
+ // This patch was previously released by the HAL. Thus we need to pass '0'
+ // to the HAL to obtain a new patch.
+ int32_t newAidlPatchId = 0;
+ RETURN_STATUS_IF_ERROR(mMapper.createOrUpdatePatch(
+ aidlSources, aidlSinks, &newAidlPatchId, &cleanups));
+ mMapper.updateFwkPatch(aidlPatchId, newAidlPatchId);
+ } else {
+ RETURN_STATUS_IF_ERROR(mMapper.createOrUpdatePatch(
+ aidlSources, aidlSinks, &aidlHalPatchId, &cleanups));
+ }
+ } else {
+ RETURN_STATUS_IF_ERROR(mMapper.createOrUpdatePatch(
+ aidlSources, aidlSinks, &aidlPatchId, &cleanups));
+ }
}
*patch = static_cast<audio_patch_handle_t>(aidlPatchId);
cleanups.disarmAll();
@@ -631,7 +646,19 @@
return BAD_VALUE;
}
std::lock_guard l(mLock);
- RETURN_STATUS_IF_ERROR(mMapper.releaseAudioPatch(static_cast<int32_t>(patch)));
+ // Check for patches that only exist for the framework, or have different HAL patch ID.
+ int32_t aidlPatchId = static_cast<int32_t>(patch);
+ if (int32_t aidlHalPatchId = mMapper.findFwkPatch(aidlPatchId); aidlHalPatchId != 0) {
+ if (aidlHalPatchId == aidlPatchId) {
+ // This patch was previously released by the HAL, just need to finish its removal.
+ mMapper.eraseFwkPatch(aidlPatchId);
+ return OK;
+ } else {
+ // This patch has a HAL patch ID which is different
+ aidlPatchId = aidlHalPatchId;
+ }
+ }
+ RETURN_STATUS_IF_ERROR(mMapper.releaseAudioPatch(aidlPatchId));
return OK;
}
@@ -988,7 +1015,7 @@
if (mModule == nullptr) return NO_INIT;
{
std::lock_guard l(mLock);
- mMapper.resetUnusedPatchesPortConfigsAndPorts();
+ mMapper.resetUnusedPatchesAndPortConfigs();
}
ModuleDebug debug{ .simulateDeviceConnections = enabled };
status_t status = statusTFromBinderStatus(mModule->setModuleDebug(debug));
diff --git a/media/libaudiohal/impl/DeviceHalHidl.cpp b/media/libaudiohal/impl/DeviceHalHidl.cpp
index 478e0f0..ea4258c 100644
--- a/media/libaudiohal/impl/DeviceHalHidl.cpp
+++ b/media/libaudiohal/impl/DeviceHalHidl.cpp
@@ -752,10 +752,14 @@
// the attributes reported by `getParameters` API.
struct audio_port_v7 temp = *devicePort;
AudioProfileAttributesMultimap attrsFromDevice;
- status_t status = getAudioPort(&temp);
- if (status == NO_ERROR) {
- attrsFromDevice = createAudioProfilesAttrMap(temp.audio_profiles, 0 /*first*/,
- temp.num_audio_profiles);
+ bool supportsPatches;
+ if (supportsAudioPatches(&supportsPatches) == OK && supportsPatches) {
+ // The audio patches are supported since HAL 3.0, which is the same HAL version
+ // requirement for 'getAudioPort' API.
+ if (getAudioPort(&temp) == NO_ERROR) {
+ attrsFromDevice = createAudioProfilesAttrMap(temp.audio_profiles, 0 /*first*/,
+ temp.num_audio_profiles);
+ }
}
auto streamIt = mStreams.find(mixPort->ext.mix.handle);
if (streamIt == mStreams.end()) {
@@ -767,7 +771,7 @@
}
String8 formatsStr;
- status = getParametersFromStream(
+ status_t status = getParametersFromStream(
stream, AudioParameter::keyStreamSupportedFormats, nullptr /*extraParameters*/,
&formatsStr);
if (status != NO_ERROR) {
diff --git a/media/libaudiohal/impl/EffectConversionHelperAidl.cpp b/media/libaudiohal/impl/EffectConversionHelperAidl.cpp
index e1a82f8..ff6126d 100644
--- a/media/libaudiohal/impl/EffectConversionHelperAidl.cpp
+++ b/media/libaudiohal/impl/EffectConversionHelperAidl.cpp
@@ -181,7 +181,7 @@
State state;
RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mEffect->getState(&state)));
if (state == State::INIT) {
- ALOGI("%s at state %s, opening effect with input %s output %s", __func__,
+ ALOGD("%s at state %s, opening effect with input %s output %s", __func__,
android::internal::ToString(state).c_str(), common.input.toString().c_str(),
common.output.toString().c_str());
IEffect::OpenEffectReturn openReturn;
@@ -189,10 +189,12 @@
statusTFromBinderStatus(mEffect->open(common, std::nullopt, &openReturn)));
updateMqsAndEventFlags(openReturn);
} else if (mCommon != common) {
- ALOGI("%s at state %s, setParameter", __func__, android::internal::ToString(state).c_str());
+ ALOGV("%s at state %s, setCommonParameter %s", __func__,
+ android::internal::ToString(state).c_str(), common.toString().c_str());
Parameter aidlParam = UNION_MAKE(Parameter, common, common);
RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mEffect->setParameter(aidlParam)));
}
+ mOutputAccessMode = config->outputCfg.accessMode;
mCommon = common;
return *static_cast<int32_t*>(pReplyData) = OK;
@@ -397,12 +399,12 @@
effect_offload_param_t* offload = (effect_offload_param_t*)pCmdData;
// send to proxy to update active sub-effect
if (mIsProxyEffect) {
- ALOGI("%s offload param offload %s ioHandle %d", __func__,
+ ALOGV("%s offload param offload %s ioHandle %d", __func__,
offload->isOffload ? "true" : "false", offload->ioHandle);
const auto& effectProxy = std::static_pointer_cast<EffectProxy>(mEffect);
RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(effectProxy->setOffloadParam(offload)));
if (mCommon.ioHandle != offload->ioHandle) {
- ALOGI("%s ioHandle update [%d to %d]", __func__, mCommon.ioHandle, offload->ioHandle);
+ ALOGV("%s ioHandle update [%d to %d]", __func__, mCommon.ioHandle, offload->ioHandle);
mCommon.ioHandle = offload->ioHandle;
Parameter aidlParam = UNION_MAKE(Parameter, common, mCommon);
RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mEffect->setParameter(aidlParam)));
diff --git a/media/libaudiohal/impl/EffectConversionHelperAidl.h b/media/libaudiohal/impl/EffectConversionHelperAidl.h
index 0c0184e..29c5a83 100644
--- a/media/libaudiohal/impl/EffectConversionHelperAidl.h
+++ b/media/libaudiohal/impl/EffectConversionHelperAidl.h
@@ -49,6 +49,8 @@
::aidl::android::hardware::audio::effect::Descriptor getDescriptor() const;
status_t reopen();
+ uint8_t mOutputAccessMode = EFFECT_BUFFER_ACCESS_WRITE;
+
protected:
const int32_t mSessionId;
const int32_t mIoId;
diff --git a/media/libaudiohal/impl/EffectHalAidl.cpp b/media/libaudiohal/impl/EffectHalAidl.cpp
index ebda86a..c35a60e 100644
--- a/media/libaudiohal/impl/EffectHalAidl.cpp
+++ b/media/libaudiohal/impl/EffectHalAidl.cpp
@@ -20,6 +20,7 @@
#include <memory>
+#include <audio_utils/primitives.h>
#include <error/expected_utils.h>
#include <media/AidlConversionCppNdk.h>
#include <media/AidlConversionEffect.h>
@@ -196,7 +197,7 @@
::android::OK == efGroup->wait(kEventFlagDataMqUpdate, &efState,
1 /* ns */, true /* retry */) &&
efState & kEventFlagDataMqUpdate) {
- ALOGI("%s %s V%d receive dataMQUpdate eventFlag from HAL", __func__, effectName.c_str(),
+ ALOGV("%s %s V%d receive dataMQUpdate eventFlag from HAL", __func__, effectName.c_str(),
halVersion);
mConversion->reopen();
}
@@ -239,16 +240,23 @@
mOutBuffer->getSize() / sizeof(float), available);
return INVALID_OPERATION;
}
+
+ float *outputRawBuffer = mOutBuffer->audioBuffer()->f32;
+ std::vector<float> tempBuffer;
+ if (mConversion->mOutputAccessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
+ tempBuffer.resize(floatsToRead);
+ outputRawBuffer = tempBuffer.data();
+ }
// always read floating point data for AIDL
- if (!mOutBuffer->audioBuffer() ||
- !outputQ->read(mOutBuffer->audioBuffer()->f32, floatsToRead)) {
+ if (!outputQ->read(outputRawBuffer, floatsToRead)) {
ALOGE("%s failed to read %zu from outputQ to audioBuffer %p", __func__, floatsToRead,
mOutBuffer->audioBuffer());
return INVALID_OPERATION;
}
+ if (mConversion->mOutputAccessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
+ accumulate_float(mOutBuffer->audioBuffer()->f32, outputRawBuffer, floatsToRead);
+ }
- ALOGD("%s %s consumed %zu produced %zu", __func__, effectName.c_str(), floatsToWrite,
- floatsToRead);
return OK;
}
diff --git a/media/libaudiohal/impl/EffectProxy.cpp b/media/libaudiohal/impl/EffectProxy.cpp
index 3d9832c..9aa02e2 100644
--- a/media/libaudiohal/impl/EffectProxy.cpp
+++ b/media/libaudiohal/impl/EffectProxy.cpp
@@ -147,7 +147,7 @@
// close all opened effects if failure
if (!status.isOk()) {
- ALOGE("%s: closing all sub-effects with error %s", __func__,
+ ALOGW("%s: closing all sub-effects with error %s", __func__,
status.getDescription().c_str());
close();
}
@@ -259,7 +259,7 @@
std::function<ndk::ScopedAStatus(const std::shared_ptr<IEffect>&)> const& func) {
ndk::ScopedAStatus status = runWithActiveSubEffect(func);
if (!status.isOk()) {
- ALOGE("%s active sub-effect return error %s", __func__, status.getDescription().c_str());
+ ALOGW("%s active sub-effect return error %s", __func__, status.getDescription().c_str());
}
// proceed with others
@@ -268,7 +268,7 @@
continue;
}
if (!mSubEffects[i].handle) {
- ALOGE("%s null sub-effect interface for %s", __func__,
+ ALOGW("%s null sub-effect interface for %s", __func__,
mSubEffects[i].descriptor.common.id.uuid.toString().c_str());
continue;
}
diff --git a/media/libaudiohal/impl/EffectsFactoryHalAidl.cpp b/media/libaudiohal/impl/EffectsFactoryHalAidl.cpp
index 7d807b2..424fdb7 100644
--- a/media/libaudiohal/impl/EffectsFactoryHalAidl.cpp
+++ b/media/libaudiohal/impl/EffectsFactoryHalAidl.cpp
@@ -120,8 +120,6 @@
}
*pNumEffects = mEffectCount;
- ALOGD("%s %u non %zu proxyMap %zu proxyDesc %zu", __func__, *pNumEffects,
- mNonProxyDescList.size(), mProxyUuidDescriptorMap.size(), mProxyDescList.size());
return OK;
}
@@ -178,7 +176,7 @@
if (sessionId == AUDIO_SESSION_DEVICE && ioId == AUDIO_IO_HANDLE_NONE) {
return INVALID_OPERATION;
}
- ALOGI("%s session %d ioId %d", __func__, sessionId, ioId);
+ ALOGV("%s session %d ioId %d", __func__, sessionId, ioId);
AudioUuid aidlUuid =
VALUE_OR_RETURN_STATUS(::aidl::android::legacy2aidl_audio_uuid_t_AudioUuid(*uuid));
@@ -218,13 +216,11 @@
}
status_t EffectsFactoryHalAidl::allocateBuffer(size_t size, sp<EffectBufferHalInterface>* buffer) {
- ALOGI("%s size %zu buffer %p", __func__, size, buffer);
return EffectBufferHalAidl::allocate(size, buffer);
}
status_t EffectsFactoryHalAidl::mirrorBuffer(void* external, size_t size,
sp<EffectBufferHalInterface>* buffer) {
- ALOGI("%s extern %p size %zu buffer %p", __func__, external, size, buffer);
return EffectBufferHalAidl::mirror(external, size, buffer);
}
@@ -245,7 +241,6 @@
ALOGE("%s UUID not found in HAL and proxy list %s", __func__, toString(uuid).c_str());
return NAME_NOT_FOUND;
}
- ALOGI("%s UUID impl found %s", __func__, toString(uuid).c_str());
*pDescriptor = VALUE_OR_RETURN_STATUS(
::aidl::android::aidl2legacy_Descriptor_effect_descriptor(*matchIt));
@@ -267,7 +262,6 @@
ALOGW("%s UUID type not found in HAL and proxy list %s", __func__, toString(type).c_str());
return BAD_VALUE;
}
- ALOGI("%s UUID type found %zu \n %s", __func__, result.size(), toString(type).c_str());
*descriptors = VALUE_OR_RETURN_STATUS(
aidl::android::convertContainer<std::vector<effect_descriptor_t>>(
diff --git a/media/libaudiohal/impl/Hal2AidlMapper.cpp b/media/libaudiohal/impl/Hal2AidlMapper.cpp
index 2b7f298..acc69ec 100644
--- a/media/libaudiohal/impl/Hal2AidlMapper.cpp
+++ b/media/libaudiohal/impl/Hal2AidlMapper.cpp
@@ -102,8 +102,8 @@
}
void Hal2AidlMapper::addStream(
- const sp<StreamHalInterface>& stream, int32_t portConfigId, int32_t patchId) {
- mStreams.insert(std::pair(stream, std::pair(portConfigId, patchId)));
+ const sp<StreamHalInterface>& stream, int32_t mixPortConfigId, int32_t patchId) {
+ mStreams.insert(std::pair(stream, std::pair(mixPortConfigId, patchId)));
}
bool Hal2AidlMapper::audioDeviceMatches(const AudioDevice& device, const AudioPort& p) {
@@ -698,20 +698,23 @@
return OK;
}
-bool Hal2AidlMapper::isPortBeingHeld(int32_t portId) {
- // It is assumed that mStreams has already been cleaned up.
- for (const auto& s : mStreams) {
- if (portConfigBelongsToPort(s.second.first, portId)) return true;
- }
- for (const auto& [_, patch] : mPatches) {
+std::set<int32_t> Hal2AidlMapper::getPatchIdsByPortId(int32_t portId) {
+ std::set<int32_t> result;
+ for (const auto& [patchId, patch] : mPatches) {
for (int32_t id : patch.sourcePortConfigIds) {
- if (portConfigBelongsToPort(id, portId)) return true;
+ if (portConfigBelongsToPort(id, portId)) {
+ result.insert(patchId);
+ break;
+ }
}
for (int32_t id : patch.sinkPortConfigIds) {
- if (portConfigBelongsToPort(id, portId)) return true;
+ if (portConfigBelongsToPort(id, portId)) {
+ result.insert(patchId);
+ break;
+ }
}
}
- return false;
+ return result;
}
status_t Hal2AidlMapper::prepareToDisconnectExternalDevice(const AudioPort& devicePort) {
@@ -730,7 +733,7 @@
this, __func__, ioHandle, device.toString().c_str(),
flags.toString().c_str(), toString(source).c_str(),
config->toString().c_str(), mixPortConfig->toString().c_str());
- resetUnusedPatchesPortConfigsAndPorts();
+ resetUnusedPatchesAndPortConfigs();
const AudioConfig initialConfig = *config;
// Find / create AudioPortConfigs for the device port and the mix port,
// then find / create a patch between them, and open a stream on the mix port.
@@ -843,39 +846,52 @@
return releaseAudioPatches({patchId});
}
+// Note: does not reset port configs.
+status_t Hal2AidlMapper::releaseAudioPatch(Patches::iterator it) {
+ const int32_t patchId = it->first;
+ if (ndk::ScopedAStatus status = mModule->resetAudioPatch(patchId); !status.isOk()) {
+ ALOGE("%s: error while resetting patch %d: %s",
+ __func__, patchId, status.getDescription().c_str());
+ return statusTFromBinderStatus(status);
+ }
+ mPatches.erase(it);
+ for (auto it = mFwkPatches.begin(); it != mFwkPatches.end(); ++it) {
+ if (it->second == patchId) {
+ mFwkPatches.erase(it);
+ break;
+ }
+ }
+ return OK;
+}
+
status_t Hal2AidlMapper::releaseAudioPatches(const std::set<int32_t>& patchIds) {
status_t result = OK;
for (const auto patchId : patchIds) {
if (auto it = mPatches.find(patchId); it != mPatches.end()) {
- mPatches.erase(it);
- if (ndk::ScopedAStatus status = mModule->resetAudioPatch(patchId); !status.isOk()) {
- ALOGE("%s: error while resetting patch %d: %s",
- __func__, patchId, status.getDescription().c_str());
- result = statusTFromBinderStatus(status);
- }
+ releaseAudioPatch(it);
} else {
ALOGE("%s: patch id %d not found", __func__, patchId);
result = BAD_VALUE;
}
}
- resetUnusedPortConfigsAndPorts();
+ resetUnusedPortConfigs();
return result;
}
void Hal2AidlMapper::resetPortConfig(int32_t portConfigId) {
if (auto it = mPortConfigs.find(portConfigId); it != mPortConfigs.end()) {
- mPortConfigs.erase(it);
if (ndk::ScopedAStatus status = mModule->resetAudioPortConfig(portConfigId);
!status.isOk()) {
ALOGE("%s: error while resetting port config %d: %s",
__func__, portConfigId, status.getDescription().c_str());
}
+ mPortConfigs.erase(it);
return;
}
ALOGE("%s: port config id %d not found", __func__, portConfigId);
}
-void Hal2AidlMapper::resetUnusedPatchesPortConfigsAndPorts() {
+void Hal2AidlMapper::resetUnusedPatchesAndPortConfigs() {
// Since patches can be created independently of streams via 'createOrUpdatePatch',
// here we only clean up patches for released streams.
std::set<int32_t> patchesToRelease;
@@ -889,52 +905,35 @@
it = mStreams.erase(it);
}
}
- // 'releaseAudioPatches' also resets unused port configs and ports.
+ // 'releaseAudioPatches' also resets unused port configs.
releaseAudioPatches(patchesToRelease);
}
-void Hal2AidlMapper::resetUnusedPortConfigsAndPorts() {
+void Hal2AidlMapper::resetUnusedPortConfigs() {
// The assumption is that port configs are used to create patches
// (or to open streams, but that involves creation of patches, too). Thus,
// orphaned port configs can and should be reset.
- std::map<int32_t, int32_t /*portID*/> portConfigIds;
+ std::set<int32_t> portConfigIdsToReset;
std::transform(mPortConfigs.begin(), mPortConfigs.end(),
- std::inserter(portConfigIds, portConfigIds.end()),
- [](const auto& pcPair) { return std::make_pair(pcPair.first, pcPair.second.portId); });
+ std::inserter(portConfigIdsToReset, portConfigIdsToReset.end()),
+ [](const auto& pcPair) { return pcPair.first; });
for (const auto& p : mPatches) {
- for (int32_t id : p.second.sourcePortConfigIds) portConfigIds.erase(id);
- for (int32_t id : p.second.sinkPortConfigIds) portConfigIds.erase(id);
+ for (int32_t id : p.second.sourcePortConfigIds) portConfigIdsToReset.erase(id);
+ for (int32_t id : p.second.sinkPortConfigIds) portConfigIdsToReset.erase(id);
}
for (int32_t id : mInitialPortConfigIds) {
- portConfigIds.erase(id);
+ portConfigIdsToReset.erase(id);
}
for (const auto& s : mStreams) {
- portConfigIds.erase(s.second.first);
+ portConfigIdsToReset.erase(s.second.first);
}
- std::set<int32_t> retryDeviceDisconnection;
- for (const auto& portConfigAndIdPair : portConfigIds) {
- resetPortConfig(portConfigAndIdPair.first);
- if (const auto it = mConnectedPorts.find(portConfigAndIdPair.second);
- it != mConnectedPorts.end() && it->second) {
- retryDeviceDisconnection.insert(portConfigAndIdPair.second);
- }
- }
- for (int32_t portId : retryDeviceDisconnection) {
- if (!isPortBeingHeld(portId)) {
- if (auto status = mModule->disconnectExternalDevice(portId); status.isOk()) {
- eraseConnectedPort(portId);
- ALOGD("%s: executed postponed external device disconnection for port ID %d",
- __func__, portId);
- }
- }
- }
- if (!retryDeviceDisconnection.empty()) {
- updateRoutes();
+ for (const auto& portConfigId : portConfigIdsToReset) {
+ resetPortConfig(portConfigId);
}
}
status_t Hal2AidlMapper::setDevicePortConnectedState(const AudioPort& devicePort, bool connected) {
- resetUnusedPatchesPortConfigsAndPorts();
+ resetUnusedPatchesAndPortConfigs();
if (connected) {
AudioDevice matchDevice = devicePort.ext.get<AudioPortExt::device>().device;
std::optional<AudioPort> templatePort;
@@ -980,7 +979,7 @@
"%s: module %s, duplicate port ID received from HAL: %s, existing port: %s",
__func__, mInstance.c_str(), connectedPort.toString().c_str(),
it->second.toString().c_str());
- mConnectedPorts[connectedPort.id] = false;
+ mConnectedPorts.insert(connectedPort.id);
if (erasePortAfterConnectionIt != mPorts.end()) {
mPorts.erase(erasePortAfterConnectionIt);
}
@@ -1007,17 +1006,27 @@
port.ext.get<AudioPortExt::Tag::device>().device = matchDevice;
port.profiles = portsIt->second.profiles;
}
- // Streams are closed by AudioFlinger independently from device disconnections.
- // It is possible that the stream has not been closed yet.
- if (!isPortBeingHeld(portId)) {
- RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
- mModule->disconnectExternalDevice(portId)));
- eraseConnectedPort(portId);
- } else {
- ALOGD("%s: since device port ID %d is used by a stream, "
- "external device disconnection postponed", __func__, portId);
- mConnectedPorts[portId] = true;
+
+ // Patches may still exist, the framework may reset or update them later.
+ // For disconnection to succeed, need to release these patches first.
+ if (std::set<int32_t> patchIdsToRelease = getPatchIdsByPortId(portId);
+ !patchIdsToRelease.empty()) {
+ FwkPatches releasedPatches;
+ status_t status = OK;
+ for (int32_t patchId : patchIdsToRelease) {
+ if (auto it = mPatches.find(patchId); it != mPatches.end()) {
+ if (status = releaseAudioPatch(it); status != OK) break;
+ releasedPatches.insert(std::make_pair(patchId, patchId));
+ }
+ }
+ resetUnusedPortConfigs();
+ mFwkPatches.merge(releasedPatches);
+ LOG_ALWAYS_FATAL_IF(!releasedPatches.empty(),
+ "mFwkPatches already contains some of released patches");
+ if (status != OK) return status;
}
+ RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->disconnectExternalDevice(portId)));
+ eraseConnectedPort(portId);
}
return updateRoutes();
}
diff --git a/media/libaudiohal/impl/Hal2AidlMapper.h b/media/libaudiohal/impl/Hal2AidlMapper.h
index f937173..f302c23 100644
--- a/media/libaudiohal/impl/Hal2AidlMapper.h
+++ b/media/libaudiohal/impl/Hal2AidlMapper.h
@@ -49,7 +49,7 @@
const std::string& instance,
const std::shared_ptr<::aidl::android::hardware::audio::core::IModule>& module);
- void addStream(const sp<StreamHalInterface>& stream, int32_t portConfigId, int32_t patchId);
+ void addStream(const sp<StreamHalInterface>& stream, int32_t mixPortConfigId, int32_t patchId);
status_t createOrUpdatePatch(
const std::vector<::aidl::android::media::audio::common::AudioPortConfig>& sources,
const std::vector<::aidl::android::media::audio::common::AudioPortConfig>& sinks,
@@ -91,13 +91,32 @@
::aidl::android::media::audio::common::AudioPortConfig* portConfig,
Cleanups* cleanups = nullptr);
status_t releaseAudioPatch(int32_t patchId);
- void resetUnusedPatchesPortConfigsAndPorts();
+ void resetUnusedPatchesAndPortConfigs();
status_t setDevicePortConnectedState(
const ::aidl::android::media::audio::common::AudioPort& devicePort, bool connected);
+ // Methods to work with FwkPatches.
+ void eraseFwkPatch(int32_t fwkPatchId) { mFwkPatches.erase(fwkPatchId); }
+ int32_t findFwkPatch(int32_t fwkPatchId) {
+ const auto it = mFwkPatches.find(fwkPatchId);
+ return it != mFwkPatches.end() ? it->second : 0;
+ }
+ void updateFwkPatch(int32_t fwkPatchId, int32_t halPatchId) {
+ mFwkPatches[fwkPatchId] = halPatchId;
+ }
+
private:
- // IDs of ports for connected external devices, and whether they are held by streams.
- using ConnectedPorts = std::map<int32_t /*port ID*/, bool>;
+ // 'FwkPatches' is used to store patches that diverge from the framework's state.
+ // Uses framework patch ID (aka audio_patch_handle_t) values for indexing.
+ // When the 'key == value', that means Hal2AidlMapper has removed this patch, and it is absent
+ // from 'mPatches', but it still "exists" for the framework. It will either remove it or
+ // re-patch. If the framework re-patches, it will continue to use the same patch handle,
+ // but the HAL will use the new one (since the old patch was reset), thus 'key != value'
+ // for such patches. Since they "exist" both for the framework and the HAL, 'mPatches'
+ // contains their data under HAL patch ID ('value' of 'FwkPatches').
+ // To avoid confusion, all patchIDs used by Hal2AidlMapper are HAL IDs. Mapping between
+ // framework patch IDs and HAL patch IDs is done by DeviceHalAidl.
+ using FwkPatches = std::map<int32_t /*audio_patch_handle_t*/, int32_t /*patch ID*/>;
using Patches = std::map<int32_t /*patch ID*/,
::aidl::android::hardware::audio::core::AudioPatch>;
using PortConfigs = std::map<int32_t /*port config ID*/,
@@ -107,12 +126,12 @@
// Answers the question "whether portID 'first' is reachable from portID 'second'?"
// It's not a map because both portIDs are known. The matrix is symmetric.
using RoutingMatrix = std::set<std::pair<int32_t, int32_t>>;
- // There is always a port config ID set. The patch ID is set after stream
+ // There is always a mix port config ID set. The patch ID is set after stream
// creation, and can be set to '-1' later if the framework happens to create
// a patch between the same endpoints. In that case, the ownership of the patch
// is on the framework.
using Streams = std::map<wp<StreamHalInterface>,
- std::pair<int32_t /*port config ID*/, int32_t /*patch ID*/>>;
+ std::pair<int32_t /*mix port config ID*/, int32_t /*patch ID*/>>;
const std::string mInstance;
const std::shared_ptr<::aidl::android::hardware::audio::core::IModule> mModule;
@@ -168,7 +187,7 @@
const std::optional<::aidl::android::media::audio::common::AudioConfig>& config,
const std::optional<::aidl::android::media::audio::common::AudioIoFlags>& flags,
int32_t ioHandle);
- bool isPortBeingHeld(int32_t portId);
+ std::set<int32_t> getPatchIdsByPortId(int32_t portId);
status_t prepareToOpenStreamHelper(
int32_t ioHandle, int32_t devicePortId, int32_t devicePortConfigId,
const ::aidl::android::media::audio::common::AudioIoFlags& flags,
@@ -181,10 +200,11 @@
auto it = mPortConfigs.find(portConfigId);
return it != mPortConfigs.end() && it->second.portId == portId;
}
+ status_t releaseAudioPatch(Patches::iterator it);
status_t releaseAudioPatches(const std::set<int32_t>& patchIds);
void resetPatch(int32_t patchId) { (void)releaseAudioPatch(patchId); }
void resetPortConfig(int32_t portConfigId);
- void resetUnusedPortConfigsAndPorts();
+ void resetUnusedPortConfigs();
status_t updateAudioPort(
int32_t portId, ::aidl::android::media::audio::common::AudioPort* port);
status_t updateRoutes();
@@ -197,13 +217,14 @@
std::optional<::aidl::android::media::audio::common::AudioPort> mRemoteSubmixOut;
int32_t mDefaultInputPortId = -1;
int32_t mDefaultOutputPortId = -1;
+ FwkPatches mFwkPatches;
PortConfigs mPortConfigs;
std::set<int32_t> mInitialPortConfigIds;
Patches mPatches;
Routes mRoutes;
RoutingMatrix mRoutingMatrix;
Streams mStreams;
- ConnectedPorts mConnectedPorts;
+ std::set<int32_t> mConnectedPorts;
std::pair<int32_t, ::aidl::android::media::audio::common::AudioPort>
mDisconnectedPortReplacement;
std::set<int32_t> mDynamicMixPortIds;
diff --git a/media/libaudiohal/impl/effectsAidlConversion/AidlConversionPresetReverb.cpp b/media/libaudiohal/impl/effectsAidlConversion/AidlConversionPresetReverb.cpp
index 3cac591..642c370 100644
--- a/media/libaudiohal/impl/effectsAidlConversion/AidlConversionPresetReverb.cpp
+++ b/media/libaudiohal/impl/effectsAidlConversion/AidlConversionPresetReverb.cpp
@@ -71,7 +71,6 @@
status_t AidlConversionPresetReverb::getParameter(EffectParamWriter& param) {
uint32_t type = 0;
uint16_t value = 0;
- ALOGE("%s enter %s", __func__, param.toString().c_str());
if (!param.validateParamValueSize(sizeof(uint32_t), sizeof(uint16_t)) ||
OK != param.readFromParameter(&type)) {
ALOGE("%s invalid param %s", __func__, param.toString().c_str());
diff --git a/media/libaudiohal/impl/effectsAidlConversion/AidlConversionSpatializer.cpp b/media/libaudiohal/impl/effectsAidlConversion/AidlConversionSpatializer.cpp
index d1794f0..da28204 100644
--- a/media/libaudiohal/impl/effectsAidlConversion/AidlConversionSpatializer.cpp
+++ b/media/libaudiohal/impl/effectsAidlConversion/AidlConversionSpatializer.cpp
@@ -142,10 +142,8 @@
toString(mode).c_str());
return status;
}
- ALOGI("%s %d: %s", __func__, __LINE__, aidlParam.toString().c_str());
aidlParam = MAKE_SPECIFIC_PARAMETER(Spatializer, spatializer, headTrackingSensorId,
sensorId);
- ALOGI("%s %d: %s", __func__, __LINE__, aidlParam.toString().c_str());
return statusTFromBinderStatus(mEffect->setParameter(aidlParam));
}
default: {
@@ -158,7 +156,6 @@
::aidl::android::legacy2aidl_EffectParameterReader_Parameter(param));
}
- ALOGI("%s %d: %s", __func__, __LINE__, aidlParam.toString().c_str());
return statusTFromBinderStatus(mEffect->setParameter(aidlParam));
}
@@ -183,7 +180,7 @@
Spatializer::make<Spatializer::spatializationLevel>(level);
if (spatializer >= range->min && spatializer <= range->max) {
if (status_t status = param.writeToValue(&level); status != OK) {
- ALOGI("%s %d: write level %s to value failed %d", __func__, __LINE__,
+ ALOGW("%s %d: write level %s to value failed %d", __func__, __LINE__,
toString(level).c_str(), status);
return status;
}
@@ -200,7 +197,6 @@
const auto level = VALUE_OR_RETURN_STATUS(GET_PARAMETER_SPECIFIC_FIELD(
aidlParam, Spatializer, spatializer, Spatializer::spatializationLevel,
Spatialization::Level));
- ALOGI("%s %d: %s", __func__, __LINE__, aidlParam.toString().c_str());
return param.writeToValue(&level);
}
case SPATIALIZER_PARAM_HEADTRACKING_SUPPORTED: {
@@ -227,7 +223,6 @@
const auto mode = VALUE_OR_RETURN_STATUS(GET_PARAMETER_SPECIFIC_FIELD(
aidlParam, Spatializer, spatializer, Spatializer::headTrackingMode,
HeadTracking::Mode));
- ALOGI("%s %d: %s", __func__, __LINE__, aidlParam.toString().c_str());
return param.writeToValue(&mode);
}
case SPATIALIZER_PARAM_SUPPORTED_CHANNEL_MASKS: {
@@ -244,12 +239,11 @@
::aidl::android::aidl2legacy_AudioChannelLayout_audio_channel_mask_t(
layout, false /* isInput */));
if (status_t status = param.writeToValue(&mask); status != OK) {
- ALOGI("%s %d: write mask %s to value failed %d", __func__, __LINE__,
+ ALOGW("%s %d: write mask %s to value failed %d", __func__, __LINE__,
layout.toString().c_str(), status);
return status;
}
}
- ALOGI("%s %d: %s", __func__, __LINE__, aidlParam.toString().c_str());
return OK;
}
case SPATIALIZER_PARAM_SUPPORTED_SPATIALIZATION_MODES: {
@@ -263,7 +257,7 @@
Spatializer::make<Spatializer::spatializationMode>(mode);
spatializer >= range->min && spatializer <= range->max) {
if (status_t status = param.writeToValue(&mode); status != OK) {
- ALOGI("%s %d: write mode %s to value failed %d", __func__, __LINE__,
+ ALOGW("%s %d: write mode %s to value failed %d", __func__, __LINE__,
toString(mode).c_str(), status);
return status;
}
@@ -284,8 +278,8 @@
continue;
}
if (status_t status = param.writeToValue(&mode); status != OK) {
- ALOGI("%s %d: write mode %s to value failed %d", __func__, __LINE__,
- toString(mode).c_str(), status);
+ ALOGW("%s %d: write mode %s to value failed %d", __func__, __LINE__,
+ toString(mode).c_str(), status);
return status;
}
}
@@ -311,16 +305,15 @@
Spatializer::headTrackingSensorId, int32_t));
uint32_t modeInt32 = static_cast<int32_t>(mode);
if (status = param.writeToValue(&modeInt32); status != OK) {
- ALOGI("%s %d: write mode %s to value failed %d", __func__, __LINE__,
+ ALOGW("%s %d: write mode %s to value failed %d", __func__, __LINE__,
toString(mode).c_str(), status);
return status;
}
if (status = param.writeToValue(&sensorId); status != OK) {
- ALOGI("%s %d: write sensorId %d to value failed %d", __func__, __LINE__,
+ ALOGW("%s %d: write sensorId %d to value failed %d", __func__, __LINE__,
sensorId, status);
return status;
}
- ALOGI("%s %d: %s", __func__, __LINE__, aidlParam.toString().c_str());
return OK;
}
default: {
@@ -343,8 +336,6 @@
idTag.extension.setParcelable(defaultExt);
Parameter::Id id = UNION_MAKE(Parameter::Id, vendorEffectTag, idTag);
RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mEffect->getParameter(id, &aidlParam)));
- ALOGI("%s %d: %s", __func__, __LINE__,
- aidlParam.get<Parameter::specific>().toString().c_str());
// copy the AIDL extension data back to effect_param_t
return VALUE_OR_RETURN_STATUS(
::aidl::android::aidl2legacy_Parameter_EffectParameterWriter(aidlParam, param));
diff --git a/media/libaudiohal/impl/effectsAidlConversion/AidlConversionVirtualizer.cpp b/media/libaudiohal/impl/effectsAidlConversion/AidlConversionVirtualizer.cpp
index cad0068..db5cb9a 100644
--- a/media/libaudiohal/impl/effectsAidlConversion/AidlConversionVirtualizer.cpp
+++ b/media/libaudiohal/impl/effectsAidlConversion/AidlConversionVirtualizer.cpp
@@ -133,7 +133,6 @@
const audio_channel_mask_t chMask = ::aidl::android::
aidl2legacy_AudioChannelLayout_layout_audio_channel_mask_t_bits(
angle.channel, false);
- ALOGW("%s aidl %d ch %d", __func__, angle.channel, chMask);
if (OK != param.writeToValue(&chMask) ||
OK != param.writeToValue(&angle.azimuthDegree) ||
OK != param.writeToValue(&angle.elevationDegree)) {
diff --git a/media/libeffects/downmix/aidl/DownmixContext.cpp b/media/libeffects/downmix/aidl/DownmixContext.cpp
index 5fb44b5..593e16f 100644
--- a/media/libeffects/downmix/aidl/DownmixContext.cpp
+++ b/media/libeffects/downmix/aidl/DownmixContext.cpp
@@ -76,18 +76,15 @@
DownmixContext::DownmixContext(int statusDepth, const Parameter::Common& common)
: EffectContext(statusDepth, common) {
- LOG(DEBUG) << __func__;
mState = DOWNMIX_STATE_UNINITIALIZED;
init_params(common);
}
DownmixContext::~DownmixContext() {
- LOG(DEBUG) << __func__;
mState = DOWNMIX_STATE_UNINITIALIZED;
}
RetCode DownmixContext::enable() {
- LOG(DEBUG) << __func__;
if (mState != DOWNMIX_STATE_INITIALIZED) {
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
@@ -96,7 +93,6 @@
}
RetCode DownmixContext::disable() {
- LOG(DEBUG) << __func__;
if (mState != DOWNMIX_STATE_ACTIVE) {
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
@@ -105,7 +101,6 @@
}
void DownmixContext::reset() {
- LOG(DEBUG) << __func__;
disable();
resetBuffer();
}
@@ -127,7 +122,6 @@
return status;
}
- LOG(DEBUG) << __func__ << " start processing";
bool accumulate = false;
int frames = samples * sizeof(float) / getInputFrameSize();
if (mType == Downmix::Type::STRIP) {
@@ -152,9 +146,6 @@
}
}
int producedSamples = (samples / mInputChannelCount) << 1;
- LOG(DEBUG) << __func__ << " done processing " << samples << " samples, generated "
- << producedSamples << " frameSize: " << getInputFrameSize() << " - "
- << getOutputFrameSize();
return {STATUS_OK, samples, producedSamples};
}
diff --git a/media/libeffects/downmix/aidl/EffectDownmix.cpp b/media/libeffects/downmix/aidl/EffectDownmix.cpp
index 46156ce..de60ca4 100644
--- a/media/libeffects/downmix/aidl/EffectDownmix.cpp
+++ b/media/libeffects/downmix/aidl/EffectDownmix.cpp
@@ -14,10 +14,12 @@
* limitations under the License.
*/
+#define ATRACE_TAG ATRACE_TAG_AUDIO
#define LOG_TAG "AHAL_DownmixImpl"
#include <android-base/logging.h>
#include <system/audio_effects/effect_uuid.h>
+#include <utils/Trace.h>
#include "EffectDownmix.h"
@@ -36,7 +38,6 @@
}
if (instanceSpp) {
*instanceSpp = ndk::SharedRefBase::make<DownmixImpl>();
- LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
LOG(ERROR) << __func__ << " invalid input parameter!";
@@ -66,7 +67,6 @@
ndk::ScopedAStatus DownmixImpl::getDescriptor(Descriptor* _aidl_return) {
RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr");
- LOG(DEBUG) << __func__ << kDescriptor.toString();
*_aidl_return = kDescriptor;
return ndk::ScopedAStatus::ok();
}
@@ -171,6 +171,7 @@
}
void DownmixImpl::process() {
+ ATRACE_NAME("Downmix::process");
/**
* wait for the EventFlag without lock, it's ok because the mEfGroup pointer will not change
* in the life cycle of workerThread (threadLoop).
@@ -203,8 +204,6 @@
IEffect::Status status = effectProcessImpl(buffer, buffer, processSamples);
outputMQ->write(buffer, status.fmqProduced);
statusMQ->writeBlocking(&status, 1);
- LOG(VERBOSE) << getEffectName() << __func__ << ": done processing, effect consumed "
- << status.fmqConsumed << " produced " << status.fmqProduced;
}
}
}
diff --git a/media/libeffects/downmix/aidl/EffectDownmix.h b/media/libeffects/downmix/aidl/EffectDownmix.h
index 54557dc..b7d621a 100644
--- a/media/libeffects/downmix/aidl/EffectDownmix.h
+++ b/media/libeffects/downmix/aidl/EffectDownmix.h
@@ -28,11 +28,8 @@
public:
static const std::string kEffectName;
static const Descriptor kDescriptor;
- DownmixImpl() { LOG(DEBUG) << __func__; }
- ~DownmixImpl() {
- cleanUp();
- LOG(DEBUG) << __func__;
- }
+ DownmixImpl() = default;
+ ~DownmixImpl() { cleanUp(); }
ndk::ScopedAStatus commandImpl(CommandId command) REQUIRES(mImplMutex) override;
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
diff --git a/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.cpp b/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.cpp
index 7e1549d..fdc16e3 100644
--- a/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.cpp
+++ b/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.cpp
@@ -41,7 +41,6 @@
}
if (instanceSpp) {
*instanceSpp = ndk::SharedRefBase::make<DynamicsProcessingImpl>();
- LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
LOG(ERROR) << __func__ << " invalid input parameter!";
@@ -206,7 +205,6 @@
ndk::ScopedAStatus DynamicsProcessingImpl::open(const Parameter::Common& common,
const std::optional<Parameter::Specific>& specific,
OpenEffectReturn* ret) {
- LOG(DEBUG) << __func__;
// effect only support 32bits float
RETURN_IF(common.input.base.format.pcm != common.output.base.format.pcm ||
common.input.base.format.pcm != PcmType::FLOAT_32_BIT,
@@ -240,7 +238,6 @@
ndk::ScopedAStatus DynamicsProcessingImpl::getDescriptor(Descriptor* _aidl_return) {
RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr");
- LOG(DEBUG) << __func__ << kDescriptor.toString();
*_aidl_return = kDescriptor;
return ndk::ScopedAStatus::ok();
}
diff --git a/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.h b/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.h
index 4897888..e850ba4 100644
--- a/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.h
+++ b/media/libeffects/dynamicsproc/aidl/DynamicsProcessing.h
@@ -30,11 +30,8 @@
static const Descriptor kDescriptor;
static const Capability kCapability;
- DynamicsProcessingImpl() { LOG(DEBUG) << __func__; }
- ~DynamicsProcessingImpl() {
- cleanUp();
- LOG(DEBUG) << __func__;
- }
+ DynamicsProcessingImpl() = default;
+ ~DynamicsProcessingImpl() { cleanUp(); }
ndk::ScopedAStatus open(const Parameter::Common& common,
const std::optional<Parameter::Specific>& specific,
diff --git a/media/libeffects/dynamicsproc/aidl/DynamicsProcessingContext.cpp b/media/libeffects/dynamicsproc/aidl/DynamicsProcessingContext.cpp
index 311d60a..9c440df 100644
--- a/media/libeffects/dynamicsproc/aidl/DynamicsProcessingContext.cpp
+++ b/media/libeffects/dynamicsproc/aidl/DynamicsProcessingContext.cpp
@@ -29,16 +29,10 @@
DynamicsProcessingContext::DynamicsProcessingContext(int statusDepth,
const Parameter::Common& common)
: EffectContext(statusDepth, common) {
- LOG(DEBUG) << __func__;
init();
}
-DynamicsProcessingContext::~DynamicsProcessingContext() {
- LOG(DEBUG) << __func__;
-}
-
RetCode DynamicsProcessingContext::enable() {
- std::lock_guard lg(mMutex);
if (mState != DYNAMICS_PROCESSING_STATE_INITIALIZED) {
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
@@ -47,7 +41,6 @@
}
RetCode DynamicsProcessingContext::disable() {
- std::lock_guard lg(mMutex);
if (mState != DYNAMICS_PROCESSING_STATE_ACTIVE) {
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
@@ -56,7 +49,6 @@
}
void DynamicsProcessingContext::reset() {
- std::lock_guard lg(mMutex);
if (mDpFreq != nullptr) {
mDpFreq.reset();
}
@@ -68,12 +60,10 @@
}
mCommon = common;
init();
- LOG(INFO) << __func__ << common.toString();
return RetCode::SUCCESS;
}
RetCode DynamicsProcessingContext::setVolumeStereo(const Parameter::VolumeStereo& volumeStereo) {
- std::lock_guard lg(mMutex);
dp_fx::DPChannel* leftChannel = mDpFreq->getChannel(0);
dp_fx::DPChannel* rightChannel = mDpFreq->getChannel(1);
if (leftChannel != nullptr) {
@@ -99,8 +89,8 @@
int32_t sampleRate = mCommon.input.base.sampleRate;
int32_t minBlockSize = (int32_t)dp_fx::DPFrequency::getMinBockSize();
int32_t block = engine.preferredProcessingDurationMs * sampleRate / 1000.0f;
- LOG(INFO) << __func__ << " sampleRate " << sampleRate << " block length "
- << engine.preferredProcessingDurationMs << " ms (" << block << "samples)";
+ LOG(VERBOSE) << __func__ << " sampleRate " << sampleRate << " block length "
+ << engine.preferredProcessingDurationMs << " ms (" << block << "samples)";
if (block < minBlockSize) {
block = minBlockSize;
} else if (!powerof2(block)) {
@@ -112,7 +102,6 @@
RetCode DynamicsProcessingContext::setEngineArchitecture(
const DynamicsProcessing::EngineArchitecture& engineArchitecture) {
- std::lock_guard lg(mMutex);
if (!mEngineInited || mEngineArchitecture != engineArchitecture) {
if (engineArchitecture.resolutionPreference ==
DynamicsProcessing::ResolutionPreference::FAVOR_FREQUENCY_RESOLUTION) {
@@ -124,34 +113,29 @@
mEngineInited = true;
mEngineArchitecture = engineArchitecture;
}
- LOG(INFO) << __func__ << engineArchitecture.toString();
return RetCode::SUCCESS;
}
RetCode DynamicsProcessingContext::setPreEq(
const std::vector<DynamicsProcessing::ChannelConfig>& channels) {
- std::lock_guard lg(mMutex);
return setDpChannels_l<dp_fx::DPEq>(channels, mEngineArchitecture.preEqStage.inUse,
StageType::PREEQ);
}
RetCode DynamicsProcessingContext::setPostEq(
const std::vector<DynamicsProcessing::ChannelConfig>& channels) {
- std::lock_guard lg(mMutex);
return setDpChannels_l<dp_fx::DPEq>(channels, mEngineArchitecture.postEqStage.inUse,
StageType::POSTEQ);
}
RetCode DynamicsProcessingContext::setMbc(
const std::vector<DynamicsProcessing::ChannelConfig>& channels) {
- std::lock_guard lg(mMutex);
return setDpChannels_l<dp_fx::DPMbc>(channels, mEngineArchitecture.mbcStage.inUse,
StageType::MBC);
}
RetCode DynamicsProcessingContext::setPreEqBand(
const std::vector<DynamicsProcessing::EqBandConfig>& bands) {
- std::lock_guard lg(mMutex);
RETURN_VALUE_IF(!mEngineArchitecture.preEqStage.inUse, RetCode::ERROR_ILLEGAL_PARAMETER,
"preEqNotInUse");
RETURN_VALUE_IF(
@@ -162,7 +146,6 @@
RetCode DynamicsProcessingContext::setPostEqBand(
const std::vector<DynamicsProcessing::EqBandConfig>& bands) {
- std::lock_guard lg(mMutex);
RETURN_VALUE_IF(!mEngineArchitecture.postEqStage.inUse, RetCode::ERROR_ILLEGAL_PARAMETER,
"postEqNotInUse");
RETURN_VALUE_IF(
@@ -173,7 +156,6 @@
RetCode DynamicsProcessingContext::setMbcBand(
const std::vector<DynamicsProcessing::MbcBandConfig>& bands) {
- std::lock_guard lg(mMutex);
RETURN_VALUE_IF(!mEngineArchitecture.mbcStage.inUse, RetCode::ERROR_ILLEGAL_PARAMETER,
"mbcNotInUse");
RETURN_VALUE_IF(
@@ -184,7 +166,6 @@
RetCode DynamicsProcessingContext::setLimiter(
const std::vector<DynamicsProcessing::LimiterConfig>& limiters) {
- std::lock_guard lg(mMutex);
RETURN_VALUE_IF(!mEngineArchitecture.limiterInUse, RetCode::ERROR_ILLEGAL_PARAMETER,
"limiterNotInUse");
RETURN_VALUE_IF(!validateLimiterConfig(limiters, mChannelCount),
@@ -194,15 +175,12 @@
RetCode DynamicsProcessingContext::setInputGain(
const std::vector<DynamicsProcessing::InputGain>& inputGains) {
- std::lock_guard lg(mMutex);
RETURN_VALUE_IF(!validateInputGainConfig(inputGains, mChannelCount),
RetCode::ERROR_ILLEGAL_PARAMETER, "inputGainNotValid");
return setBands_l<DynamicsProcessing::InputGain>(inputGains, StageType::INPUTGAIN);
}
DynamicsProcessing::EngineArchitecture DynamicsProcessingContext::getEngineArchitecture() {
- std::lock_guard lg(mMutex);
- LOG(INFO) << __func__ << mEngineArchitecture.toString();
return mEngineArchitecture;
}
@@ -228,8 +206,6 @@
std::vector<DynamicsProcessing::MbcBandConfig> DynamicsProcessingContext::getMbcBand() {
std::vector<DynamicsProcessing::MbcBandConfig> bands;
-
- std::lock_guard lg(mMutex);
auto maxBand = mEngineArchitecture.mbcStage.bandCount;
for (int32_t ch = 0; ch < mChannelCount; ch++) {
auto mbc = getMbc_l(ch);
@@ -261,8 +237,6 @@
std::vector<DynamicsProcessing::LimiterConfig> DynamicsProcessingContext::getLimiter() {
std::vector<DynamicsProcessing::LimiterConfig> ret;
-
- std::lock_guard lg(mMutex);
for (int32_t ch = 0; ch < mChannelCount; ch++) {
auto limiter = getLimiter_l(ch);
if (!limiter) {
@@ -282,8 +256,6 @@
std::vector<DynamicsProcessing::InputGain> DynamicsProcessingContext::getInputGain() {
std::vector<DynamicsProcessing::InputGain> ret;
-
- std::lock_guard lg(mMutex);
for (int32_t ch = 0; ch < mChannelCount; ch++) {
auto channel = getChannel_l(ch);
if (!channel) {
@@ -295,26 +267,20 @@
}
IEffect::Status DynamicsProcessingContext::dpeProcess(float* in, float* out, int samples) {
- LOG(DEBUG) << __func__ << " in " << in << " out " << out << " sample " << samples;
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!in, status, "nullInput");
RETURN_VALUE_IF(!out, status, "nullOutput");
status = {EX_ILLEGAL_STATE, 0, 0};
- LOG(DEBUG) << __func__ << " start processing";
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(mState != DynamicsProcessingState::DYNAMICS_PROCESSING_STATE_ACTIVE, status,
- "notInActiveState");
- RETURN_VALUE_IF(!mDpFreq, status, "engineNotInited");
- mDpFreq->processSamples(in, out, samples);
- }
+ RETURN_VALUE_IF(mState != DynamicsProcessingState::DYNAMICS_PROCESSING_STATE_ACTIVE, status,
+ "notInActiveState");
+ RETURN_VALUE_IF(!mDpFreq, status, "engineNotInited");
+ mDpFreq->processSamples(in, out, samples);
return {STATUS_OK, samples, samples};
}
void DynamicsProcessingContext::init() {
- std::lock_guard lg(mMutex);
if (mState == DYNAMICS_PROCESSING_STATE_UNINITIALIZED) {
mState = DYNAMICS_PROCESSING_STATE_INITIALIZED;
}
@@ -399,7 +365,6 @@
StageType type) {
std::vector<DynamicsProcessing::ChannelConfig> ret;
- std::lock_guard lg(mMutex);
for (int32_t ch = 0; ch < mChannelCount; ch++) {
auto stage = getStageWithType_l(type, ch);
if (!stage) {
@@ -414,7 +379,6 @@
StageType type) {
std::vector<DynamicsProcessing::EqBandConfig> eqBands;
- std::lock_guard lg(mMutex);
auto maxBand = mEngineArchitecture.preEqStage.bandCount;
for (int32_t ch = 0; ch < mChannelCount; ch++) {
auto eq = getEqWithType_l(type, ch);
@@ -509,7 +473,6 @@
continue;
}
if (dp->isEnabled() != it.enable) {
- LOG(INFO) << __func__ << it.toString();
dp->setEnabled(it.enable);
}
}
@@ -590,7 +553,6 @@
ret = RetCode::ERROR_ILLEGAL_PARAMETER;
continue;
}
- LOG(INFO) << __func__ << it.toString();
}
return ret;
}
diff --git a/media/libeffects/dynamicsproc/aidl/DynamicsProcessingContext.h b/media/libeffects/dynamicsproc/aidl/DynamicsProcessingContext.h
index 839c6dd..a059dd0 100644
--- a/media/libeffects/dynamicsproc/aidl/DynamicsProcessingContext.h
+++ b/media/libeffects/dynamicsproc/aidl/DynamicsProcessingContext.h
@@ -16,7 +16,6 @@
#pragma once
-#include <android-base/thread_annotations.h>
#include <audio_effects/effect_dynamicsprocessing.h>
#include "effect-impl/EffectContext.h"
@@ -37,8 +36,7 @@
class DynamicsProcessingContext final : public EffectContext {
public:
DynamicsProcessingContext(int statusDepth, const Parameter::Common& common);
- ~DynamicsProcessingContext();
-
+ ~DynamicsProcessingContext() = default;
RetCode enable();
RetCode disable();
void reset();
@@ -73,12 +71,11 @@
private:
static constexpr float kPreferredProcessingDurationMs = 10.0f;
static constexpr int kBandCount = 5;
- std::mutex mMutex;
- int mChannelCount GUARDED_BY(mMutex) = 0;
- DynamicsProcessingState mState GUARDED_BY(mMutex) = DYNAMICS_PROCESSING_STATE_UNINITIALIZED;
- std::unique_ptr<dp_fx::DPFrequency> mDpFreq GUARDED_BY(mMutex) = nullptr;
- bool mEngineInited GUARDED_BY(mMutex) = false;
- DynamicsProcessing::EngineArchitecture mEngineArchitecture GUARDED_BY(mMutex) = {
+ int mChannelCount = 0;
+ DynamicsProcessingState mState = DYNAMICS_PROCESSING_STATE_UNINITIALIZED;
+ std::unique_ptr<dp_fx::DPFrequency> mDpFreq = nullptr;
+ bool mEngineInited = false;
+ DynamicsProcessing::EngineArchitecture mEngineArchitecture = {
.resolutionPreference =
DynamicsProcessing::ResolutionPreference::FAVOR_FREQUENCY_RESOLUTION,
.preferredProcessingDurationMs = kPreferredProcessingDurationMs,
@@ -92,22 +89,21 @@
void init();
- void dpSetFreqDomainVariant_l(const DynamicsProcessing::EngineArchitecture& engine)
- REQUIRES(mMutex);
- dp_fx::DPChannel* getChannel_l(int ch) REQUIRES(mMutex);
- dp_fx::DPEq* getPreEq_l(int ch) REQUIRES(mMutex);
- dp_fx::DPEq* getPostEq_l(int ch) REQUIRES(mMutex);
- dp_fx::DPMbc* getMbc_l(int ch) REQUIRES(mMutex);
- dp_fx::DPLimiter* getLimiter_l(int ch) REQUIRES(mMutex);
- dp_fx::DPBandStage* getStageWithType_l(StageType type, int ch) REQUIRES(mMutex);
- dp_fx::DPEq* getEqWithType_l(StageType type, int ch) REQUIRES(mMutex);
+ void dpSetFreqDomainVariant_l(const DynamicsProcessing::EngineArchitecture& engine);
+ dp_fx::DPChannel* getChannel_l(int ch);
+ dp_fx::DPEq* getPreEq_l(int ch);
+ dp_fx::DPEq* getPostEq_l(int ch);
+ dp_fx::DPMbc* getMbc_l(int ch);
+ dp_fx::DPLimiter* getLimiter_l(int ch);
+ dp_fx::DPBandStage* getStageWithType_l(StageType type, int ch);
+ dp_fx::DPEq* getEqWithType_l(StageType type, int ch);
template <typename D>
RetCode setDpChannels_l(const std::vector<DynamicsProcessing::ChannelConfig>& channels,
- bool stageInUse, StageType type) REQUIRES(mMutex);
+ bool stageInUse, StageType type);
template <typename T /* BandConfig */>
- RetCode setBands_l(const std::vector<T>& bands, StageType type) REQUIRES(mMutex);
+ RetCode setBands_l(const std::vector<T>& bands, StageType type);
RetCode setDpChannelBand_l(const std::any& anyConfig, StageType type,
- std::set<std::pair<int, int>>& chBandSet) REQUIRES(mMutex);
+ std::set<std::pair<int, int>>& chBandSet);
std::vector<DynamicsProcessing::EqBandConfig> getEqBandConfigs(StageType type);
std::vector<DynamicsProcessing::ChannelConfig> getChannelConfig(StageType type);
diff --git a/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.cpp b/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.cpp
index 2d3bdd0..b803ee4 100644
--- a/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.cpp
+++ b/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.cpp
@@ -37,7 +37,6 @@
}
if (instanceSpp) {
*instanceSpp = ndk::SharedRefBase::make<HapticGeneratorImpl>();
- LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
LOG(ERROR) << __func__ << " invalid input parameter!";
@@ -67,7 +66,6 @@
ndk::ScopedAStatus HapticGeneratorImpl::getDescriptor(Descriptor* _aidl_return) {
RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr");
- LOG(DEBUG) << __func__ << kDescriptor.toString();
*_aidl_return = kDescriptor;
return ndk::ScopedAStatus::ok();
}
diff --git a/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.h b/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.h
index 53dcd49..a775f06 100644
--- a/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.h
+++ b/media/libeffects/hapticgenerator/aidl/EffectHapticGenerator.h
@@ -27,11 +27,8 @@
public:
static const std::string kEffectName;
static const Descriptor kDescriptor;
- HapticGeneratorImpl() { LOG(DEBUG) << __func__; }
- ~HapticGeneratorImpl() {
- cleanUp();
- LOG(DEBUG) << __func__;
- }
+ HapticGeneratorImpl() = default;
+ ~HapticGeneratorImpl() { cleanUp(); }
ndk::ScopedAStatus commandImpl(CommandId command) REQUIRES(mImplMutex) override;
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
diff --git a/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.cpp b/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.cpp
index e671543..e4b0484 100644
--- a/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.cpp
+++ b/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.cpp
@@ -28,7 +28,6 @@
HapticGeneratorContext::HapticGeneratorContext(int statusDepth, const Parameter::Common& common)
: EffectContext(statusDepth, common) {
- LOG(DEBUG) << __func__;
mState = HAPTIC_GENERATOR_STATE_UNINITIALIZED;
mSampleRate = common.input.base.sampleRate;
mFrameCount = common.input.frameCount;
@@ -36,7 +35,6 @@
}
HapticGeneratorContext::~HapticGeneratorContext() {
- LOG(DEBUG) << __func__;
mState = HAPTIC_GENERATOR_STATE_UNINITIALIZED;
}
@@ -70,7 +68,6 @@
RetCode HapticGeneratorContext::setHgHapticScales(
const std::vector<HapticGenerator::HapticScale>& hapticScales) {
- std::lock_guard lg(mMutex);
for (auto hapticScale : hapticScales) {
mParams.mHapticScales.insert_or_assign(hapticScale.id, hapticScale.scale);
}
@@ -82,13 +79,11 @@
}
HapticGenerator::VibratorInformation HapticGeneratorContext::getHgVibratorInformation() {
- std::lock_guard lg(mMutex);
return mParams.mVibratorInfo;
}
std::vector<HapticGenerator::HapticScale> HapticGeneratorContext::getHgHapticScales() {
std::vector<HapticGenerator::HapticScale> result;
- std::lock_guard lg(mMutex);
for (const auto& [id, vibratorScale] : mParams.mHapticScales) {
result.push_back({id, vibratorScale});
}
@@ -97,30 +92,23 @@
RetCode HapticGeneratorContext::setHgVibratorInformation(
const HapticGenerator::VibratorInformation& vibratorInfo) {
- {
- std::lock_guard lg(mMutex);
- mParams.mVibratorInfo = vibratorInfo;
+ mParams.mVibratorInfo = vibratorInfo;
- if (mProcessorsRecord.bpf != nullptr) {
- mProcessorsRecord.bpf->setCoefficients(
- ::android::audio_effect::haptic_generator::bpfCoefs(
- mParams.mVibratorInfo.resonantFrequencyHz, DEFAULT_BPF_Q, mSampleRate));
- }
- if (mProcessorsRecord.bsf != nullptr) {
- mProcessorsRecord.bsf->setCoefficients(
- ::android::audio_effect::haptic_generator::bsfCoefs(
- mParams.mVibratorInfo.resonantFrequencyHz,
- mParams.mVibratorInfo.qFactor, mParams.mVibratorInfo.qFactor / 2.0f,
- mSampleRate));
- }
+ if (mProcessorsRecord.bpf != nullptr) {
+ mProcessorsRecord.bpf->setCoefficients(::android::audio_effect::haptic_generator::bpfCoefs(
+ mParams.mVibratorInfo.resonantFrequencyHz, DEFAULT_BPF_Q, mSampleRate));
}
+ if (mProcessorsRecord.bsf != nullptr) {
+ mProcessorsRecord.bsf->setCoefficients(::android::audio_effect::haptic_generator::bsfCoefs(
+ mParams.mVibratorInfo.resonantFrequencyHz, mParams.mVibratorInfo.qFactor,
+ mParams.mVibratorInfo.qFactor / 2.0f, mSampleRate));
+ }
+
configure();
return RetCode::SUCCESS;
}
IEffect::Status HapticGeneratorContext::process(float* in, float* out, int samples) {
- LOG(DEBUG) << __func__ << " in " << in << " out " << out << " sample " << samples;
-
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!in, status, "nullInput");
RETURN_VALUE_IF(!out, status, "nullOutput");
@@ -129,17 +117,11 @@
auto frameSize = getInputFrameSize();
RETURN_VALUE_IF(0 == frameSize, status, "zeroFrameSize");
- LOG(DEBUG) << __func__ << " start processing";
// The audio data must not be modified but just written to
// output buffer according the access mode.
- bool accumulate = false;
if (in != out) {
for (int i = 0; i < samples; i++) {
- if (accumulate) {
- out[i] += in[i];
- } else {
- out[i] = in[i];
- }
+ out[i] = in[i];
}
}
@@ -147,7 +129,6 @@
return status;
}
- std::lock_guard lg(mMutex);
if (mParams.mMaxVibratorScale == HapticGenerator::VibratorScale::MUTE) {
// Haptic channels are muted, not need to generate haptic data.
return {STATUS_OK, samples, samples};
@@ -189,7 +170,6 @@
void HapticGeneratorContext::init_params(media::audio::common::AudioChannelLayout inputChMask,
media::audio::common::AudioChannelLayout outputChMask) {
- std::lock_guard lg(mMutex);
mParams.mMaxVibratorScale = HapticGenerator::VibratorScale::MUTE;
mParams.mVibratorInfo.resonantFrequencyHz = DEFAULT_RESONANT_FREQUENCY;
mParams.mVibratorInfo.qFactor = DEFAULT_BSF_ZERO_Q;
@@ -210,7 +190,6 @@
float HapticGeneratorContext::getDistortionOutputGain() {
float distortionOutputGain = getFloatProperty(
"vendor.audio.hapticgenerator.distortion.output.gain", DEFAULT_DISTORTION_OUTPUT_GAIN);
- LOG(DEBUG) << "Using distortion output gain as " << distortionOutputGain;
return distortionOutputGain;
}
@@ -237,7 +216,6 @@
* Build haptic generator processing chain.
*/
void HapticGeneratorContext::buildProcessingChain() {
- std::lock_guard lg(mMutex);
const size_t channelCount = mParams.mHapticChannelCount;
float highPassCornerFrequency = 50.0f;
auto hpf = ::android::audio_effect::haptic_generator::createHPF2(highPassCornerFrequency,
diff --git a/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.h b/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.h
index 8618b7b..3a2ad1c 100644
--- a/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.h
+++ b/media/libeffects/hapticgenerator/aidl/HapticGeneratorContext.h
@@ -16,7 +16,6 @@
#pragma once
-#include <android-base/thread_annotations.h>
#include <vibrator/ExternalVibrationUtils.h>
#include <map>
@@ -88,9 +87,8 @@
static constexpr float DEFAULT_DISTORTION_INPUT_GAIN = 0.3f;
static constexpr float DEFAULT_DISTORTION_CUBE_THRESHOLD = 0.1f;
- std::mutex mMutex;
HapticGeneratorState mState;
- HapticGeneratorParam mParams GUARDED_BY(mMutex);
+ HapticGeneratorParam mParams;
int mSampleRate;
int64_t mFrameCount = 0;
diff --git a/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.cpp b/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.cpp
index bcf0db6..f89606e 100644
--- a/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.cpp
+++ b/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.cpp
@@ -37,7 +37,6 @@
}
if (instanceSpp) {
*instanceSpp = ndk::SharedRefBase::make<LoudnessEnhancerImpl>();
- LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
LOG(ERROR) << __func__ << " invalid input parameter!";
@@ -67,7 +66,6 @@
ndk::ScopedAStatus LoudnessEnhancerImpl::getDescriptor(Descriptor* _aidl_return) {
RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr");
- LOG(DEBUG) << __func__ << kDescriptor.toString();
*_aidl_return = kDescriptor;
return ndk::ScopedAStatus::ok();
}
diff --git a/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.h b/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.h
index e2e716c..98bdc6b 100644
--- a/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.h
+++ b/media/libeffects/loudness/aidl/EffectLoudnessEnhancer.h
@@ -27,11 +27,8 @@
public:
static const std::string kEffectName;
static const Descriptor kDescriptor;
- LoudnessEnhancerImpl() { LOG(DEBUG) << __func__; }
- ~LoudnessEnhancerImpl() {
- cleanUp();
- LOG(DEBUG) << __func__;
- }
+ LoudnessEnhancerImpl() = default;
+ ~LoudnessEnhancerImpl() { cleanUp(); }
ndk::ScopedAStatus commandImpl(CommandId command) REQUIRES(mImplMutex) override;
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
diff --git a/media/libeffects/loudness/aidl/LoudnessEnhancerContext.cpp b/media/libeffects/loudness/aidl/LoudnessEnhancerContext.cpp
index be914bf..d8bcfc0 100644
--- a/media/libeffects/loudness/aidl/LoudnessEnhancerContext.cpp
+++ b/media/libeffects/loudness/aidl/LoudnessEnhancerContext.cpp
@@ -24,16 +24,10 @@
LoudnessEnhancerContext::LoudnessEnhancerContext(int statusDepth, const Parameter::Common& common)
: EffectContext(statusDepth, common) {
- LOG(DEBUG) << __func__;
init_params();
}
-LoudnessEnhancerContext::~LoudnessEnhancerContext() {
- LOG(DEBUG) << __func__;
-}
-
RetCode LoudnessEnhancerContext::enable() {
- std::lock_guard lg(mMutex);
if (mState != LOUDNESS_ENHANCER_STATE_INITIALIZED) {
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
@@ -42,7 +36,6 @@
}
RetCode LoudnessEnhancerContext::disable() {
- std::lock_guard lg(mMutex);
if (mState != LOUDNESS_ENHANCER_STATE_ACTIVE) {
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
@@ -52,7 +45,6 @@
void LoudnessEnhancerContext::reset() {
float targetAmp = pow(10, mGain / 2000.0f); // mB to linear amplification
- std::lock_guard lg(mMutex);
if (mCompressor != nullptr) {
// Get samplingRate from input
mCompressor->Initialize(targetAmp, mCommon.input.base.sampleRate);
@@ -66,8 +58,6 @@
}
IEffect::Status LoudnessEnhancerContext::process(float* in, float* out, int samples) {
- LOG(DEBUG) << __func__ << " in " << in << " out " << out << " sample " << samples;
-
IEffect::Status status = {EX_NULL_POINTER, 0, 0};
RETURN_VALUE_IF(!in, status, "nullInput");
RETURN_VALUE_IF(!out, status, "nullOutput");
@@ -76,11 +66,9 @@
auto frameSize = getInputFrameSize();
RETURN_VALUE_IF(0 == frameSize, status, "zeroFrameSize");
- std::lock_guard lg(mMutex);
status = {STATUS_INVALID_OPERATION, 0, 0};
RETURN_VALUE_IF(mState != LOUDNESS_ENHANCER_STATE_ACTIVE, status, "stateNotActive");
- LOG(DEBUG) << __func__ << " start processing";
// PcmType is always expected to be Float 32 bit.
constexpr float scale = 1 << 15; // power of 2 is lossless conversion to int16_t range
constexpr float inverseScale = 1.f / scale;
@@ -124,9 +112,8 @@
mGain = LOUDNESS_ENHANCER_DEFAULT_TARGET_GAIN_MB;
float targetAmp = pow(10, mGain / 2000.0f); // mB to linear amplification
- LOG(DEBUG) << __func__ << "Target gain = " << mGain << "mB <=> factor = " << targetAmp;
+ LOG(VERBOSE) << __func__ << "Target gain = " << mGain << "mB <=> factor = " << targetAmp;
- std::lock_guard lg(mMutex);
mCompressor = std::make_unique<le_fx::AdaptiveDynamicRangeCompression>();
mCompressor->Initialize(targetAmp, mCommon.input.base.sampleRate);
mState = LOUDNESS_ENHANCER_STATE_INITIALIZED;
diff --git a/media/libeffects/loudness/aidl/LoudnessEnhancerContext.h b/media/libeffects/loudness/aidl/LoudnessEnhancerContext.h
index fd688d7..192b212 100644
--- a/media/libeffects/loudness/aidl/LoudnessEnhancerContext.h
+++ b/media/libeffects/loudness/aidl/LoudnessEnhancerContext.h
@@ -16,7 +16,6 @@
#pragma once
-#include <android-base/thread_annotations.h>
#include <audio_effects/effect_loudnessenhancer.h>
#include "dsp/core/dynamic_range_compression.h"
@@ -33,7 +32,7 @@
class LoudnessEnhancerContext final : public EffectContext {
public:
LoudnessEnhancerContext(int statusDepth, const Parameter::Common& common);
- ~LoudnessEnhancerContext();
+ ~LoudnessEnhancerContext() = default;
RetCode enable();
RetCode disable();
@@ -45,12 +44,11 @@
IEffect::Status process(float* in, float* out, int samples);
private:
- std::mutex mMutex;
- LoudnessEnhancerState mState GUARDED_BY(mMutex) = LOUDNESS_ENHANCER_STATE_UNINITIALIZED;
+ LoudnessEnhancerState mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED;
int mGain = LOUDNESS_ENHANCER_DEFAULT_TARGET_GAIN_MB;
// In this implementation, there is no coupling between the compression on the left and right
// channels
- std::unique_ptr<le_fx::AdaptiveDynamicRangeCompression> mCompressor GUARDED_BY(mMutex);
+ std::unique_ptr<le_fx::AdaptiveDynamicRangeCompression> mCompressor;
void init_params();
};
diff --git a/media/libeffects/lvm/wrapper/Aidl/BundleContext.cpp b/media/libeffects/lvm/wrapper/Aidl/BundleContext.cpp
index aa18deb..90406e9 100644
--- a/media/libeffects/lvm/wrapper/Aidl/BundleContext.cpp
+++ b/media/libeffects/lvm/wrapper/Aidl/BundleContext.cpp
@@ -36,20 +36,16 @@
BundleContext::BundleContext(int statusDepth, const Parameter::Common& common,
const lvm::BundleEffectType& type)
: EffectContext(statusDepth, common), mType(type) {
- LOG(DEBUG) << __func__ << type;
-
int inputChannelCount = ::aidl::android::hardware::audio::common::getChannelCount(
common.input.base.channelMask);
mSamplesPerSecond = common.input.base.sampleRate * inputChannelCount;
}
BundleContext::~BundleContext() {
- LOG(DEBUG) << __func__;
deInit();
}
RetCode BundleContext::init() {
- std::lock_guard lg(mMutex);
// init with pre-defined preset NORMAL
for (std::size_t i = 0; i < lvm::MAX_NUM_BANDS; i++) {
mBandGainmB[i] = lvm::kSoftPresets[0 /* normal */][i] * 100;
@@ -88,7 +84,6 @@
}
void BundleContext::deInit() {
- std::lock_guard lg(mMutex);
if (mInstance) {
LVM_DelInstanceHandle(&mInstance);
mInstance = nullptr;
@@ -102,27 +97,23 @@
bool tempDisabled = false;
switch (mType) {
case lvm::BundleEffectType::EQUALIZER:
- LOG(DEBUG) << __func__ << " enable bundle EQ";
if (mSamplesToExitCountEq <= 0) mNumberEffectsEnabled++;
mSamplesToExitCountEq = (mSamplesPerSecond * 0.1);
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::EQUALIZER));
break;
case lvm::BundleEffectType::BASS_BOOST:
- LOG(DEBUG) << __func__ << " enable bundle BB";
if (mSamplesToExitCountBb <= 0) mNumberEffectsEnabled++;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::BASS_BOOST));
mSamplesToExitCountBb = (mSamplesPerSecond * 0.1);
tempDisabled = mBassTempDisabled;
break;
case lvm::BundleEffectType::VIRTUALIZER:
- LOG(DEBUG) << __func__ << " enable bundle VR";
if (mSamplesToExitCountVirt <= 0) mNumberEffectsEnabled++;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::VIRTUALIZER));
mSamplesToExitCountVirt = (mSamplesPerSecond * 0.1);
tempDisabled = mVirtualizerTempDisabled;
break;
case lvm::BundleEffectType::VOLUME:
- LOG(DEBUG) << __func__ << " enable bundle VOL";
if ((mEffectInDrain & (1 << int(lvm::BundleEffectType::VOLUME))) == 0)
mNumberEffectsEnabled++;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::VOLUME));
@@ -134,30 +125,24 @@
RetCode BundleContext::enableOperatingMode() {
LVM_ControlParams_t params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, "failGetControlParams");
- switch (mType) {
- case lvm::BundleEffectType::EQUALIZER:
- LOG(DEBUG) << __func__ << " enable bundle EQ";
- params.EQNB_OperatingMode = LVM_EQNB_ON;
- break;
- case lvm::BundleEffectType::BASS_BOOST:
- LOG(DEBUG) << __func__ << " enable bundle BB";
- params.BE_OperatingMode = LVM_BE_ON;
- break;
- case lvm::BundleEffectType::VIRTUALIZER:
- LOG(DEBUG) << __func__ << " enable bundle VR";
- params.VirtualizerOperatingMode = LVM_MODE_ON;
- break;
- case lvm::BundleEffectType::VOLUME:
- LOG(DEBUG) << __func__ << " enable bundle VOL";
- break;
- }
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, "failSetControlParams");
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, "failGetControlParams");
+ switch (mType) {
+ case lvm::BundleEffectType::EQUALIZER:
+ params.EQNB_OperatingMode = LVM_EQNB_ON;
+ break;
+ case lvm::BundleEffectType::BASS_BOOST:
+ params.BE_OperatingMode = LVM_BE_ON;
+ break;
+ case lvm::BundleEffectType::VIRTUALIZER:
+ params.VirtualizerOperatingMode = LVM_MODE_ON;
+ break;
+ case lvm::BundleEffectType::VOLUME:
+ break;
}
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, "failSetControlParams");
+
return limitLevel();
}
@@ -165,19 +150,15 @@
if (!mEnabled) return RetCode::ERROR_ILLEGAL_PARAMETER;
switch (mType) {
case lvm::BundleEffectType::EQUALIZER:
- LOG(DEBUG) << __func__ << " disable bundle EQ";
mEffectInDrain |= 1 << int(lvm::BundleEffectType::EQUALIZER);
break;
case lvm::BundleEffectType::BASS_BOOST:
- LOG(DEBUG) << __func__ << " disable bundle BB";
mEffectInDrain |= 1 << int(lvm::BundleEffectType::BASS_BOOST);
break;
case lvm::BundleEffectType::VIRTUALIZER:
- LOG(DEBUG) << __func__ << " disable bundle VR";
mEffectInDrain |= 1 << int(lvm::BundleEffectType::VIRTUALIZER);
break;
case lvm::BundleEffectType::VOLUME:
- LOG(DEBUG) << __func__ << " disable bundle VOL";
mEffectInDrain |= 1 << int(lvm::BundleEffectType::VOLUME);
break;
}
@@ -187,30 +168,23 @@
RetCode BundleContext::disableOperatingMode() {
LVM_ControlParams_t params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, "failGetControlParams");
- switch (mType) {
- case lvm::BundleEffectType::EQUALIZER:
- LOG(DEBUG) << __func__ << " disable bundle EQ";
- params.EQNB_OperatingMode = LVM_EQNB_OFF;
- break;
- case lvm::BundleEffectType::BASS_BOOST:
- LOG(DEBUG) << __func__ << " disable bundle BB";
- params.BE_OperatingMode = LVM_BE_OFF;
- break;
- case lvm::BundleEffectType::VIRTUALIZER:
- LOG(DEBUG) << __func__ << " disable bundle VR";
- params.VirtualizerOperatingMode = LVM_MODE_OFF;
- break;
- case lvm::BundleEffectType::VOLUME:
- LOG(DEBUG) << __func__ << " disable bundle VOL";
- break;
- }
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, "failSetControlParams");
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, "failGetControlParams");
+ switch (mType) {
+ case lvm::BundleEffectType::EQUALIZER:
+ params.EQNB_OperatingMode = LVM_EQNB_OFF;
+ break;
+ case lvm::BundleEffectType::BASS_BOOST:
+ params.BE_OperatingMode = LVM_BE_OFF;
+ break;
+ case lvm::BundleEffectType::VIRTUALIZER:
+ params.VirtualizerOperatingMode = LVM_MODE_OFF;
+ break;
+ case lvm::BundleEffectType::VOLUME:
+ break;
}
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, "failSetControlParams");
mEnabled = false;
return limitLevel();
}
@@ -223,89 +197,80 @@
float energyBassBoost = 0;
float crossCorrection = 0;
LVM_ControlParams_t params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- bool eqEnabled = params.EQNB_OperatingMode == LVM_EQNB_ON;
- bool bbEnabled = params.BE_OperatingMode == LVM_BE_ON;
- bool viEnabled = params.VirtualizerOperatingMode == LVM_MODE_ON;
+ bool eqEnabled = params.EQNB_OperatingMode == LVM_EQNB_ON;
+ bool bbEnabled = params.BE_OperatingMode == LVM_BE_ON;
+ bool viEnabled = params.VirtualizerOperatingMode == LVM_MODE_ON;
+
+ if (eqEnabled) {
+ for (unsigned int i = 0; i < lvm::MAX_NUM_BANDS; i++) {
+ float bandFactor = mBandGainmB[i] / 1500.0;
+ float bandCoefficient = lvm::kBandEnergyCoefficient[i];
+ float bandEnergy = bandFactor * bandCoefficient * bandCoefficient;
+ if (bandEnergy > 0) energyContribution += bandEnergy;
+ }
+
+ // cross EQ coefficients
+ float bandFactorSum = 0;
+ for (unsigned int i = 0; i < lvm::MAX_NUM_BANDS - 1; i++) {
+ float bandFactor1 = mBandGainmB[i] / 1500.0;
+ float bandFactor2 = mBandGainmB[i + 1] / 1500.0;
+
+ if (bandFactor1 > 0 && bandFactor2 > 0) {
+ float crossEnergy =
+ bandFactor1 * bandFactor2 * lvm::kBandEnergyCrossCoefficient[i];
+ bandFactorSum += bandFactor1 * bandFactor2;
+
+ if (crossEnergy > 0) energyCross += crossEnergy;
+ }
+ }
+ bandFactorSum -= 1.0;
+ if (bandFactorSum > 0) crossCorrection = bandFactorSum * 0.7;
+ }
+ // BassBoost contribution
+ if (bbEnabled) {
+ float boostFactor = mBassStrengthSaved / 1000.0;
+ float boostCoefficient = lvm::kBassBoostEnergyCoefficient;
+
+ energyContribution += boostFactor * boostCoefficient * boostCoefficient;
if (eqEnabled) {
for (unsigned int i = 0; i < lvm::MAX_NUM_BANDS; i++) {
float bandFactor = mBandGainmB[i] / 1500.0;
- float bandCoefficient = lvm::kBandEnergyCoefficient[i];
- float bandEnergy = bandFactor * bandCoefficient * bandCoefficient;
- if (bandEnergy > 0) energyContribution += bandEnergy;
- }
-
- // cross EQ coefficients
- float bandFactorSum = 0;
- for (unsigned int i = 0; i < lvm::MAX_NUM_BANDS - 1; i++) {
- float bandFactor1 = mBandGainmB[i] / 1500.0;
- float bandFactor2 = mBandGainmB[i + 1] / 1500.0;
-
- if (bandFactor1 > 0 && bandFactor2 > 0) {
- float crossEnergy =
- bandFactor1 * bandFactor2 * lvm::kBandEnergyCrossCoefficient[i];
- bandFactorSum += bandFactor1 * bandFactor2;
-
- if (crossEnergy > 0) energyCross += crossEnergy;
- }
- }
- bandFactorSum -= 1.0;
- if (bandFactorSum > 0) crossCorrection = bandFactorSum * 0.7;
- }
- // BassBoost contribution
- if (bbEnabled) {
- float boostFactor = mBassStrengthSaved / 1000.0;
- float boostCoefficient = lvm::kBassBoostEnergyCoefficient;
-
- energyContribution += boostFactor * boostCoefficient * boostCoefficient;
-
- if (eqEnabled) {
- for (unsigned int i = 0; i < lvm::MAX_NUM_BANDS; i++) {
- float bandFactor = mBandGainmB[i] / 1500.0;
- float bandCrossCoefficient = lvm::kBassBoostEnergyCrossCoefficient[i];
- float bandEnergy = boostFactor * bandFactor * bandCrossCoefficient;
- if (bandEnergy > 0) energyBassBoost += bandEnergy;
- }
+ float bandCrossCoefficient = lvm::kBassBoostEnergyCrossCoefficient[i];
+ float bandEnergy = boostFactor * bandFactor * bandCrossCoefficient;
+ if (bandEnergy > 0) energyBassBoost += bandEnergy;
}
}
- // Virtualizer contribution
- if (viEnabled) {
- energyContribution += lvm::kVirtualizerContribution * lvm::kVirtualizerContribution;
- }
+ }
+ // Virtualizer contribution
+ if (viEnabled) {
+ energyContribution += lvm::kVirtualizerContribution * lvm::kVirtualizerContribution;
+ }
- double totalEnergyEstimation =
- sqrt(energyContribution + energyCross + energyBassBoost) - crossCorrection;
- LOG(INFO) << " TOTAL energy estimation: " << totalEnergyEstimation << " dB";
+ double totalEnergyEstimation =
+ sqrt(energyContribution + energyCross + energyBassBoost) - crossCorrection;
- // roundoff
- int maxLevelRound = (int)(totalEnergyEstimation + 0.99);
- if (maxLevelRound + mVolumedB > 0) {
- gainCorrection = maxLevelRound + mVolumedB;
- }
+ // roundoff
+ int maxLevelRound = (int)(totalEnergyEstimation + 0.99);
+ if (maxLevelRound + mVolumedB > 0) {
+ gainCorrection = maxLevelRound + mVolumedB;
+ }
- params.VC_EffectLevel = mVolumedB - gainCorrection;
- if (params.VC_EffectLevel < -96) {
- params.VC_EffectLevel = -96;
- }
- LOG(INFO) << "\tVol: " << mVolumedB << ", GainCorrection: " << gainCorrection
- << ", Actual vol: " << params.VC_EffectLevel;
+ params.VC_EffectLevel = mVolumedB - gainCorrection;
+ if (params.VC_EffectLevel < -96) {
+ params.VC_EffectLevel = -96;
+ }
+ /* Activate the initial settings */
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- /* Activate the initial settings */
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
-
- if (mFirstVolume) {
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetVolumeNoSmoothing(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setVolumeNoSmoothingFailed");
- LOG(INFO) << "\tLVM_VOLUME: Disabling Smoothing for first volume change to remove "
- "spikes/clicks";
- mFirstVolume = false;
- }
+ if (mFirstVolume) {
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetVolumeNoSmoothing(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setVolumeNoSmoothingFailed");
+ mFirstVolume = false;
}
return RetCode::SUCCESS;
@@ -439,17 +404,13 @@
float maxdB = std::max(leftdB, rightdB);
float pandB = rightdB - leftdB;
setVolumeLevel(maxdB);
- LOG(DEBUG) << __func__ << " pandB: " << pandB << " maxdB " << maxdB;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, "");
- params.VC_Balance = pandB;
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, "");
+ params.VC_Balance = pandB;
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, "");
- }
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, "");
mVolumeStereo = volume;
return RetCode::SUCCESS;
}
@@ -469,7 +430,6 @@
RetCode ret = updateControlParameter(bandLevels);
if (RetCode::SUCCESS == ret) {
mCurPresetIdx = presetIdx;
- LOG(INFO) << __func__ << " success with " << presetIdx;
} else {
LOG(ERROR) << __func__ << " failed to setPreset " << presetIdx;
}
@@ -483,7 +443,6 @@
RetCode ret = updateControlParameter(bandLevels);
if (RetCode::SUCCESS == ret) {
mCurPresetIdx = lvm::PRESET_CUSTOM;
- LOG(INFO) << __func__ << " succeed with " << ::android::internal::ToString(bandLevels);
} else {
LOG(ERROR) << __func__ << " failed with " << ::android::internal::ToString(bandLevels);
}
@@ -502,14 +461,11 @@
std::vector<int32_t> BundleContext::getEqualizerCenterFreqs() {
std::vector<int32_t> freqs;
LVM_ControlParams_t params;
- {
- std::lock_guard lg(mMutex);
- /* Get the current settings */
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms), freqs,
- " getControlParamFailed");
- for (std::size_t i = 0; i < lvm::MAX_NUM_BANDS; i++) {
- freqs.push_back((int32_t)params.pEQNB_BandDefinition[i].Frequency * 1000);
- }
+ /* Get the current settings */
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms), freqs,
+ " getControlParamFailed");
+ for (std::size_t i = 0; i < lvm::MAX_NUM_BANDS; i++) {
+ freqs.push_back((int32_t)params.pEQNB_BandDefinition[i].Frequency * 1000);
}
return freqs;
@@ -533,44 +489,36 @@
}
LVM_ControlParams_t params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- for (std::size_t i = 0; i < lvm::MAX_NUM_BANDS; i++) {
- params.pEQNB_BandDefinition[i].Frequency = lvm::kPresetsFrequencies[i];
- params.pEQNB_BandDefinition[i].QFactor = lvm::kPresetsQFactors[i];
- params.pEQNB_BandDefinition[i].Gain =
- tempLevel[i] > 0 ? (tempLevel[i] + 50) / 100 : (tempLevel[i] - 50) / 100;
- }
-
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
+ for (std::size_t i = 0; i < lvm::MAX_NUM_BANDS; i++) {
+ params.pEQNB_BandDefinition[i].Frequency = lvm::kPresetsFrequencies[i];
+ params.pEQNB_BandDefinition[i].QFactor = lvm::kPresetsQFactors[i];
+ params.pEQNB_BandDefinition[i].Gain =
+ tempLevel[i] > 0 ? (tempLevel[i] + 50) / 100 : (tempLevel[i] - 50) / 100;
}
- mBandGainmB = tempLevel;
- LOG(DEBUG) << __func__ << " update bandGain to " << ::android::internal::ToString(mBandGainmB)
- << "mdB";
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
+
+ mBandGainmB = tempLevel;
return RetCode::SUCCESS;
}
RetCode BundleContext::setBassBoostStrength(int strength) {
// Update Control Parameter
LVM_ControlParams_t params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- params.BE_EffectLevel = (LVM_INT16)((15 * strength) / 1000);
- params.BE_CentreFreq = LVM_BE_CENTRE_90Hz;
+ params.BE_EffectLevel = (LVM_INT16)((15 * strength) / 1000);
+ params.BE_CentreFreq = LVM_BE_CENTRE_90Hz;
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- }
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
+
mBassStrengthSaved = strength;
- LOG(INFO) << __func__ << " success with strength " << strength;
return limitLevel();
}
@@ -580,7 +528,6 @@
} else {
mVolumedB = level;
}
- LOG(INFO) << __func__ << " success with level " << level;
return limitLevel();
}
@@ -602,19 +549,15 @@
RetCode BundleContext::setVirtualizerStrength(int strength) {
// Update Control Parameter
LVM_ControlParams_t params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- params.CS_EffectLevel = ((strength * 32767) / 1000);
+ params.CS_EffectLevel = ((strength * 32767) / 1000);
- RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- }
+ RETURN_VALUE_IF(LVM_SUCCESS != LVM_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
mVirtStrengthSaved = strength;
- LOG(INFO) << __func__ << " success with strength " << strength;
return limitLevel();
}
@@ -760,29 +703,24 @@
auto frameSize = getInputFrameSize();
RETURN_VALUE_IF(0 == frameSize, status, "zeroFrameSize");
- LOG(DEBUG) << __func__ << " start processing";
if ((mEffectProcessCalled & 1 << int(mType)) != 0) {
const int undrainedEffects = mEffectInDrain & ~mEffectProcessCalled;
if ((undrainedEffects & 1 << int(lvm::BundleEffectType::EQUALIZER)) != 0) {
- LOG(DEBUG) << "Draining EQUALIZER";
mSamplesToExitCountEq = 0;
--mNumberEffectsEnabled;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::EQUALIZER));
}
if ((undrainedEffects & 1 << int(lvm::BundleEffectType::BASS_BOOST)) != 0) {
- LOG(DEBUG) << "Draining BASS_BOOST";
mSamplesToExitCountBb = 0;
--mNumberEffectsEnabled;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::BASS_BOOST));
}
if ((undrainedEffects & 1 << int(lvm::BundleEffectType::VIRTUALIZER)) != 0) {
- LOG(DEBUG) << "Draining VIRTUALIZER";
mSamplesToExitCountVirt = 0;
--mNumberEffectsEnabled;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::VIRTUALIZER));
}
if ((undrainedEffects & 1 << int(lvm::BundleEffectType::VOLUME)) != 0) {
- LOG(DEBUG) << "Draining VOLUME";
--mNumberEffectsEnabled;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::VOLUME));
}
@@ -800,7 +738,6 @@
mNumberEffectsEnabled--;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::EQUALIZER));
}
- LOG(DEBUG) << "Effect_process() this is the last frame for EQUALIZER";
}
break;
case lvm::BundleEffectType::BASS_BOOST:
@@ -813,7 +750,6 @@
mNumberEffectsEnabled--;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::BASS_BOOST));
}
- LOG(DEBUG) << "Effect_process() this is the last frame for BASS_BOOST";
}
break;
case lvm::BundleEffectType::VIRTUALIZER:
@@ -826,7 +762,6 @@
mNumberEffectsEnabled--;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::VIRTUALIZER));
}
- LOG(DEBUG) << "Effect_process() this is the last frame for VIRTUALIZER";
}
break;
case lvm::BundleEffectType::VOLUME:
@@ -835,14 +770,13 @@
mNumberEffectsEnabled--;
mEffectInDrain &= ~(1 << int(lvm::BundleEffectType::VOLUME));
}
- LOG(DEBUG) << "Effect_process() LVM_VOLUME Effect is not enabled";
break;
}
}
if (isDataAvailable) {
mNumberEffectsCalled++;
}
- bool accumulate = false;
+
if (mNumberEffectsCalled >= mNumberEffectsEnabled) {
// We expect the # effects called to be equal to # effects enabled in sequence (including
// draining effects). Warn if this is not the case due to inconsistent calls.
@@ -850,9 +784,6 @@
"%s Number of effects called %d is greater than number of effects enabled %d",
__func__, mNumberEffectsCalled, mNumberEffectsEnabled);
mEffectProcessCalled = 0; // reset our consistency check.
- if (!isDataAvailable) {
- LOG(DEBUG) << "Effect_process() processing last frame";
- }
mNumberEffectsCalled = 0;
int frames = samples * sizeof(float) / frameSize;
int bufferIndex = 0;
@@ -862,38 +793,24 @@
constexpr int kMaxBlockFrames =
(std::numeric_limits<int16_t>::max() / kBlockSizeMultiple) * kBlockSizeMultiple;
while (frames > 0) {
- float* outTmp = (accumulate ? getWorkBuffer() : out);
/* Process the samples */
LVM_ReturnStatus_en lvmStatus;
- {
- std::lock_guard lg(mMutex);
- int processFrames = std::min(frames, kMaxBlockFrames);
- lvmStatus = LVM_Process(mInstance, in + bufferIndex, outTmp + bufferIndex,
- processFrames, 0);
- if (lvmStatus != LVM_SUCCESS) {
- LOG(ERROR) << "LVM lib failed with error: " << lvmStatus;
- return {EX_UNSUPPORTED_OPERATION, 0, 0};
- }
- if (accumulate) {
- for (int i = 0; i < samples; i++) {
- out[i] += outTmp[i];
- }
- }
- frames -= processFrames;
- int processedSize = processFrames * frameSize / sizeof(float);
- bufferIndex += processedSize;
+ int processFrames = std::min(frames, kMaxBlockFrames);
+ lvmStatus = LVM_Process(mInstance, in + bufferIndex, out + bufferIndex,
+ processFrames, 0);
+ if (lvmStatus != LVM_SUCCESS) {
+ LOG(ERROR) << "LVM_Process failed with error: " << lvmStatus;
+ return {EX_UNSUPPORTED_OPERATION, 0, 0};
}
+ frames -= processFrames;
+ int processedSize = processFrames * frameSize / sizeof(float);
+ bufferIndex += processedSize;
}
} else {
for (int i = 0; i < samples; i++) {
- if (accumulate) {
- out[i] += in[i];
- } else {
- out[i] = in[i];
- }
+ out[i] = in[i];
}
}
- LOG(DEBUG) << __func__ << " done processing";
return {STATUS_OK, samples, samples};
}
diff --git a/media/libeffects/lvm/wrapper/Aidl/BundleContext.h b/media/libeffects/lvm/wrapper/Aidl/BundleContext.h
index d823030..ba3997a 100644
--- a/media/libeffects/lvm/wrapper/Aidl/BundleContext.h
+++ b/media/libeffects/lvm/wrapper/Aidl/BundleContext.h
@@ -17,7 +17,6 @@
#pragma once
#include <android-base/logging.h>
-#include <android-base/thread_annotations.h>
#include <array>
#include <cstddef>
@@ -90,10 +89,9 @@
IEffect::Status processEffect(float* in, float* out, int sampleToProcess);
private:
- std::mutex mMutex;
const lvm::BundleEffectType mType;
bool mEnabled = false;
- LVM_Handle_t mInstance GUARDED_BY(mMutex);
+ LVM_Handle_t mInstance;
aidl::android::media::audio::common::AudioDeviceDescription mVirtualizerForcedDevice;
diff --git a/media/libeffects/lvm/wrapper/Aidl/EffectBundleAidl.cpp b/media/libeffects/lvm/wrapper/Aidl/EffectBundleAidl.cpp
index 755f57c..70c276d 100644
--- a/media/libeffects/lvm/wrapper/Aidl/EffectBundleAidl.cpp
+++ b/media/libeffects/lvm/wrapper/Aidl/EffectBundleAidl.cpp
@@ -55,7 +55,6 @@
}
if (instanceSpp) {
*instanceSpp = ndk::SharedRefBase::make<EffectBundleAidl>(*uuid);
- LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
LOG(ERROR) << __func__ << " invalid input parameter!";
@@ -83,7 +82,6 @@
namespace aidl::android::hardware::audio::effect {
EffectBundleAidl::EffectBundleAidl(const AudioUuid& uuid) {
- LOG(DEBUG) << __func__ << uuid.toString();
if (uuid == getEffectImplUuidEqualizerBundle()) {
mType = lvm::BundleEffectType::EQUALIZER;
mDescriptor = &lvm::kEqualizerDesc;
@@ -107,12 +105,10 @@
EffectBundleAidl::~EffectBundleAidl() {
cleanUp();
- LOG(DEBUG) << __func__;
}
ndk::ScopedAStatus EffectBundleAidl::getDescriptor(Descriptor* _aidl_return) {
RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr");
- LOG(DEBUG) << _aidl_return->toString();
*_aidl_return = *mDescriptor;
return ndk::ScopedAStatus::ok();
}
@@ -154,7 +150,6 @@
}
ndk::ScopedAStatus EffectBundleAidl::setParameterSpecific(const Parameter::Specific& specific) {
- LOG(DEBUG) << __func__ << " specific " << specific.toString();
RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext");
auto tag = specific.getTag();
diff --git a/media/libeffects/lvm/wrapper/Aidl/GlobalSession.h b/media/libeffects/lvm/wrapper/Aidl/GlobalSession.h
index d31763b..ea1a8fe 100644
--- a/media/libeffects/lvm/wrapper/Aidl/GlobalSession.h
+++ b/media/libeffects/lvm/wrapper/Aidl/GlobalSession.h
@@ -21,7 +21,6 @@
#include <unordered_map>
#include <android-base/logging.h>
-#include <android-base/thread_annotations.h>
#include "BundleContext.h"
#include "BundleTypes.h"
@@ -41,11 +40,6 @@
return instance;
}
- bool isSessionIdExist(int sessionId) {
- std::lock_guard lg(mMutex);
- return mSessionMap.count(sessionId);
- }
-
static bool findBundleTypeInList(std::vector<std::shared_ptr<BundleContext>>& list,
const lvm::BundleEffectType& type, bool remove = false) {
auto itor = std::find_if(list.begin(), list.end(),
@@ -69,8 +63,7 @@
std::shared_ptr<BundleContext> createSession(const lvm::BundleEffectType& type, int statusDepth,
const Parameter::Common& common) {
int sessionId = common.session;
- LOG(DEBUG) << __func__ << type << " with sessionId " << sessionId;
- std::lock_guard lg(mMutex);
+ LOG(VERBOSE) << __func__ << type << " with sessionId " << sessionId;
if (mSessionMap.count(sessionId) == 0 && mSessionMap.size() >= MAX_BUNDLE_SESSIONS) {
LOG(ERROR) << __func__ << " exceed max bundle session";
return nullptr;
@@ -97,8 +90,7 @@
}
void releaseSession(const lvm::BundleEffectType& type, int sessionId) {
- LOG(DEBUG) << __func__ << type << " sessionId " << sessionId;
- std::lock_guard lg(mMutex);
+ LOG(VERBOSE) << __func__ << type << " sessionId " << sessionId;
if (mSessionMap.count(sessionId)) {
auto& list = mSessionMap[sessionId];
if (!findBundleTypeInList(list, type, true /* remove */)) {
@@ -112,11 +104,9 @@
}
private:
- // Lock for mSessionMap access.
- std::mutex mMutex;
// Max session number supported.
static constexpr int MAX_BUNDLE_SESSIONS = 32;
std::unordered_map<int /* session ID */, std::vector<std::shared_ptr<BundleContext>>>
- mSessionMap GUARDED_BY(mMutex);
+ mSessionMap;
};
} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libeffects/lvm/wrapper/Reverb/aidl/EffectReverb.cpp b/media/libeffects/lvm/wrapper/Reverb/aidl/EffectReverb.cpp
index c714bc9..4d369b1 100644
--- a/media/libeffects/lvm/wrapper/Reverb/aidl/EffectReverb.cpp
+++ b/media/libeffects/lvm/wrapper/Reverb/aidl/EffectReverb.cpp
@@ -55,7 +55,6 @@
}
if (instanceSpp) {
*instanceSpp = ndk::SharedRefBase::make<EffectReverb>(*uuid);
- LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
LOG(ERROR) << __func__ << " invalid input parameter!";
@@ -82,7 +81,6 @@
namespace aidl::android::hardware::audio::effect {
EffectReverb::EffectReverb(const AudioUuid& uuid) {
- LOG(DEBUG) << __func__ << uuid.toString();
if (uuid == getEffectImplUuidAuxEnvReverb()) {
mType = lvm::ReverbEffectType::AUX_ENV;
mDescriptor = &lvm::kAuxEnvReverbDesc;
@@ -106,18 +104,16 @@
EffectReverb::~EffectReverb() {
cleanUp();
- LOG(DEBUG) << __func__;
}
ndk::ScopedAStatus EffectReverb::getDescriptor(Descriptor* _aidl_return) {
RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr");
- LOG(DEBUG) << _aidl_return->toString();
*_aidl_return = *mDescriptor;
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus EffectReverb::setParameterSpecific(const Parameter::Specific& specific) {
- LOG(DEBUG) << __func__ << " specific " << specific.toString();
+ LOG(VERBOSE) << __func__ << " specific " << specific.toString();
RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext");
auto tag = specific.getTag();
diff --git a/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.cpp b/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.cpp
index 1c66c78..67518af 100644
--- a/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.cpp
+++ b/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.cpp
@@ -68,24 +68,21 @@
// allocate lvm reverb instance
LVREV_ReturnStatus_en status = LVREV_SUCCESS;
- {
- std::lock_guard lg(mMutex);
- LVREV_InstanceParams_st params = {
- .MaxBlockSize = lvm::kMaxCallSize,
- // Max format, could be mono during process
- .SourceFormat = LVM_STEREO,
- .NumDelays = LVREV_DELAYLINES_4,
- };
- /* Init sets the instance handle */
- status = LVREV_GetInstanceHandle(&mInstance, ¶ms);
- GOTO_IF_LVREV_ERROR(status, deinit, "LVREV_GetInstanceHandleFailed");
+ LVREV_InstanceParams_st params = {
+ .MaxBlockSize = lvm::kMaxCallSize,
+ // Max format, could be mono during process
+ .SourceFormat = LVM_STEREO,
+ .NumDelays = LVREV_DELAYLINES_4,
+ };
+ /* Init sets the instance handle */
+ status = LVREV_GetInstanceHandle(&mInstance, ¶ms);
+ GOTO_IF_LVREV_ERROR(status, deinit, "LVREV_GetInstanceHandleFailed");
- // set control
- LVREV_ControlParams_st controlParams;
- initControlParameter(controlParams);
- status = LVREV_SetControlParameters(mInstance, &controlParams);
- GOTO_IF_LVREV_ERROR(status, deinit, "LVREV_SetControlParametersFailed");
- }
+ // set control
+ LVREV_ControlParams_st controlParams;
+ initControlParameter(controlParams);
+ status = LVREV_SetControlParameters(mInstance, &controlParams);
+ GOTO_IF_LVREV_ERROR(status, deinit, "LVREV_SetControlParametersFailed");
return RetCode::SUCCESS;
@@ -95,7 +92,6 @@
}
void ReverbContext::deInit() {
- std::lock_guard lg(mMutex);
if (mInstance) {
LVREV_FreeInstance(mInstance);
mInstance = nullptr;
@@ -143,19 +139,16 @@
RetCode ReverbContext::setEnvironmentalReverbRoomLevel(int roomLevel) {
// Update Control Parameter
LVREV_ControlParams_st params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- // Sum of room and reverb level controls
- // needs to subtract max levels for both room level and reverb level
- int combinedLevel = (roomLevel + mLevel) - lvm::kMaxReverbLevel;
- params.Level = convertLevel(combinedLevel);
+ // Sum of room and reverb level controls
+ // needs to subtract max levels for both room level and reverb level
+ int combinedLevel = (roomLevel + mLevel) - lvm::kMaxReverbLevel;
+ params.Level = convertLevel(combinedLevel);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- }
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
mRoomLevel = roomLevel;
return RetCode::SUCCESS;
}
@@ -163,16 +156,13 @@
RetCode ReverbContext::setEnvironmentalReverbRoomHfLevel(int roomHfLevel) {
// Update Control Parameter
LVREV_ControlParams_st params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- params.LPF = convertHfLevel(roomHfLevel);
+ params.LPF = convertHfLevel(roomHfLevel);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- }
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
mRoomHfLevel = roomHfLevel;
return RetCode::SUCCESS;
}
@@ -185,17 +175,15 @@
// Update Control Parameter
LVREV_ControlParams_st params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- params.T60 = (LVM_UINT16)time;
- mSamplesToExitCount = (params.T60 * mCommon.input.base.sampleRate) / 1000;
+ params.T60 = (LVM_UINT16)time;
+ mSamplesToExitCount = (params.T60 * mCommon.input.base.sampleRate) / 1000;
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- }
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
+
mDecayTime = time;
return RetCode::SUCCESS;
}
@@ -203,16 +191,13 @@
RetCode ReverbContext::setEnvironmentalReverbDecayHfRatio(int decayHfRatio) {
// Update Control Parameter
LVREV_ControlParams_st params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- params.Damping = (LVM_INT16)(decayHfRatio / 20);
+ params.Damping = (LVM_INT16)(decayHfRatio / 20);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- }
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
mDecayHfRatio = decayHfRatio;
return RetCode::SUCCESS;
}
@@ -220,19 +205,17 @@
RetCode ReverbContext::setEnvironmentalReverbLevel(int level) {
// Update Control Parameter
LVREV_ControlParams_st params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- // Sum of room and reverb level controls
- // needs to subtract max levels for both room level and level
- int combinedLevel = (level + mRoomLevel) - lvm::kMaxReverbLevel;
- params.Level = convertLevel(combinedLevel);
+ // Sum of room and reverb level controls
+ // needs to subtract max levels for both room level and level
+ int combinedLevel = (level + mRoomLevel) - lvm::kMaxReverbLevel;
+ params.Level = convertLevel(combinedLevel);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- }
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
+
mLevel = level;
return RetCode::SUCCESS;
}
@@ -245,16 +228,14 @@
RetCode ReverbContext::setEnvironmentalReverbDiffusion(int diffusion) {
// Update Control Parameter
LVREV_ControlParams_st params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- params.Density = (LVM_INT16)(diffusion / 10);
+ params.Density = (LVM_INT16)(diffusion / 10);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- }
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
+
mDiffusion = diffusion;
return RetCode::SUCCESS;
}
@@ -262,16 +243,14 @@
RetCode ReverbContext::setEnvironmentalReverbDensity(int density) {
// Update Control Parameter
LVREV_ControlParams_st params;
- {
- std::lock_guard lg(mMutex);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_GetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " getControlParamFailed");
- params.RoomSize = (LVM_INT16)(((density * 99) / 1000) + 1);
+ params.RoomSize = (LVM_INT16)(((density * 99) / 1000) + 1);
- RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
- RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
- }
+ RETURN_VALUE_IF(LVREV_SUCCESS != LVREV_SetControlParameters(mInstance, ¶ms),
+ RetCode::ERROR_EFFECT_LIB_ERROR, " setControlParamFailed");
+
mDensity = density;
return RetCode::SUCCESS;
}
@@ -362,9 +341,6 @@
RETURN_VALUE_IF(inputFrameCount != outputFrameCount, status, "FrameCountMismatch");
RETURN_VALUE_IF(0 == getInputFrameSize(), status, "zeroFrameSize");
- LOG(DEBUG) << __func__ << " start processing";
- std::lock_guard lg(mMutex);
-
int channels = ::aidl::android::hardware::audio::common::getChannelCount(
mCommon.input.base.channelMask);
int outChannels = ::aidl::android::hardware::audio::common::getChannelCount(
@@ -405,7 +381,6 @@
} else {
if (!mEnabled && mSamplesToExitCount > 0) {
std::fill(outFrames.begin(), outFrames.end(), 0);
- LOG(VERBOSE) << "Zeroing " << channels << " samples per frame at the end of call ";
}
/* Process the samples, producing a stereo output */
@@ -415,7 +390,7 @@
outFrames.data(), /* Output buffer */
frameCount); /* Number of samples to read */
if (lvrevStatus != LVREV_SUCCESS) {
- LOG(ERROR) << __func__ << lvrevStatus;
+ LOG(ERROR) << __func__ << " LVREV_Process error: " << lvrevStatus;
return {EX_UNSUPPORTED_OPERATION, 0, 0};
}
}
@@ -464,19 +439,10 @@
}
}
- bool accumulate = false;
if (outChannels > 2) {
- // Accumulate if required
- if (accumulate) {
- for (int i = 0; i < frameCount; i++) {
- out[outChannels * i] += outFrames[FCC_2 * i];
- out[outChannels * i + 1] += outFrames[FCC_2 * i + 1];
- }
- } else {
- for (int i = 0; i < frameCount; i++) {
- out[outChannels * i] = outFrames[FCC_2 * i];
- out[outChannels * i + 1] = outFrames[FCC_2 * i + 1];
- }
+ for (int i = 0; i < frameCount; i++) {
+ out[outChannels * i] = outFrames[FCC_2 * i];
+ out[outChannels * i + 1] = outFrames[FCC_2 * i + 1];
}
if (!isAuxiliary()) {
for (int i = 0; i < frameCount; i++) {
@@ -487,29 +453,15 @@
}
}
} else {
- if (accumulate) {
- if (outChannels == FCC_1) {
- for (int i = 0; i < frameCount; i++) {
- out[i] += ((outFrames[i * FCC_2] + outFrames[i * FCC_2 + 1]) * 0.5f);
- }
- } else {
- for (int i = 0; i < frameCount * FCC_2; i++) {
- out[i] += outFrames[i];
- }
- }
+ if (outChannels == FCC_1) {
+ From2iToMono_Float(outFrames.data(), out, frameCount);
} else {
- if (outChannels == FCC_1) {
- From2iToMono_Float(outFrames.data(), out, frameCount);
- } else {
- for (int i = 0; i < frameCount * FCC_2; i++) {
- out[i] = outFrames[i];
- }
+ for (int i = 0; i < frameCount * FCC_2; i++) {
+ out[i] = outFrames[i];
}
}
}
- LOG(DEBUG) << __func__ << " done processing";
-
if (!mEnabled && mSamplesToExitCount > 0) {
// signed - unsigned will trigger integer overflow if result becomes negative.
mSamplesToExitCount -= samples;
diff --git a/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.h b/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.h
index 7d0ccff..44391f2 100644
--- a/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.h
+++ b/media/libeffects/lvm/wrapper/Reverb/aidl/ReverbContext.h
@@ -17,7 +17,6 @@
#pragma once
#include <android-base/logging.h>
-#include <android-base/thread_annotations.h>
#include <unordered_map>
#include "ReverbTypes.h"
@@ -158,10 +157,9 @@
{-400, -600, 1800, 700, -2000, 30, -1400, 60, 1000, 1000}},
{PresetReverb::Presets::PLATE, {-400, -200, 1300, 900, 0, 2, 0, 10, 1000, 750}}};
- std::mutex mMutex;
const lvm::ReverbEffectType mType;
bool mEnabled = false;
- LVREV_Handle_t mInstance GUARDED_BY(mMutex) = LVM_NULL;
+ LVREV_Handle_t mInstance = LVM_NULL;
int mRoomLevel = 0;
int mRoomHfLevel = 0;
diff --git a/media/libeffects/preprocessing/aidl/EffectPreProcessing.cpp b/media/libeffects/preprocessing/aidl/EffectPreProcessing.cpp
index 1675d97..87d267b 100644
--- a/media/libeffects/preprocessing/aidl/EffectPreProcessing.cpp
+++ b/media/libeffects/preprocessing/aidl/EffectPreProcessing.cpp
@@ -50,7 +50,6 @@
}
if (instanceSpp) {
*instanceSpp = ndk::SharedRefBase::make<EffectPreProcessing>(*uuid);
- LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
LOG(ERROR) << __func__ << " invalid input parameter!";
@@ -78,7 +77,6 @@
namespace aidl::android::hardware::audio::effect {
EffectPreProcessing::EffectPreProcessing(const AudioUuid& uuid) {
- LOG(DEBUG) << __func__ << uuid.toString();
if (uuid == getEffectImplUuidAcousticEchoCancelerSw()) {
mType = PreProcessingEffectType::ACOUSTIC_ECHO_CANCELLATION;
mDescriptor = &kAcousticEchoCancelerDesc;
@@ -102,18 +100,16 @@
EffectPreProcessing::~EffectPreProcessing() {
cleanUp();
- LOG(DEBUG) << __func__;
}
ndk::ScopedAStatus EffectPreProcessing::getDescriptor(Descriptor* _aidl_return) {
RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr");
- LOG(DEBUG) << _aidl_return->toString();
*_aidl_return = *mDescriptor;
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus EffectPreProcessing::setParameterSpecific(const Parameter::Specific& specific) {
- LOG(DEBUG) << __func__ << " specific " << specific.toString();
+ LOG(VERBOSE) << __func__ << " specific " << specific.toString();
RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext");
auto tag = specific.getTag();
diff --git a/media/libeffects/preprocessing/aidl/PreProcessingContext.cpp b/media/libeffects/preprocessing/aidl/PreProcessingContext.cpp
index 6f671f0..2d549ef 100644
--- a/media/libeffects/preprocessing/aidl/PreProcessingContext.cpp
+++ b/media/libeffects/preprocessing/aidl/PreProcessingContext.cpp
@@ -26,7 +26,6 @@
using aidl::android::media::audio::common::AudioDeviceType;
RetCode PreProcessingContext::init(const Parameter::Common& common) {
- std::lock_guard lg(mMutex);
webrtc::AudioProcessingBuilder apBuilder;
mAudioProcessingModule = apBuilder.Create();
if (mAudioProcessingModule == nullptr) {
@@ -64,7 +63,6 @@
}
RetCode PreProcessingContext::deInit() {
- std::lock_guard lg(mMutex);
mAudioProcessingModule = nullptr;
mState = PRE_PROC_STATE_UNINITIALIZED;
return RetCode::SUCCESS;
@@ -75,7 +73,6 @@
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
int typeMsk = (1 << int(mType));
- std::lock_guard lg(mMutex);
// Check if effect is already enabled.
if ((mEnabledMsk & typeMsk) == typeMsk) {
return RetCode::ERROR_ILLEGAL_PARAMETER;
@@ -110,7 +107,6 @@
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
int typeMsk = (1 << int(mType));
- std::lock_guard lg(mMutex);
// Check if effect is already disabled.
if ((mEnabledMsk & typeMsk) != typeMsk) {
return RetCode::ERROR_ILLEGAL_PARAMETER;
@@ -160,7 +156,6 @@
RetCode PreProcessingContext::setAcousticEchoCancelerEchoDelay(int echoDelayUs) {
mEchoDelayUs = echoDelayUs;
- std::lock_guard lg(mMutex);
mAudioProcessingModule->set_stream_delay_ms(mEchoDelayUs / 1000);
return RetCode::SUCCESS;
}
@@ -171,7 +166,6 @@
RetCode PreProcessingContext::setAcousticEchoCancelerMobileMode(bool mobileMode) {
mMobileMode = mobileMode;
- std::lock_guard lg(mMutex);
auto config = mAudioProcessingModule->GetConfig();
config.echo_canceller.mobile_mode = mobileMode;
mAudioProcessingModule->ApplyConfig(config);
@@ -184,7 +178,6 @@
RetCode PreProcessingContext::setAutomaticGainControlV1TargetPeakLevel(int targetPeakLevel) {
mTargetPeakLevel = targetPeakLevel;
- std::lock_guard lg(mMutex);
auto config = mAudioProcessingModule->GetConfig();
config.gain_controller1.target_level_dbfs = -(mTargetPeakLevel / 100);
mAudioProcessingModule->ApplyConfig(config);
@@ -197,7 +190,6 @@
RetCode PreProcessingContext::setAutomaticGainControlV1MaxCompressionGain(int maxCompressionGain) {
mMaxCompressionGain = maxCompressionGain;
- std::lock_guard lg(mMutex);
auto config = mAudioProcessingModule->GetConfig();
config.gain_controller1.compression_gain_db = mMaxCompressionGain / 100;
mAudioProcessingModule->ApplyConfig(config);
@@ -210,7 +202,6 @@
RetCode PreProcessingContext::setAutomaticGainControlV1EnableLimiter(bool enableLimiter) {
mEnableLimiter = enableLimiter;
- std::lock_guard lg(mMutex);
auto config = mAudioProcessingModule->GetConfig();
config.gain_controller1.enable_limiter = mEnableLimiter;
mAudioProcessingModule->ApplyConfig(config);
@@ -223,7 +214,6 @@
RetCode PreProcessingContext::setAutomaticGainControlV2DigitalGain(int gain) {
mDigitalGain = gain;
- std::lock_guard lg(mMutex);
auto config = mAudioProcessingModule->GetConfig();
config.gain_controller2.fixed_digital.gain_db = mDigitalGain;
mAudioProcessingModule->ApplyConfig(config);
@@ -256,7 +246,6 @@
RetCode PreProcessingContext::setNoiseSuppressionLevel(NoiseSuppression::Level level) {
mLevel = level;
- std::lock_guard lg(mMutex);
auto config = mAudioProcessingModule->GetConfig();
config.noise_suppression.level =
(webrtc::AudioProcessing::Config::NoiseSuppression::Level)level;
@@ -278,9 +267,6 @@
RETURN_VALUE_IF(inputFrameCount != outputFrameCount, status, "FrameCountMismatch");
RETURN_VALUE_IF(0 == getInputFrameSize(), status, "zeroFrameSize");
- LOG(DEBUG) << __func__ << " start processing";
- std::lock_guard lg(mMutex);
-
mProcessedMsk |= (1 << int(mType));
// webrtc implementation clear out was_stream_delay_set every time after ProcessStream() call
diff --git a/media/libeffects/preprocessing/aidl/PreProcessingContext.h b/media/libeffects/preprocessing/aidl/PreProcessingContext.h
index 811bacf..11a2bea 100644
--- a/media/libeffects/preprocessing/aidl/PreProcessingContext.h
+++ b/media/libeffects/preprocessing/aidl/PreProcessingContext.h
@@ -17,7 +17,6 @@
#pragma once
#include <android-base/logging.h>
-#include <android-base/thread_annotations.h>
#include <audio_processing.h>
#include <unordered_map>
@@ -37,10 +36,9 @@
PreProcessingContext(int statusDepth, const Parameter::Common& common,
const PreProcessingEffectType& type)
: EffectContext(statusDepth, common), mType(type) {
- LOG(DEBUG) << __func__ << type;
mState = PRE_PROC_STATE_UNINITIALIZED;
}
- ~PreProcessingContext() override { LOG(DEBUG) << __func__; }
+ ~PreProcessingContext() = default;
RetCode init(const Parameter::Common& common);
RetCode deInit();
@@ -85,20 +83,19 @@
static constexpr inline webrtc::AudioProcessing::Config::NoiseSuppression::Level
kNsDefaultLevel = webrtc::AudioProcessing::Config::NoiseSuppression::kModerate;
- std::mutex mMutex;
const PreProcessingEffectType mType;
PreProcEffectState mState; // current state
// handle on webRTC audio processing module (APM)
- rtc::scoped_refptr<webrtc::AudioProcessing> mAudioProcessingModule GUARDED_BY(mMutex);
+ rtc::scoped_refptr<webrtc::AudioProcessing> mAudioProcessingModule;
- int mEnabledMsk GUARDED_BY(mMutex); // bit field containing IDs of enabled pre processors
- int mProcessedMsk GUARDED_BY(mMutex); // bit field containing IDs of pre processors already
+ int mEnabledMsk; // bit field containing IDs of enabled pre processors
+ int mProcessedMsk; // bit field containing IDs of pre processors already
// processed in current round
- int mRevEnabledMsk GUARDED_BY(mMutex); // bit field containing IDs of enabled pre processors
+ int mRevEnabledMsk; // bit field containing IDs of enabled pre processors
// with reverse channel
- int mRevProcessedMsk GUARDED_BY(mMutex); // bit field containing IDs of pre processors with
- // reverse channel already processed in current round
+ int mRevProcessedMsk; // bit field containing IDs of pre processors with
+ // reverse channel already processed in current round
webrtc::StreamConfig mInputConfig; // input stream configuration
webrtc::StreamConfig mOutputConfig; // output stream configuration
diff --git a/media/libeffects/preprocessing/aidl/PreProcessingSession.h b/media/libeffects/preprocessing/aidl/PreProcessingSession.h
index 877292f..4a66e81 100644
--- a/media/libeffects/preprocessing/aidl/PreProcessingSession.h
+++ b/media/libeffects/preprocessing/aidl/PreProcessingSession.h
@@ -21,7 +21,6 @@
#include <unordered_map>
#include <android-base/logging.h>
-#include <android-base/thread_annotations.h>
#include "PreProcessingContext.h"
#include "PreProcessingTypes.h"
@@ -67,7 +66,6 @@
const Parameter::Common& common) {
int sessionId = common.session;
LOG(DEBUG) << __func__ << type << " with sessionId " << sessionId;
- std::lock_guard lg(mMutex);
if (mSessionMap.count(sessionId) == 0 && mSessionMap.size() >= MAX_PRE_PROC_SESSIONS) {
LOG(ERROR) << __func__ << " exceed max bundle session";
return nullptr;
@@ -95,7 +93,6 @@
void releaseSession(const PreProcessingEffectType& type, int sessionId) {
LOG(DEBUG) << __func__ << type << " sessionId " << sessionId;
- std::lock_guard lg(mMutex);
if (mSessionMap.count(sessionId)) {
auto& list = mSessionMap[sessionId];
if (!findPreProcessingTypeInList(list, type, true /* remove */)) {
@@ -109,11 +106,9 @@
}
private:
- // Lock for mSessionMap access.
- std::mutex mMutex;
// Max session number supported.
static constexpr int MAX_PRE_PROC_SESSIONS = 8;
std::unordered_map<int /* session ID */, std::vector<std::shared_ptr<PreProcessingContext>>>
- mSessionMap GUARDED_BY(mMutex);
+ mSessionMap;
};
} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libeffects/visualizer/aidl/Visualizer.cpp b/media/libeffects/visualizer/aidl/Visualizer.cpp
index 9b1bac6..9c2b71e 100644
--- a/media/libeffects/visualizer/aidl/Visualizer.cpp
+++ b/media/libeffects/visualizer/aidl/Visualizer.cpp
@@ -37,7 +37,6 @@
}
if (instanceSpp) {
*instanceSpp = ndk::SharedRefBase::make<VisualizerImpl>();
- LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
LOG(ERROR) << __func__ << " invalid input parameter!";
diff --git a/media/libeffects/visualizer/aidl/Visualizer.h b/media/libeffects/visualizer/aidl/Visualizer.h
index b48c85e..3180972 100644
--- a/media/libeffects/visualizer/aidl/Visualizer.h
+++ b/media/libeffects/visualizer/aidl/Visualizer.h
@@ -29,11 +29,8 @@
static const std::string kEffectName;
static const Capability kCapability;
static const Descriptor kDescriptor;
- VisualizerImpl() { LOG(DEBUG) << __func__; }
- ~VisualizerImpl() {
- cleanUp();
- LOG(DEBUG) << __func__;
- }
+ VisualizerImpl() = default;
+ ~VisualizerImpl() { cleanUp(); }
ndk::ScopedAStatus commandImpl(CommandId command) REQUIRES(mImplMutex) override;
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
diff --git a/media/libeffects/visualizer/aidl/VisualizerContext.cpp b/media/libeffects/visualizer/aidl/VisualizerContext.cpp
index c763b1a..1e08674 100644
--- a/media/libeffects/visualizer/aidl/VisualizerContext.cpp
+++ b/media/libeffects/visualizer/aidl/VisualizerContext.cpp
@@ -38,14 +38,10 @@
}
VisualizerContext::~VisualizerContext() {
- std::lock_guard lg(mMutex);
- LOG(DEBUG) << __func__;
mState = State::UNINITIALIZED;
}
RetCode VisualizerContext::initParams(const Parameter::Common& common) {
- std::lock_guard lg(mMutex);
- LOG(DEBUG) << __func__;
if (common.input != common.output) {
LOG(ERROR) << __func__ << " mismatch input: " << common.input.toString()
<< " and output: " << common.output.toString();
@@ -66,7 +62,6 @@
}
RetCode VisualizerContext::enable() {
- std::lock_guard lg(mMutex);
if (mState != State::INITIALIZED) {
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
@@ -75,7 +70,6 @@
}
RetCode VisualizerContext::disable() {
- std::lock_guard lg(mMutex);
if (mState != State::ACTIVE) {
return RetCode::ERROR_EFFECT_LIB_ERROR;
}
@@ -84,48 +78,39 @@
}
void VisualizerContext::reset() {
- std::lock_guard lg(mMutex);
std::fill(mCaptureBuf.begin(), mCaptureBuf.end(), 0x80);
}
RetCode VisualizerContext::setCaptureSamples(int samples) {
- std::lock_guard lg(mMutex);
mCaptureSamples = samples;
return RetCode::SUCCESS;
}
int32_t VisualizerContext::getCaptureSamples() {
- std::lock_guard lg(mMutex);
return mCaptureSamples;
}
RetCode VisualizerContext::setMeasurementMode(Visualizer::MeasurementMode mode) {
- std::lock_guard lg(mMutex);
mMeasurementMode = mode;
return RetCode::SUCCESS;
}
Visualizer::MeasurementMode VisualizerContext::getMeasurementMode() {
- std::lock_guard lg(mMutex);
return mMeasurementMode;
}
RetCode VisualizerContext::setScalingMode(Visualizer::ScalingMode mode) {
- std::lock_guard lg(mMutex);
mScalingMode = mode;
return RetCode::SUCCESS;
}
Visualizer::ScalingMode VisualizerContext::getScalingMode() {
- std::lock_guard lg(mMutex);
return mScalingMode;
}
RetCode VisualizerContext::setDownstreamLatency(int latency) {
- std::lock_guard lg(mMutex);
mDownstreamLatency = latency;
return RetCode::SUCCESS;
}
int VisualizerContext::getDownstreamLatency() {
- std::lock_guard lg(mMutex);
return mDownstreamLatency;
}
@@ -152,7 +137,6 @@
uint8_t nbValidMeasurements = 0;
{
- std::lock_guard lg(mMutex);
// reset measurements if last measurement was too long ago (which implies stored
// measurements aren't relevant anymore and shouldn't bias the new one)
const uint32_t delayMs = getDeltaTimeMsFromUpdatedTime_l();
@@ -185,13 +169,12 @@
// convert from I16 sample values to mB and write results
measure.rms = (rms < 0.000016f) ? -9600 : (int32_t)(2000 * log10(rms / 32767.0f));
measure.peak = (peakU16 == 0) ? -9600 : (int32_t)(2000 * log10(peakU16 / 32767.0f));
- LOG(INFO) << __func__ << " peak " << peakU16 << " (" << measure.peak << "mB), rms " << rms
- << " (" << measure.rms << "mB)";
+ LOG(VERBOSE) << __func__ << " peak " << peakU16 << " (" << measure.peak << "mB), rms " << rms
+ << " (" << measure.rms << "mB)";
return measure;
}
std::vector<uint8_t> VisualizerContext::capture() {
- std::lock_guard lg(mMutex);
uint32_t captureSamples = mCaptureSamples;
std::vector<uint8_t> result(captureSamples, 0x80);
// cts android.media.audio.cts.VisualizerTest expecting silence data when effect not running
@@ -205,7 +188,6 @@
// clear the capture buffer to return silence
if ((mLastCaptureIdx == mCaptureIdx) && (mBufferUpdateTime.tv_sec != 0) &&
(deltaMs > kMaxStallTimeMs)) {
- LOG(INFO) << __func__ << " capture going to idle";
mBufferUpdateTime.tv_sec = 0;
return result;
}
@@ -247,10 +229,8 @@
IEffect::Status result = {STATUS_NOT_ENOUGH_DATA, 0, 0};
RETURN_VALUE_IF(in == nullptr || out == nullptr || samples == 0, result, "dataBufferError");
- std::lock_guard lg(mMutex);
result.status = STATUS_INVALID_OPERATION;
RETURN_VALUE_IF(mState != State::ACTIVE, result, "stateNotActive");
- LOG(DEBUG) << __func__ << " in " << in << " out " << out << " sample " << samples;
// perform measurements if needed
if (mMeasurementMode == Visualizer::MeasurementMode::PEAK_RMS) {
// find the peak and RMS squared for the new buffer
diff --git a/media/libeffects/visualizer/aidl/VisualizerContext.h b/media/libeffects/visualizer/aidl/VisualizerContext.h
index b03e038..9715e20 100644
--- a/media/libeffects/visualizer/aidl/VisualizerContext.h
+++ b/media/libeffects/visualizer/aidl/VisualizerContext.h
@@ -16,7 +16,6 @@
#pragma once
-#include <android-base/thread_annotations.h>
#include <audio_effects/effect_dynamicsprocessing.h>
#include <system/audio_effects/effect_visualizer.h>
@@ -79,28 +78,26 @@
// note: buffer index is stored in uint8_t
static const uint32_t kMeasurementWindowMaxSizeInBuffers = 25;
- // serialize process() and parameter setting
- std::mutex mMutex;
- Parameter::Common mCommon GUARDED_BY(mMutex);
- State mState GUARDED_BY(mMutex) = State::UNINITIALIZED;
- uint32_t mCaptureIdx GUARDED_BY(mMutex) = 0;
- uint32_t mLastCaptureIdx GUARDED_BY(mMutex) = 0;
- Visualizer::ScalingMode mScalingMode GUARDED_BY(mMutex) = Visualizer::ScalingMode::NORMALIZED;
- struct timespec mBufferUpdateTime GUARDED_BY(mMutex);
+ Parameter::Common mCommon;
+ State mState = State::UNINITIALIZED;
+ uint32_t mCaptureIdx = 0;
+ uint32_t mLastCaptureIdx = 0;
+ Visualizer::ScalingMode mScalingMode = Visualizer::ScalingMode::NORMALIZED;
+ struct timespec mBufferUpdateTime;
// capture buf with 8 bits mono PCM samples
- std::array<uint8_t, kMaxCaptureBufSize> mCaptureBuf GUARDED_BY(mMutex);
- uint32_t mDownstreamLatency GUARDED_BY(mMutex) = 0;
- int32_t mCaptureSamples GUARDED_BY(mMutex) = kMaxCaptureBufSize;
+ std::array<uint8_t, kMaxCaptureBufSize> mCaptureBuf;
+ uint32_t mDownstreamLatency = 0;
+ int32_t mCaptureSamples = kMaxCaptureBufSize;
// to avoid recomputing it every time a buffer is processed
- uint8_t mChannelCount GUARDED_BY(mMutex) = 0;
- Visualizer::MeasurementMode mMeasurementMode GUARDED_BY(mMutex) =
+ uint8_t mChannelCount = 0;
+ Visualizer::MeasurementMode mMeasurementMode =
Visualizer::MeasurementMode::NONE;
uint8_t mMeasurementWindowSizeInBuffers = kMeasurementWindowMaxSizeInBuffers;
- uint8_t mMeasurementBufferIdx GUARDED_BY(mMutex) = 0;
+ uint8_t mMeasurementBufferIdx = 0;
std::array<BufferStats, kMeasurementWindowMaxSizeInBuffers> mPastMeasurements;
void init_params();
- uint32_t getDeltaTimeMsFromUpdatedTime_l() REQUIRES(mMutex);
+ uint32_t getDeltaTimeMsFromUpdatedTime_l();
};
} // namespace aidl::android::hardware::audio::effect
diff --git a/media/libstagefright/webm/Android.bp b/media/libstagefright/webm/Android.bp
index 6ed3e0e..723131d 100644
--- a/media/libstagefright/webm/Android.bp
+++ b/media/libstagefright/webm/Android.bp
@@ -10,8 +10,6 @@
cc_library_static {
name: "libstagefright_webm",
- cppflags: ["-D__STDINT_LIMITS"],
-
cflags: [
"-Werror",
"-Wall",
diff --git a/media/utils/ServiceUtilities.cpp b/media/utils/ServiceUtilities.cpp
index 2946398..b85d9de 100644
--- a/media/utils/ServiceUtilities.cpp
+++ b/media/utils/ServiceUtilities.cpp
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+//#define LOG_NDEBUG 0
#define LOG_TAG "ServiceUtilities"
#include <audio_utils/clock.h>
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index c5424a2..97c80a8 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -2551,6 +2551,7 @@
bool mm;
if (OK == dev->getMasterMute(&mm)) {
mMasterMute = mm;
+ ALOGI_IF(mMasterMute, "%s: applying mute from HAL %s", __func__, name);
}
}
diff --git a/services/audioflinger/Effects.cpp b/services/audioflinger/Effects.cpp
index 73a89e5..ae55329 100644
--- a/services/audioflinger/Effects.cpp
+++ b/services/audioflinger/Effects.cpp
@@ -31,6 +31,7 @@
#include <media/AudioContainers.h>
#include <media/AudioDeviceTypeAddr.h>
#include <media/AudioEffect.h>
+#include <media/EffectClientAsyncProxy.h>
#include <media/ShmemCompat.h>
#include <media/TypeConverter.h>
#include <media/audiohal/EffectHalInterface.h>
@@ -1691,7 +1692,8 @@
const sp<media::IEffectClient>& effectClient,
int32_t priority, bool notifyFramesProcessed)
: BnEffect(),
- mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
+ mEffect(effect), mEffectClient(media::EffectClientAsyncProxy::makeIfNeeded(effectClient)),
+ mClient(client), mCblk(nullptr),
mPriority(priority), mHasControl(false), mEnabled(false), mDisconnected(false),
mNotifyFramesProcessed(notifyFramesProcessed)
{
diff --git a/services/audioflinger/IAfThread.h b/services/audioflinger/IAfThread.h
index 7084be9..46a67e8 100644
--- a/services/audioflinger/IAfThread.h
+++ b/services/audioflinger/IAfThread.h
@@ -386,6 +386,12 @@
const effect_uuid_t* type, bool suspend, audio_session_t sessionId)
REQUIRES(mutex()) = 0;
+ // Wait while the Thread is busy. This is done to ensure that
+ // the Thread is not busy releasing the Tracks, during which the Thread mutex
+ // may be temporarily unlocked. Some Track methods will use this method to
+ // avoid races.
+ virtual void waitWhileThreadBusy_l(audio_utils::unique_lock& ul)
+ REQUIRES(mutex()) = 0;
// Dynamic cast to derived interface
virtual sp<IAfDirectOutputThread> asIAfDirectOutputThread() { return nullptr; }
virtual sp<IAfDuplicatingThread> asIAfDuplicatingThread() { return nullptr; }
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index d61621a..bba3d86 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -721,8 +721,9 @@
{
audio_utils::unique_lock _l(event->mutex());
while (event->mWaitStatus) {
- if (event->mCondition.wait_for(_l, std::chrono::nanoseconds(kConfigEventTimeoutNs))
- == std::cv_status::timeout) {
+ if (event->mCondition.wait_for(
+ _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
+ == std::cv_status::timeout) {
event->mStatus = TIMED_OUT;
event->mWaitStatus = false;
}
@@ -2849,6 +2850,8 @@
// effectively get the latency it requested.
if (track->isExternalTrack()) {
IAfTrackBase::track_state state = track->state();
+ // Because the track is not on the ActiveTracks,
+ // at this point, only the TrackHandle will be adding the track.
mutex().unlock();
status = AudioSystem::startOutput(track->portId());
mutex().lock();
@@ -2929,7 +2932,12 @@
track->setResetDone(false);
track->resetPresentationComplete();
+
+ // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
+ // all key changes are complete. It is possible that the threadLoop will begin
+ // processing the added track immediately after the ThreadBase mutex is released.
mActiveTracks.add(track);
+
if (chain != 0) {
ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
track->sessionId());
@@ -4704,8 +4712,12 @@
void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
{
+ if (tracksToRemove.empty()) return;
+
+ // Block all incoming TrackHandle requests until we are finished with the release.
+ setThreadBusy_l(true);
+
for (const auto& track : tracksToRemove) {
- mActiveTracks.remove(track);
ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
if (chain != 0) {
@@ -4713,17 +4725,16 @@
__func__, track->id(), chain.get(), track->sessionId());
chain->decActiveTrackCnt();
}
+
// If an external client track, inform APM we're no longer active, and remove if needed.
- // We do this under lock so that the state is consistent if the Track is destroyed.
+ // Since the track is active, we do it here instead of TrackBase::destroy().
if (track->isExternalTrack()) {
+ mutex().unlock();
AudioSystem::stopOutput(track->portId());
if (track->isTerminated()) {
AudioSystem::releaseOutput(track->portId());
}
- }
- if (track->isTerminated()) {
- // remove from our tracks vector
- removeTrack_l(track);
+ mutex().lock();
}
if (mHapticChannelCount > 0 &&
((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
@@ -4740,7 +4751,24 @@
chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
}
}
+
+ // Under lock, the track is removed from the active tracks list.
+ //
+ // Once the track is no longer active, the TrackHandle may directly
+ // modify it as the threadLoop() is no longer responsible for its maintenance.
+ // Do not modify the track from threadLoop after the mutex is unlocked
+ // if it is not active.
+ mActiveTracks.remove(track);
+
+ if (track->isTerminated()) {
+ // remove from our tracks vector
+ removeTrack_l(track);
+ }
}
+
+ // Allow incoming TrackHandle requests. We still hold the mutex,
+ // so pending TrackHandle requests will occur after we unlock it.
+ setThreadBusy_l(false);
}
status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
@@ -11033,7 +11061,7 @@
char *endptr;
unsigned long ul = strtoul(value, &endptr, 0);
if (*endptr == '\0' && ul != 0) {
- ALOGD("Silence is golden");
+ ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
// The setprop command will not allow a property to be changed after
// the first time it is set, so we don't have to worry about un-muting.
setMasterMute_l(true);
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index 21134a2..ddf0669 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -599,6 +599,35 @@
// check if some effects must be suspended when an effect chain is added
void checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex());
+ /**
+ * waitWhileThreadBusy_l() serves as a mutex gate, which does not allow
+ * progress beyond the method while the PlaybackThread is busy (see setThreadBusy_l()).
+ * During the wait, the ThreadBase_Mutex is temporarily unlocked.
+ *
+ * This implementation uses a condition variable. Alternative methods to gate
+ * the thread may use a second mutex (i.e. entry based on scoped_lock(mutex, gating_mutex)),
+ * but those have less flexibility and more lock order issues.
+ *
+ * Current usage by Track::destroy(), Track::start(), Track::stop(), Track::pause(),
+ * and Track::flush() block this way, and the primary caller is through TrackHandle
+ * with no other mutexes held.
+ *
+ * Special tracks like PatchTrack and OutputTrack may also hold the another thread's
+ * ThreadBase_Mutex during this time. No other mutex is held.
+ */
+
+ void waitWhileThreadBusy_l(audio_utils::unique_lock& ul) final REQUIRES(mutex()) {
+ // the wait returns immediately if the predicate is satisfied.
+ mThreadBusyCv.wait(ul, [&]{ return mThreadBusy == false;});
+ }
+
+ void setThreadBusy_l(bool busy) REQUIRES(mutex()) {
+ if (busy == mThreadBusy) return;
+ mThreadBusy = busy;
+ if (busy == true) return; // no need to wake threads if we become busy.
+ mThreadBusyCv.notify_all();
+ }
+
// sends the metadata of the active tracks to the HAL
struct MetadataUpdate {
std::vector<playback_track_metadata_v7_t> playbackMetadataUpdate;
@@ -641,6 +670,13 @@
ThreadMetrics mThreadMetrics;
const bool mIsOut;
+ // mThreadBusy is checked under the ThreadBase_Mutex to ensure that
+ // TrackHandle operations do not proceed while the ThreadBase is busy
+ // with the track. mThreadBusy is only true if the track is active.
+ //
+ bool mThreadBusy = false; // GUARDED_BY(ThreadBase_Mutex) but read in lambda.
+ audio_utils::condition_variable mThreadBusyCv;
+
// updated by PlaybackThread::readOutputParameters_l() or
// RecordThread::readInputParameters_l()
uint32_t mSampleRate;
@@ -839,7 +875,7 @@
SimpleLog mLocalLog; // locked internally
-private:
+ private:
void dumpBase_l(int fd, const Vector<String16>& args) REQUIRES(mutex());
void dumpEffectChains_l(int fd, const Vector<String16>& args) REQUIRES(mutex());
};
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index f18e69b..77abaf6 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -890,12 +890,17 @@
bool wasActive = false;
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- audio_utils::lock_guard _l(thread->mutex());
+ audio_utils::unique_lock ul(thread->mutex());
+ thread->waitWhileThreadBusy_l(ul);
+
auto* const playbackThread = thread->asIAfPlaybackThread().get();
wasActive = playbackThread->destroyTrack_l(this);
forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->destroy(); });
}
if (isExternalTrack() && !wasActive) {
+ // If the track is not active, the TrackHandle is responsible for
+ // releasing the port id, not the ThreadBase::threadLoop().
+ // At this point, there is no concurrency issue as the track is going away.
AudioSystem::releaseOutput(mPortId);
}
}
@@ -1187,7 +1192,9 @@
return PERMISSION_DENIED;
}
}
- audio_utils::lock_guard _lth(thread->mutex());
+ audio_utils::unique_lock ul(thread->mutex());
+ thread->waitWhileThreadBusy_l(ul);
+
track_state state = mState;
// here the track could be either new, or restarted
// in both cases "unstop" the track
@@ -1312,7 +1319,9 @@
ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- audio_utils::lock_guard _l(thread->mutex());
+ audio_utils::unique_lock ul(thread->mutex());
+ thread->waitWhileThreadBusy_l(ul);
+
track_state state = mState;
if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
// If the track is not active (PAUSED and buffers full), flush buffers
@@ -1347,7 +1356,9 @@
ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- audio_utils::lock_guard _l(thread->mutex());
+ audio_utils::unique_lock ul(thread->mutex());
+ thread->waitWhileThreadBusy_l(ul);
+
auto* const playbackThread = thread->asIAfPlaybackThread().get();
switch (mState) {
case STOPPING_1:
@@ -1384,7 +1395,9 @@
ALOGV("%s(%d)", __func__, mId);
const sp<IAfThreadBase> thread = mThread.promote();
if (thread != 0) {
- audio_utils::lock_guard _l(thread->mutex());
+ audio_utils::unique_lock ul(thread->mutex());
+ thread->waitWhileThreadBusy_l(ul);
+
auto* const playbackThread = thread->asIAfPlaybackThread().get();
// Flush the ring buffer now if the track is not active in the PlaybackThread.
@@ -1661,7 +1674,7 @@
if (result == OK) {
ALOGI("%s(%d): processed mute state for port ID %d from %d to %d", __func__, id(), mPortId,
- int(muteState), int(mMuteState));
+ static_cast<int>(mMuteState), static_cast<int>(muteState));
mMuteState = muteState;
} else {
ALOGW("%s(%d): cannot process mute state for port ID %d, status error %d", __func__, id(),
@@ -3541,6 +3554,8 @@
}
if (result == OK) {
+ ALOGI("%s(%d): processed mute state for port ID %d from %d to %d", __func__, id(), mPortId,
+ static_cast<int>(mMuteState), static_cast<int>(muteState));
mMuteState = muteState;
} else {
ALOGW("%s(%d): cannot process mute state for port ID %d, status error %d",
diff --git a/services/audioflinger/afutils/NBAIO_Tee.cpp b/services/audioflinger/afutils/NBAIO_Tee.cpp
index 86fb128..cdc8e95 100644
--- a/services/audioflinger/afutils/NBAIO_Tee.cpp
+++ b/services/audioflinger/afutils/NBAIO_Tee.cpp
@@ -514,6 +514,12 @@
return NO_ERROR; // return full path
}
+/* static */
+NBAIO_Tee::RunningTees& NBAIO_Tee::getRunningTees() {
+ [[clang::no_destroy]] static RunningTees runningTees;
+ return runningTees;
+}
+
} // namespace android
#endif // TEE_SINK
diff --git a/services/audioflinger/afutils/NBAIO_Tee.h b/services/audioflinger/afutils/NBAIO_Tee.h
index a5c544e..5ab1949 100644
--- a/services/audioflinger/afutils/NBAIO_Tee.h
+++ b/services/audioflinger/afutils/NBAIO_Tee.h
@@ -310,10 +310,7 @@
};
// singleton
- static RunningTees &getRunningTees() {
- static RunningTees runningTees;
- return runningTees;
- }
+ static RunningTees& getRunningTees();
// The NBAIO TeeImpl may have lifetime longer than NBAIO_Tee if
// RunningTees::dump() is being called simultaneous to ~NBAIO_Tee().
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h
index 13b70e5..c8b2962 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h
@@ -16,7 +16,6 @@
#pragma once
-#define __STDC_LIMIT_MACROS
#include <inttypes.h>
#include <sys/types.h>
diff --git a/services/audiopolicy/service/AudioPolicyEffects.cpp b/services/audiopolicy/service/AudioPolicyEffects.cpp
index 85b7ad9..d67ddb6 100644
--- a/services/audiopolicy/service/AudioPolicyEffects.cpp
+++ b/services/audiopolicy/service/AudioPolicyEffects.cpp
@@ -42,55 +42,25 @@
// ----------------------------------------------------------------------------
AudioPolicyEffects::AudioPolicyEffects(const sp<EffectsFactoryHalInterface>& effectsFactoryHal) {
+ // Note: clang thread-safety permits the ctor to call guarded _l methods without
+ // acquiring the associated mutex capability as standard practice is to assume
+ // single threaded construction and destruction.
+
// load xml config with effectsFactoryHal
- status_t loadResult = loadAudioEffectConfig(effectsFactoryHal);
+ status_t loadResult = loadAudioEffectConfig_ll(effectsFactoryHal);
if (loadResult < 0) {
ALOGW("Failed to query effect configuration, fallback to load .conf");
// load automatic audio effect modules
if (access(AUDIO_EFFECT_VENDOR_CONFIG_FILE, R_OK) == 0) {
- loadAudioEffectConfigLegacy(AUDIO_EFFECT_VENDOR_CONFIG_FILE);
+ loadAudioEffectConfigLegacy_l(AUDIO_EFFECT_VENDOR_CONFIG_FILE);
} else if (access(AUDIO_EFFECT_DEFAULT_CONFIG_FILE, R_OK) == 0) {
- loadAudioEffectConfigLegacy(AUDIO_EFFECT_DEFAULT_CONFIG_FILE);
+ loadAudioEffectConfigLegacy_l(AUDIO_EFFECT_DEFAULT_CONFIG_FILE);
}
} else if (loadResult > 0) {
ALOGE("Effect config is partially invalid, skipped %d elements", loadResult);
}
}
-void AudioPolicyEffects::setDefaultDeviceEffects() {
- mDefaultDeviceEffectFuture = std::async(
- std::launch::async, &AudioPolicyEffects::initDefaultDeviceEffects, this);
-}
-
-AudioPolicyEffects::~AudioPolicyEffects()
-{
- size_t i = 0;
- // release audio input processing resources
- for (i = 0; i < mInputSources.size(); i++) {
- delete mInputSources.valueAt(i);
- }
- mInputSources.clear();
-
- for (i = 0; i < mInputSessions.size(); i++) {
- mInputSessions.valueAt(i)->mEffects.clear();
- delete mInputSessions.valueAt(i);
- }
- mInputSessions.clear();
-
- // release audio output processing resources
- for (i = 0; i < mOutputStreams.size(); i++) {
- delete mOutputStreams.valueAt(i);
- }
- mOutputStreams.clear();
-
- for (i = 0; i < mOutputSessions.size(); i++) {
- mOutputSessions.valueAt(i)->mEffects.clear();
- delete mOutputSessions.valueAt(i);
- }
- mOutputSessions.clear();
-}
-
-
status_t AudioPolicyEffects::addInputEffects(audio_io_handle_t input,
audio_source_t inputSource,
audio_session_t audioSession)
@@ -101,48 +71,43 @@
audio_source_t aliasSource = (inputSource == AUDIO_SOURCE_HOTWORD) ?
AUDIO_SOURCE_VOICE_RECOGNITION : inputSource;
- Mutex::Autolock _l(mLock);
- ssize_t index = mInputSources.indexOfKey(aliasSource);
- if (index < 0) {
+ audio_utils::lock_guard _l(mMutex);
+ auto sourceIt = mInputSources.find(aliasSource);
+ if (sourceIt == mInputSources.end()) {
ALOGV("addInputEffects(): no processing needs to be attached to this source");
return status;
}
- ssize_t idx = mInputSessions.indexOfKey(audioSession);
- EffectVector *sessionDesc;
- if (idx < 0) {
- sessionDesc = new EffectVector(audioSession);
- mInputSessions.add(audioSession, sessionDesc);
- } else {
- // EffectVector is existing and we just need to increase ref count
- sessionDesc = mInputSessions.valueAt(idx);
+ std::shared_ptr<EffectVector>& sessionDesc = mInputSessions[audioSession];
+ if (sessionDesc == nullptr) {
+ sessionDesc = std::make_shared<EffectVector>(audioSession);
}
sessionDesc->mRefCount++;
ALOGV("addInputEffects(): input: %d, refCount: %d", input, sessionDesc->mRefCount);
if (sessionDesc->mRefCount == 1) {
int64_t token = IPCThreadState::self()->clearCallingIdentity();
- Vector <EffectDesc *> effects = mInputSources.valueAt(index)->mEffects;
- for (size_t i = 0; i < effects.size(); i++) {
- EffectDesc *effect = effects[i];
+ const std::shared_ptr<EffectDescVector>& effects = sourceIt->second;
+ for (const std::shared_ptr<EffectDesc>& effect : *effects) {
AttributionSourceState attributionSource;
attributionSource.packageName = "android";
attributionSource.token = sp<BBinder>::make();
- sp<AudioEffect> fx = new AudioEffect(attributionSource);
+ auto fx = sp<AudioEffect>::make(attributionSource);
fx->set(nullptr /*type */, &effect->mUuid, -1 /* priority */, nullptr /* callback */,
audioSession, input);
status_t status = fx->initCheck();
if (status != NO_ERROR && status != ALREADY_EXISTS) {
ALOGW("addInputEffects(): failed to create Fx %s on source %d",
- effect->mName, (int32_t)aliasSource);
+ effect->mName.c_str(), (int32_t)aliasSource);
// fx goes out of scope and strong ref on AudioEffect is released
continue;
}
for (size_t j = 0; j < effect->mParams.size(); j++) {
- fx->setParameter(effect->mParams[j]);
+ // const_cast here due to API.
+ fx->setParameter(const_cast<effect_param_t*>(effect->mParams[j].get()));
}
ALOGV("addInputEffects(): added Fx %s on source: %d",
- effect->mName, (int32_t)aliasSource);
- sessionDesc->mEffects.add(fx);
+ effect->mName.c_str(), (int32_t)aliasSource);
+ sessionDesc->mEffects.push_back(std::move(fx));
}
sessionDesc->setProcessorEnabled(true);
IPCThreadState::self()->restoreCallingIdentity(token);
@@ -156,18 +121,17 @@
{
status_t status = NO_ERROR;
- Mutex::Autolock _l(mLock);
- ssize_t index = mInputSessions.indexOfKey(audioSession);
- if (index < 0) {
+ audio_utils::lock_guard _l(mMutex);
+ auto it = mInputSessions.find(audioSession);
+ if (it == mInputSessions.end()) {
return status;
}
- EffectVector *sessionDesc = mInputSessions.valueAt(index);
+ std::shared_ptr<EffectVector> sessionDesc = it->second;
sessionDesc->mRefCount--;
ALOGV("releaseInputEffects(): input: %d, refCount: %d", input, sessionDesc->mRefCount);
if (sessionDesc->mRefCount == 0) {
sessionDesc->setProcessorEnabled(false);
- delete sessionDesc;
- mInputSessions.removeItemsAt(index);
+ mInputSessions.erase(it);
ALOGV("releaseInputEffects(): all effects released");
}
return status;
@@ -179,24 +143,16 @@
{
status_t status = NO_ERROR;
- Mutex::Autolock _l(mLock);
- size_t index;
- for (index = 0; index < mInputSessions.size(); index++) {
- if (mInputSessions.valueAt(index)->mSessionId == audioSession) {
- break;
- }
- }
- if (index == mInputSessions.size()) {
+ audio_utils::lock_guard _l(mMutex);
+ auto it = mInputSessions.find(audioSession);
+ if (it == mInputSessions.end()) {
*count = 0;
return BAD_VALUE;
}
- Vector< sp<AudioEffect> > effects = mInputSessions.valueAt(index)->mEffects;
-
- for (size_t i = 0; i < effects.size(); i++) {
- effect_descriptor_t desc = effects[i]->descriptor();
- if (i < *count) {
- descriptors[i] = desc;
- }
+ const std::vector<sp<AudioEffect>>& effects = it->second->mEffects;
+ const size_t copysize = std::min(effects.size(), (size_t)*count);
+ for (size_t i = 0; i < copysize; i++) {
+ descriptors[i] = effects[i]->descriptor();
}
if (effects.size() > *count) {
status = NO_MEMORY;
@@ -212,24 +168,16 @@
{
status_t status = NO_ERROR;
- Mutex::Autolock _l(mLock);
- size_t index;
- for (index = 0; index < mOutputSessions.size(); index++) {
- if (mOutputSessions.valueAt(index)->mSessionId == audioSession) {
- break;
- }
- }
- if (index == mOutputSessions.size()) {
+ audio_utils::lock_guard _l(mMutex);
+ auto it = mOutputSessions.find(audioSession);
+ if (it == mOutputSessions.end()) {
*count = 0;
return BAD_VALUE;
}
- Vector< sp<AudioEffect> > effects = mOutputSessions.valueAt(index)->mEffects;
-
- for (size_t i = 0; i < effects.size(); i++) {
- effect_descriptor_t desc = effects[i]->descriptor();
- if (i < *count) {
- descriptors[i] = desc;
- }
+ const std::vector<sp<AudioEffect>>& effects = it->second->mEffects;
+ const size_t copysize = std::min(effects.size(), (size_t)*count);
+ for (size_t i = 0; i < copysize; i++) {
+ descriptors[i] = effects[i]->descriptor();
}
if (effects.size() > *count) {
status = NO_MEMORY;
@@ -245,27 +193,22 @@
{
status_t status = NO_ERROR;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
// create audio processors according to stream
// FIXME: should we have specific post processing settings for internal streams?
// default to media for now.
if (stream >= AUDIO_STREAM_PUBLIC_CNT) {
stream = AUDIO_STREAM_MUSIC;
}
- ssize_t index = mOutputStreams.indexOfKey(stream);
- if (index < 0) {
+ auto it = mOutputStreams.find(stream);
+ if (it == mOutputStreams.end()) {
ALOGV("addOutputSessionEffects(): no output processing needed for this stream");
return NO_ERROR;
}
- ssize_t idx = mOutputSessions.indexOfKey(audioSession);
- EffectVector *procDesc;
- if (idx < 0) {
- procDesc = new EffectVector(audioSession);
- mOutputSessions.add(audioSession, procDesc);
- } else {
- // EffectVector is existing and we just need to increase ref count
- procDesc = mOutputSessions.valueAt(idx);
+ std::shared_ptr<EffectVector>& procDesc = mOutputSessions[audioSession];
+ if (procDesc == nullptr) {
+ procDesc = std::make_shared<EffectVector>(audioSession);
}
procDesc->mRefCount++;
@@ -274,25 +217,24 @@
if (procDesc->mRefCount == 1) {
// make sure effects are associated to audio server even if we are executing a binder call
int64_t token = IPCThreadState::self()->clearCallingIdentity();
- Vector <EffectDesc *> effects = mOutputStreams.valueAt(index)->mEffects;
- for (size_t i = 0; i < effects.size(); i++) {
- EffectDesc *effect = effects[i];
+ const std::shared_ptr<EffectDescVector>& effects = it->second;
+ for (const std::shared_ptr<EffectDesc>& effect : *effects) {
AttributionSourceState attributionSource;
attributionSource.packageName = "android";
attributionSource.token = sp<BBinder>::make();
- sp<AudioEffect> fx = new AudioEffect(attributionSource);
+ auto fx = sp<AudioEffect>::make(attributionSource);
fx->set(nullptr /* type */, &effect->mUuid, 0 /* priority */, nullptr /* callback */,
audioSession, output);
status_t status = fx->initCheck();
if (status != NO_ERROR && status != ALREADY_EXISTS) {
ALOGE("addOutputSessionEffects(): failed to create Fx %s on session %d",
- effect->mName, audioSession);
+ effect->mName.c_str(), audioSession);
// fx goes out of scope and strong ref on AudioEffect is released
continue;
}
ALOGV("addOutputSessionEffects(): added Fx %s on session: %d for stream: %d",
- effect->mName, audioSession, (int32_t)stream);
- procDesc->mEffects.add(fx);
+ effect->mName.c_str(), audioSession, (int32_t)stream);
+ procDesc->mEffects.push_back(std::move(fx));
}
procDesc->setProcessorEnabled(true);
@@ -305,30 +247,28 @@
audio_stream_type_t stream,
audio_session_t audioSession)
{
- status_t status = NO_ERROR;
(void) output; // argument not used for now
(void) stream; // argument not used for now
- Mutex::Autolock _l(mLock);
- ssize_t index = mOutputSessions.indexOfKey(audioSession);
- if (index < 0) {
+ audio_utils::lock_guard _l(mMutex);
+ auto it = mOutputSessions.find(audioSession);
+ if (it == mOutputSessions.end()) {
ALOGV("releaseOutputSessionEffects: no output processing was attached to this stream");
return NO_ERROR;
}
- EffectVector *procDesc = mOutputSessions.valueAt(index);
+ std::shared_ptr<EffectVector> procDesc = it->second;
procDesc->mRefCount--;
ALOGV("releaseOutputSessionEffects(): session: %d, refCount: %d",
audioSession, procDesc->mRefCount);
if (procDesc->mRefCount == 0) {
procDesc->setProcessorEnabled(false);
procDesc->mEffects.clear();
- delete procDesc;
- mOutputSessions.removeItemsAt(index);
+ mOutputSessions.erase(it);
ALOGV("releaseOutputSessionEffects(): output processing released from session: %d",
audioSession);
}
- return status;
+ return NO_ERROR;
}
status_t AudioPolicyEffects::addSourceDefaultEffect(const effect_uuid_t *type,
@@ -370,17 +310,12 @@
return BAD_VALUE;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
// Find the EffectDescVector for the given source type, or create a new one if necessary.
- ssize_t index = mInputSources.indexOfKey(source);
- EffectDescVector *desc = NULL;
- if (index < 0) {
- // No effects for this source type yet.
- desc = new EffectDescVector();
- mInputSources.add(source, desc);
- } else {
- desc = mInputSources.valueAt(index);
+ std::shared_ptr<EffectDescVector>& desc = mInputSources[source];
+ if (desc == nullptr) {
+ desc = std::make_shared<EffectDescVector>();
}
// Create a new effect and add it to the vector.
@@ -389,9 +324,9 @@
ALOGE("addSourceDefaultEffect(): failed to get new unique id.");
return res;
}
- EffectDesc *effect = new EffectDesc(
+ std::shared_ptr<EffectDesc> effect = std::make_shared<EffectDesc>(
descriptor.name, descriptor.type, opPackageName, descriptor.uuid, priority, *id);
- desc->mEffects.add(effect);
+ desc->push_back(std::move(effect));
// TODO(b/71813697): Support setting params as well.
// TODO(b/71814300): Retroactively attach to any existing sources of the given type.
@@ -435,17 +370,13 @@
return BAD_VALUE;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
// Find the EffectDescVector for the given stream type, or create a new one if necessary.
- ssize_t index = mOutputStreams.indexOfKey(stream);
- EffectDescVector *desc = NULL;
- if (index < 0) {
+ std::shared_ptr<EffectDescVector>& desc = mOutputStreams[stream];
+ if (desc == nullptr) {
// No effects for this stream type yet.
- desc = new EffectDescVector();
- mOutputStreams.add(stream, desc);
- } else {
- desc = mOutputStreams.valueAt(index);
+ desc = std::make_shared<EffectDescVector>();
}
// Create a new effect and add it to the vector.
@@ -454,9 +385,9 @@
ALOGE("addStreamDefaultEffect(): failed to get new unique id.");
return res;
}
- EffectDesc *effect = new EffectDesc(
+ std::shared_ptr<EffectDesc> effect = std::make_shared<EffectDesc>(
descriptor.name, descriptor.type, opPackageName, descriptor.uuid, priority, *id);
- desc->mEffects.add(effect);
+ desc->push_back(std::move(effect));
// TODO(b/71813697): Support setting params as well.
// TODO(b/71814300): Retroactively attach to any existing streams of the given type.
@@ -475,18 +406,16 @@
return BAD_VALUE;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
// Check each source type.
- size_t numSources = mInputSources.size();
- for (size_t i = 0; i < numSources; ++i) {
+ for (auto& [source, descVector] : mInputSources) {
// Check each effect for each source.
- EffectDescVector* descVector = mInputSources[i];
- for (auto desc = descVector->mEffects.begin(); desc != descVector->mEffects.end(); ++desc) {
+ for (auto desc = descVector->begin(); desc != descVector->end(); ++desc) {
if ((*desc)->mId == id) {
// Found it!
// TODO(b/71814300): Remove from any sources the effect was attached to.
- descVector->mEffects.erase(desc);
+ descVector->erase(desc);
// Handles are unique; there can only be one match, so return early.
return NO_ERROR;
}
@@ -506,18 +435,16 @@
return BAD_VALUE;
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
// Check each stream type.
- size_t numStreams = mOutputStreams.size();
- for (size_t i = 0; i < numStreams; ++i) {
+ for (auto& [stream, descVector] : mOutputStreams) {
// Check each effect for each stream.
- EffectDescVector* descVector = mOutputStreams[i];
- for (auto desc = descVector->mEffects.begin(); desc != descVector->mEffects.end(); ++desc) {
+ for (auto desc = descVector->begin(); desc != descVector->end(); ++desc) {
if ((*desc)->mId == id) {
// Found it!
// TODO(b/71814300): Remove from any streams the effect was attached to.
- descVector->mEffects.erase(desc);
+ descVector->erase(desc);
// Handles are unique; there can only be one match, so return early.
return NO_ERROR;
}
@@ -530,8 +457,8 @@
void AudioPolicyEffects::EffectVector::setProcessorEnabled(bool enabled)
{
- for (size_t i = 0; i < mEffects.size(); i++) {
- mEffects.itemAt(i)->setEnabled(enabled);
+ for (const auto& effect : mEffects) {
+ effect->setEnabled(enabled);
}
}
@@ -540,7 +467,8 @@
// Audio processing configuration
// ----------------------------------------------------------------------------
-/*static*/ const char * const AudioPolicyEffects::kInputSourceNames[AUDIO_SOURCE_CNT -1] = {
+// we keep to const char* instead of std::string_view as comparison is believed faster.
+constexpr const char* kInputSourceNames[AUDIO_SOURCE_CNT - 1] = {
MIC_SRC_TAG,
VOICE_UL_SRC_TAG,
VOICE_DL_SRC_TAG,
@@ -567,7 +495,8 @@
return (audio_source_t)i;
}
-const char *AudioPolicyEffects::kStreamNames[AUDIO_STREAM_PUBLIC_CNT+1] = {
+// +1 as enum starts from -1
+constexpr const char* kStreamNames[AUDIO_STREAM_PUBLIC_CNT + 1] = {
AUDIO_STREAM_DEFAULT_TAG,
AUDIO_STREAM_VOICE_CALL_TAG,
AUDIO_STREAM_SYSTEM_TAG,
@@ -584,6 +513,7 @@
// returns the audio_stream_t enum corresponding to the output stream name or
// AUDIO_STREAM_PUBLIC_CNT is no match found
+/* static */
audio_stream_type_t AudioPolicyEffects::streamNameToEnum(const char *name)
{
int i;
@@ -600,6 +530,7 @@
// Audio Effect Config parser
// ----------------------------------------------------------------------------
+/* static */
size_t AudioPolicyEffects::growParamSize(char **param,
size_t size,
size_t *curSize,
@@ -623,7 +554,7 @@
return pos;
}
-
+/* static */
size_t AudioPolicyEffects::readParamValue(cnode *node,
char **param,
size_t *curSize,
@@ -692,7 +623,8 @@
return len;
}
-effect_param_t *AudioPolicyEffects::loadEffectParameter(cnode *root)
+/* static */
+std::shared_ptr<const effect_param_t> AudioPolicyEffects::loadEffectParameter(cnode* root)
{
cnode *param;
cnode *value;
@@ -722,7 +654,7 @@
*ptr = atoi(param->value);
fx_param->psize = sizeof(int);
fx_param->vsize = sizeof(int);
- return fx_param;
+ return {fx_param, free};
}
}
if (param == NULL || value == NULL) {
@@ -760,42 +692,43 @@
value = value->next;
}
- return fx_param;
+ return {fx_param, free};
error:
free(fx_param);
return NULL;
}
-void AudioPolicyEffects::loadEffectParameters(cnode *root, Vector <effect_param_t *>& params)
+/* static */
+void AudioPolicyEffects::loadEffectParameters(
+ cnode* root, std::vector<std::shared_ptr<const effect_param_t>>& params)
{
cnode *node = root->first_child;
while (node) {
ALOGV("loadEffectParameters() loading param %s", node->name);
- effect_param_t *param = loadEffectParameter(node);
- if (param != NULL) {
- params.add(param);
+ const auto param = loadEffectParameter(node);
+ if (param != nullptr) {
+ params.push_back(param);
}
node = node->next;
}
}
-
-AudioPolicyEffects::EffectDescVector *AudioPolicyEffects::loadEffectConfig(
- cnode *root,
- const Vector <EffectDesc *>& effects)
+/* static */
+std::shared_ptr<AudioPolicyEffects::EffectDescVector> AudioPolicyEffects::loadEffectConfig(
+ cnode* root, const EffectDescVector& effects)
{
cnode *node = root->first_child;
if (node == NULL) {
ALOGW("loadInputSource() empty element %s", root->name);
return NULL;
}
- EffectDescVector *desc = new EffectDescVector();
+ auto desc = std::make_shared<EffectDescVector>();
while (node) {
size_t i;
for (i = 0; i < effects.size(); i++) {
- if (strncmp(effects[i]->mName, node->name, EFFECT_STRING_LEN_MAX) == 0) {
+ if (effects[i]->mName == node->name) {
ALOGV("loadEffectConfig() found effect %s in list", node->name);
break;
}
@@ -805,23 +738,22 @@
node = node->next;
continue;
}
- EffectDesc *effect = new EffectDesc(*effects[i]); // deep copy
+ auto effect = std::make_shared<EffectDesc>(*effects[i]); // deep copy
loadEffectParameters(node, effect->mParams);
ALOGV("loadEffectConfig() adding effect %s uuid %08x",
- effect->mName, effect->mUuid.timeLow);
- desc->mEffects.add(effect);
+ effect->mName.c_str(), effect->mUuid.timeLow);
+ desc->push_back(std::move(effect));
node = node->next;
}
- if (desc->mEffects.size() == 0) {
+ if (desc->empty()) {
ALOGW("loadEffectConfig() no valid effects found in config %s", root->name);
- delete desc;
- return NULL;
+ return nullptr;
}
return desc;
}
-status_t AudioPolicyEffects::loadInputEffectConfigurations(cnode *root,
- const Vector <EffectDesc *>& effects)
+status_t AudioPolicyEffects::loadInputEffectConfigurations_l(cnode* root,
+ const EffectDescVector& effects)
{
cnode *node = config_find(root, PREPROCESSING_TAG);
if (node == NULL) {
@@ -831,24 +763,24 @@
while (node) {
audio_source_t source = inputSourceNameToEnum(node->name);
if (source == AUDIO_SOURCE_CNT) {
- ALOGW("loadInputSources() invalid input source %s", node->name);
+ ALOGW("%s() invalid input source %s", __func__, node->name);
node = node->next;
continue;
}
- ALOGV("loadInputSources() loading input source %s", node->name);
- EffectDescVector *desc = loadEffectConfig(node, effects);
+ ALOGV("%s() loading input source %s", __func__, node->name);
+ auto desc = loadEffectConfig(node, effects);
if (desc == NULL) {
node = node->next;
continue;
}
- mInputSources.add(source, desc);
+ mInputSources[source] = std::move(desc);
node = node->next;
}
return NO_ERROR;
}
-status_t AudioPolicyEffects::loadStreamEffectConfigurations(cnode *root,
- const Vector <EffectDesc *>& effects)
+status_t AudioPolicyEffects::loadStreamEffectConfigurations_l(cnode* root,
+ const EffectDescVector& effects)
{
cnode *node = config_find(root, OUTPUT_SESSION_PROCESSING_TAG);
if (node == NULL) {
@@ -858,23 +790,24 @@
while (node) {
audio_stream_type_t stream = streamNameToEnum(node->name);
if (stream == AUDIO_STREAM_PUBLIC_CNT) {
- ALOGW("loadStreamEffectConfigurations() invalid output stream %s", node->name);
+ ALOGW("%s() invalid output stream %s", __func__, node->name);
node = node->next;
continue;
}
- ALOGV("loadStreamEffectConfigurations() loading output stream %s", node->name);
- EffectDescVector *desc = loadEffectConfig(node, effects);
+ ALOGV("%s() loading output stream %s", __func__, node->name);
+ std::shared_ptr<EffectDescVector> desc = loadEffectConfig(node, effects);
if (desc == NULL) {
node = node->next;
continue;
}
- mOutputStreams.add(stream, desc);
+ mOutputStreams[stream] = std::move(desc);
node = node->next;
}
return NO_ERROR;
}
-AudioPolicyEffects::EffectDesc *AudioPolicyEffects::loadEffect(cnode *root)
+/* static */
+std::shared_ptr<AudioPolicyEffects::EffectDesc> AudioPolicyEffects::loadEffect(cnode* root)
{
cnode *node = config_find(root, UUID_TAG);
if (node == NULL) {
@@ -885,30 +818,33 @@
ALOGW("loadEffect() invalid uuid %s", node->value);
return NULL;
}
- return new EffectDesc(root->name, uuid);
+ return std::make_shared<EffectDesc>(root->name, uuid);
}
-status_t AudioPolicyEffects::loadEffects(cnode *root, Vector <EffectDesc *>& effects)
+/* static */
+android::AudioPolicyEffects::EffectDescVector AudioPolicyEffects::loadEffects(cnode *root)
{
+ EffectDescVector effects;
cnode *node = config_find(root, EFFECTS_TAG);
if (node == NULL) {
- return -ENOENT;
+ ALOGW("%s() Cannot find %s configuration", __func__, EFFECTS_TAG);
+ return effects;
}
node = node->first_child;
while (node) {
ALOGV("loadEffects() loading effect %s", node->name);
- EffectDesc *effect = loadEffect(node);
+ auto effect = loadEffect(node);
if (effect == NULL) {
node = node->next;
continue;
}
- effects.add(effect);
+ effects.push_back(std::move(effect));
node = node->next;
}
- return NO_ERROR;
+ return effects;
}
-status_t AudioPolicyEffects::loadAudioEffectConfig(
+status_t AudioPolicyEffects::loadAudioEffectConfig_ll(
const sp<EffectsFactoryHalInterface>& effectsFactoryHal) {
if (!effectsFactoryHal) {
ALOGE("%s Null EffectsFactoryHalInterface", __func__);
@@ -924,11 +860,12 @@
auto loadProcessingChain = [](auto& processingChain, auto& streams) {
for (auto& stream : processingChain) {
- auto effectDescs = std::make_unique<EffectDescVector>();
+ auto effectDescs = std::make_shared<EffectDescVector>();
for (auto& effect : stream.effects) {
- effectDescs->mEffects.add(new EffectDesc{effect->name.c_str(), effect->uuid});
+ effectDescs->push_back(
+ std::make_shared<EffectDesc>(effect->name, effect->uuid));
}
- streams.add(stream.type, effectDescs.release());
+ streams[stream.type] = std::move(effectDescs);
}
};
@@ -936,26 +873,26 @@
for (auto& deviceProcess : processingChain) {
auto effectDescs = std::make_unique<EffectDescVector>();
for (auto& effect : deviceProcess.effects) {
- effectDescs->mEffects.add(new EffectDesc{effect->name.c_str(), effect->uuid});
+ effectDescs->push_back(
+ std::make_shared<EffectDesc>(effect->name, effect->uuid));
}
- auto deviceEffects = std::make_unique<DeviceEffects>(
+ auto devEffects = std::make_unique<DeviceEffects>(
std::move(effectDescs), deviceProcess.type, deviceProcess.address);
- devicesEffects.emplace(deviceProcess.address, std::move(deviceEffects));
+ devicesEffects.emplace(deviceProcess.address, std::move(devEffects));
}
};
+ // access to mInputSources and mOutputStreams requires mMutex;
loadProcessingChain(processings->preprocess, mInputSources);
loadProcessingChain(processings->postprocess, mOutputStreams);
- {
- Mutex::Autolock _l(mLock);
- loadDeviceProcessingChain(processings->deviceprocess, mDeviceEffects);
- }
+ // access to mDeviceEffects requires mDeviceEffectsMutex
+ loadDeviceProcessingChain(processings->deviceprocess, mDeviceEffects);
return skippedElements;
}
-status_t AudioPolicyEffects::loadAudioEffectConfigLegacy(const char *path)
+status_t AudioPolicyEffects::loadAudioEffectConfigLegacy_l(const char *path)
{
cnode *root;
char *data;
@@ -967,15 +904,11 @@
root = config_node("", "");
config_load(root, data);
- Vector <EffectDesc *> effects;
- loadEffects(root, effects);
- loadInputEffectConfigurations(root, effects);
- loadStreamEffectConfigurations(root, effects);
+ const EffectDescVector effects = loadEffects(root);
- for (size_t i = 0; i < effects.size(); i++) {
- delete effects[i];
- }
-
+ // requires mMutex
+ loadInputEffectConfigurations_l(root, effects);
+ loadStreamEffectConfigurations_l(root, effects);
config_free(root);
free(root);
free(data);
@@ -985,14 +918,14 @@
void AudioPolicyEffects::initDefaultDeviceEffects()
{
- Mutex::Autolock _l(mLock);
+ std::lock_guard _l(mDeviceEffectsMutex);
for (const auto& deviceEffectsIter : mDeviceEffects) {
const auto& deviceEffects = deviceEffectsIter.second;
- for (const auto& effectDesc : deviceEffects->mEffectDescriptors->mEffects) {
+ for (const auto& effectDesc : *deviceEffects->mEffectDescriptors) {
AttributionSourceState attributionSource;
attributionSource.packageName = "android";
attributionSource.token = sp<BBinder>::make();
- sp<AudioEffect> fx = new AudioEffect(attributionSource);
+ sp<AudioEffect> fx = sp<AudioEffect>::make(attributionSource);
fx->set(EFFECT_UUID_NULL, &effectDesc->mUuid, 0 /* priority */, nullptr /* callback */,
AUDIO_SESSION_DEVICE, AUDIO_IO_HANDLE_NONE,
AudioDeviceTypeAddr{deviceEffects->getDeviceType(),
@@ -1000,16 +933,16 @@
status_t status = fx->initCheck();
if (status != NO_ERROR && status != ALREADY_EXISTS) {
ALOGE("%s(): failed to create Fx %s on port type=%d address=%s", __func__,
- effectDesc->mName, deviceEffects->getDeviceType(),
+ effectDesc->mName.c_str(), deviceEffects->getDeviceType(),
deviceEffects->getDeviceAddress().c_str());
// fx goes out of scope and strong ref on AudioEffect is released
continue;
}
fx->setEnabled(true);
ALOGV("%s(): create Fx %s added on port type=%d address=%s", __func__,
- effectDesc->mName, deviceEffects->getDeviceType(),
+ effectDesc->mName.c_str(), deviceEffects->getDeviceType(),
deviceEffects->getDeviceAddress().c_str());
- deviceEffects->mEffects.push_back(fx);
+ deviceEffects->mEffects.push_back(std::move(fx));
}
}
}
diff --git a/services/audiopolicy/service/AudioPolicyEffects.h b/services/audiopolicy/service/AudioPolicyEffects.h
index e17df48..259b84a 100644
--- a/services/audiopolicy/service/AudioPolicyEffects.h
+++ b/services/audiopolicy/service/AudioPolicyEffects.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef ANDROID_AUDIOPOLICYEFFECTS_H
-#define ANDROID_AUDIOPOLICYEFFECTS_H
+#pragma once
#include <stdlib.h>
#include <stdio.h>
@@ -23,6 +22,7 @@
#include <future>
#include <android-base/thread_annotations.h>
+#include <audio_utils/mutex.h>
#include <cutils/misc.h>
#include <media/AudioEffect.h>
#include <media/audiohal/EffectsFactoryHalInterface.h>
@@ -56,44 +56,43 @@
// First it will look whether vendor specific file exists,
// otherwise it will parse the system default file.
explicit AudioPolicyEffects(const sp<EffectsFactoryHalInterface>& effectsFactoryHal);
- virtual ~AudioPolicyEffects();
// NOTE: methods on AudioPolicyEffects should never be called with the AudioPolicyService
- // main mutex (mLock) held as they will indirectly call back into AudioPolicyService when
+ // main mutex (mMutex) held as they will indirectly call back into AudioPolicyService when
// managing audio effects.
// Return a list of effect descriptors for default input effects
// associated with audioSession
status_t queryDefaultInputEffects(audio_session_t audioSession,
effect_descriptor_t *descriptors,
- uint32_t *count);
+ uint32_t* count) EXCLUDES_AudioPolicyEffects_Mutex;
// Add all input effects associated with this input
// Effects are attached depending on the audio_source_t
status_t addInputEffects(audio_io_handle_t input,
audio_source_t inputSource,
- audio_session_t audioSession);
+ audio_session_t audioSession) EXCLUDES_AudioPolicyEffects_Mutex;
// Add all input effects associated to this input
status_t releaseInputEffects(audio_io_handle_t input,
- audio_session_t audioSession);
+ audio_session_t audioSession) EXCLUDES_AudioPolicyEffects_Mutex;
// Return a list of effect descriptors for default output effects
// associated with audioSession
status_t queryDefaultOutputSessionEffects(audio_session_t audioSession,
effect_descriptor_t *descriptors,
- uint32_t *count);
+ uint32_t* count) EXCLUDES_AudioPolicyEffects_Mutex;
// Add all output effects associated to this output
// Effects are attached depending on the audio_stream_type_t
status_t addOutputSessionEffects(audio_io_handle_t output,
audio_stream_type_t stream,
- audio_session_t audioSession);
+ audio_session_t audioSession) EXCLUDES_AudioPolicyEffects_Mutex;
// release all output effects associated with this output stream and audiosession
status_t releaseOutputSessionEffects(audio_io_handle_t output,
audio_stream_type_t stream,
- audio_session_t audioSession);
+ audio_session_t audioSession) EXCLUDES_AudioPolicyEffects_Mutex;
// Add the effect to the list of default effects for sources of type |source|.
status_t addSourceDefaultEffect(const effect_uuid_t *type,
@@ -101,7 +100,7 @@
const effect_uuid_t *uuid,
int32_t priority,
audio_source_t source,
- audio_unique_id_t* id);
+ audio_unique_id_t* id) EXCLUDES_AudioPolicyEffects_Mutex;
// Add the effect to the list of default effects for streams of a given usage.
status_t addStreamDefaultEffect(const effect_uuid_t *type,
@@ -109,36 +108,37 @@
const effect_uuid_t *uuid,
int32_t priority,
audio_usage_t usage,
- audio_unique_id_t* id);
+ audio_unique_id_t* id) EXCLUDES_AudioPolicyEffects_Mutex;
// Remove the default source effect from wherever it's attached.
- status_t removeSourceDefaultEffect(audio_unique_id_t id);
+ status_t removeSourceDefaultEffect(audio_unique_id_t id) EXCLUDES_AudioPolicyEffects_Mutex;
// Remove the default stream effect from wherever it's attached.
- status_t removeStreamDefaultEffect(audio_unique_id_t id);
+ status_t removeStreamDefaultEffect(audio_unique_id_t id) EXCLUDES_AudioPolicyEffects_Mutex;
- void setDefaultDeviceEffects();
+ // Initializes the Effects (AudioSystem must be ready as this creates audio client objects).
+ void initDefaultDeviceEffects() EXCLUDES(mDeviceEffectsMutex) EXCLUDES_EffectHandle_Mutex;
private:
- void initDefaultDeviceEffects();
// class to store the description of an effects and its parameters
// as defined in audio_effects.conf
class EffectDesc {
public:
- EffectDesc(const char *name,
+ EffectDesc(std::string_view name,
const effect_uuid_t& typeUuid,
const String16& opPackageName,
const effect_uuid_t& uuid,
uint32_t priority,
audio_unique_id_t id) :
- mName(strdup(name)),
+ mName(name),
mTypeUuid(typeUuid),
mOpPackageName(opPackageName),
mUuid(uuid),
mPriority(priority),
mId(id) { }
- EffectDesc(const char *name, const effect_uuid_t& uuid) :
+ // Modern EffectDesc usage:
+ EffectDesc(std::string_view name, const effect_uuid_t& uuid) :
EffectDesc(name,
*EFFECT_UUID_NULL,
String16(""),
@@ -146,67 +146,36 @@
0,
AUDIO_UNIQUE_ID_ALLOCATE) { }
EffectDesc(const EffectDesc& orig) :
- mName(strdup(orig.mName)),
+ mName(orig.mName),
mTypeUuid(orig.mTypeUuid),
mOpPackageName(orig.mOpPackageName),
mUuid(orig.mUuid),
mPriority(orig.mPriority),
- mId(orig.mId) {
- // deep copy mParams
- for (size_t k = 0; k < orig.mParams.size(); k++) {
- effect_param_t *origParam = orig.mParams[k];
- // psize and vsize are rounded up to an int boundary for allocation
- size_t origSize = sizeof(effect_param_t) +
- ((origParam->psize + 3) & ~3) +
- ((origParam->vsize + 3) & ~3);
- effect_param_t *dupParam = (effect_param_t *) malloc(origSize);
- memcpy(dupParam, origParam, origSize);
- // This works because the param buffer allocation is also done by
- // multiples of 4 bytes originally. In theory we should memcpy only
- // the actual param size, that is without rounding vsize.
- mParams.add(dupParam);
- }
- }
- /*virtual*/ ~EffectDesc() {
- free(mName);
- for (size_t k = 0; k < mParams.size(); k++) {
- free(mParams[k]);
- }
- }
- char *mName;
- effect_uuid_t mTypeUuid;
- String16 mOpPackageName;
- effect_uuid_t mUuid;
- int32_t mPriority;
- audio_unique_id_t mId;
- Vector <effect_param_t *> mParams;
+ mId(orig.mId),
+ mParams(orig.mParams) { }
+
+ const std::string mName;
+ const effect_uuid_t mTypeUuid;
+ const String16 mOpPackageName;
+ const effect_uuid_t mUuid;
+ const int32_t mPriority;
+ const audio_unique_id_t mId;
+ std::vector<std::shared_ptr<const effect_param_t>> mParams;
};
- // class to store voctor of EffectDesc
- class EffectDescVector {
- public:
- EffectDescVector() {}
- /*virtual*/ ~EffectDescVector() {
- for (size_t j = 0; j < mEffects.size(); j++) {
- delete mEffects[j];
- }
- }
- Vector <EffectDesc *> mEffects;
- };
+ using EffectDescVector = std::vector<std::shared_ptr<EffectDesc>>;
- // class to store voctor of AudioEffects
class EffectVector {
public:
- explicit EffectVector(audio_session_t session) : mSessionId(session), mRefCount(0) {}
- /*virtual*/ ~EffectVector() {}
+ explicit EffectVector(audio_session_t session) : mSessionId(session) {}
// Enable or disable all effects in effect vector
void setProcessorEnabled(bool enabled);
const audio_session_t mSessionId;
- // AudioPolicyManager keeps mLock, no need for lock on reference count here
- int mRefCount;
- Vector< sp<AudioEffect> >mEffects;
+ // AudioPolicyManager keeps mMutex, no need for lock on reference count here
+ int mRefCount = 0;
+ std::vector<sp<AudioEffect>> mEffects;
};
/**
@@ -215,12 +184,11 @@
class DeviceEffects {
public:
DeviceEffects(std::unique_ptr<EffectDescVector> effectDescriptors,
- audio_devices_t device, const std::string& address) :
+ audio_devices_t device, std::string_view address) :
mEffectDescriptors(std::move(effectDescriptors)),
mDeviceType(device), mDeviceAddress(address) {}
- /*virtual*/ ~DeviceEffects() = default;
- std::vector< sp<AudioEffect> > mEffects;
+ std::vector<sp<AudioEffect>> mEffects;
audio_devices_t getDeviceType() const { return mDeviceType; }
std::string getDeviceAddress() const { return mDeviceAddress; }
const std::unique_ptr<EffectDescVector> mEffectDescriptors;
@@ -231,65 +199,81 @@
};
- static const char * const kInputSourceNames[AUDIO_SOURCE_CNT -1];
+ status_t loadAudioEffectConfig_ll(const sp<EffectsFactoryHalInterface>& effectsFactoryHal)
+ REQUIRES(mMutex, mDeviceEffectsMutex);
+
+ // Legacy: Begin methods below.
+ // Parse audio_effects.conf - called from constructor.
+ status_t loadAudioEffectConfigLegacy_l(const char* path) REQUIRES(mMutex);
+
+ // Legacy: Load all automatic effect configurations
+ status_t loadInputEffectConfigurations_l(cnode* root,
+ const EffectDescVector& effects) REQUIRES(mMutex);
+ status_t loadStreamEffectConfigurations_l(cnode* root,
+ const EffectDescVector& effects) REQUIRES(mMutex);
+
+ // Legacy: static methods below.
+
static audio_source_t inputSourceNameToEnum(const char *name);
- static const char *kStreamNames[AUDIO_STREAM_PUBLIC_CNT+1]; //+1 required as streams start from -1
- audio_stream_type_t streamNameToEnum(const char *name);
-
- // Parse audio_effects.conf
- status_t loadAudioEffectConfigLegacy(const char *path);
- status_t loadAudioEffectConfig(const sp<EffectsFactoryHalInterface>& effectsFactoryHal);
+ static audio_stream_type_t streamNameToEnum(const char* name);
// Load all effects descriptors in configuration file
- status_t loadEffects(cnode *root, Vector <EffectDesc *>& effects);
- EffectDesc *loadEffect(cnode *root);
-
- // Load all automatic effect configurations
- status_t loadInputEffectConfigurations(cnode *root, const Vector <EffectDesc *>& effects);
- status_t loadStreamEffectConfigurations(cnode *root, const Vector <EffectDesc *>& effects);
- EffectDescVector *loadEffectConfig(cnode *root, const Vector <EffectDesc *>& effects);
+ static EffectDescVector loadEffects(cnode* root);
+ static std::shared_ptr<AudioPolicyEffects::EffectDesc> loadEffect(cnode* root);
+ static std::shared_ptr<EffectDescVector> loadEffectConfig(cnode* root,
+ const EffectDescVector& effects);
// Load all automatic effect parameters
- void loadEffectParameters(cnode *root, Vector <effect_param_t *>& params);
- effect_param_t *loadEffectParameter(cnode *root);
- size_t readParamValue(cnode *node,
+ static void loadEffectParameters(
+ cnode* root, std::vector<std::shared_ptr<const effect_param_t>>& params);
+
+ // loadEffectParameter returns a shared_ptr instead of a unique_ptr as there may
+ // be multiple references to the same effect parameter.
+ static std::shared_ptr<const effect_param_t> loadEffectParameter(cnode* root);
+ static size_t readParamValue(cnode* node,
char **param,
size_t *curSize,
size_t *totSize);
- size_t growParamSize(char **param,
+ static size_t growParamSize(char** param,
size_t size,
size_t *curSize,
size_t *totSize);
+ // Legacy: End methods above.
+
+ // Note: The association of Effects to audio source, session, or stream
+ // is done through std::map instead of std::unordered_map. This gives
+ // better reproducibility of issues, since map is ordered and more predictable
+ // in enumeration.
+
// protects access to mInputSources, mInputSessions, mOutputStreams, mOutputSessions
- // never hold AudioPolicyService::mLock when calling AudioPolicyEffects methods as
+ // never hold AudioPolicyService::mMutex when calling AudioPolicyEffects methods as
// those can call back into AudioPolicyService methods and try to acquire the mutex
- Mutex mLock;
+ mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kAudioPolicyEffects_Mutex};
// Automatic input effects are configured per audio_source_t
- KeyedVector< audio_source_t, EffectDescVector* > mInputSources;
- // Automatic input effects are unique for audio_io_handle_t
- KeyedVector< audio_session_t, EffectVector* > mInputSessions;
+ std::map<audio_source_t, std::shared_ptr<EffectDescVector>> mInputSources
+ GUARDED_BY(mMutex);
+ // Automatic input effects are unique for an audio_session_t.
+ std::map<audio_session_t, std::shared_ptr<EffectVector>> mInputSessions
+ GUARDED_BY(mMutex);
// Automatic output effects are organized per audio_stream_type_t
- KeyedVector< audio_stream_type_t, EffectDescVector* > mOutputStreams;
- // Automatic output effects are unique for audiosession ID
- KeyedVector< audio_session_t, EffectVector* > mOutputSessions;
+ std::map<audio_stream_type_t, std::shared_ptr<EffectDescVector>> mOutputStreams
+ GUARDED_BY(mMutex);
+ // Automatic output effects are unique for an audio_session_t.
+ std::map<audio_session_t, std::shared_ptr<EffectVector>> mOutputSessions
+ GUARDED_BY(mMutex);
/**
* @brief mDeviceEffects map of device effects indexed by the device address
*/
- std::map<std::string, std::unique_ptr<DeviceEffects>> mDeviceEffects GUARDED_BY(mLock);
- /**
- * Device Effect initialization must be asynchronous: the audio_policy service parses and init
- * effect on first reference. AudioFlinger will handle effect creation and register these
- * effect on audio_policy service.
- * We must store the reference of the furture garantee real asynchronous operation.
- */
- std::future<void> mDefaultDeviceEffectFuture;
+ // mDeviceEffects is never accessed through AudioPolicyEffects methods.
+ // We keep a separate mutex here to catch future methods attempting to access this variable.
+ std::mutex mDeviceEffectsMutex;
+ std::map<std::string, std::unique_ptr<DeviceEffects>> mDeviceEffects
+ GUARDED_BY(mDeviceEffectsMutex);
};
} // namespace android
-
-#endif // ANDROID_AUDIOPOLICYEFFECTS_H
diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
index 509b673..6e1ecec 100644
--- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
+++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
@@ -114,7 +114,7 @@
void AudioPolicyService::doOnNewAudioModulesAvailable()
{
if (mAudioPolicyManager == NULL) return;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
mAudioPolicyManager->onNewAudioModulesAvailable();
}
@@ -140,7 +140,7 @@
}
ALOGV("setDeviceConnectionState()");
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
status_t status = mAudioPolicyManager->setDeviceConnectionState(
state, port, encodedFormat);
@@ -162,7 +162,7 @@
AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
return Status::ok();
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
legacy2aidl_audio_policy_dev_state_t_AudioPolicyDeviceState(
@@ -190,7 +190,7 @@
}
ALOGV("handleDeviceConfigChange()");
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
status_t status = mAudioPolicyManager->handleDeviceConfigChange(
device, address.c_str(), deviceNameAidl.c_str(), encodedFormat);
@@ -221,7 +221,7 @@
// acquire lock before calling setMode() so that setMode() + setPhoneState() are an atomic
// operation from policy manager standpoint (no other operation (e.g track start or stop)
// can be interleaved).
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
// TODO: check if it is more appropriate to do it in platform specific policy manager
// Audio HAL mode conversion for call redirect modes
@@ -242,7 +242,7 @@
}
Status AudioPolicyService::getPhoneState(AudioMode* _aidl_return) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_mode_t_AudioMode(mPhoneState));
return Status::ok();
}
@@ -270,7 +270,7 @@
return binderStatusFromStatusT(BAD_VALUE);
}
ALOGV("setForceUse()");
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
mAudioPolicyManager->setForceUse(usage, config);
onCheckSpatializer_l();
@@ -312,7 +312,7 @@
return binderStatusFromStatusT(NO_INIT);
}
ALOGV("getOutput()");
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
legacy2aidl_audio_io_handle_t_int32_t(mAudioPolicyManager->getOutput(stream)));
@@ -352,7 +352,7 @@
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attr, attributionSource)));
ALOGV("%s()", __func__);
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (!mPackageManager.allowPlaybackCapture(VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_int32_t_uid_t(attributionSource.uid)))) {
@@ -458,7 +458,7 @@
sp<AudioPolicyEffects>& effects,
const char *context)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
const ssize_t index = mAudioPlaybackClients.indexOfKey(portId);
if (index < 0) {
ALOGE("%s AudioTrack client not found for portId %d", context, portId);
@@ -489,7 +489,7 @@
ALOGW("Failed to add effects on session %d", client->session);
}
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
status_t status = mAudioPolicyManager->startOutput(portId);
if (status == NO_ERROR) {
@@ -531,7 +531,7 @@
ALOGW("Failed to release effects on session %d", client->session);
}
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
status_t status = mAudioPolicyManager->stopOutput(portId);
if (status == NO_ERROR) {
@@ -567,7 +567,7 @@
audioPolicyEffects->releaseOutputSessionEffects(
client->io, client->stream, client->session);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (client != nullptr && client->active) {
onUpdateActiveSpatializerTracks_l();
}
@@ -691,7 +691,7 @@
status_t status;
AudioPolicyInterface::input_type_t inputType;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
{
AutoCallerClear acc;
// the audio_in_acoustics_t parameter is ignored by get_input()
@@ -794,7 +794,7 @@
}
sp<AudioRecordClient> client;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
ssize_t index = mAudioRecordClients.indexOfKey(portId);
if (index < 0) {
@@ -817,7 +817,7 @@
return binderStatusFromStatusT(PERMISSION_DENIED);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
ALOGW_IF(client->silenced, "startInput on silenced input for port %d, uid %d. Unsilencing.",
portIdAidl,
@@ -937,7 +937,7 @@
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
ssize_t index = mAudioRecordClients.indexOfKey(portId);
if (index < 0) {
@@ -967,7 +967,7 @@
sp<AudioPolicyEffects>audioPolicyEffects;
sp<AudioRecordClient> client;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
audioPolicyEffects = mAudioPolicyEffects;
ssize_t index = mAudioRecordClients.indexOfKey(portId);
if (index < 0) {
@@ -995,7 +995,7 @@
}
}
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
mAudioPolicyManager->releaseInput(portId);
}
@@ -1019,7 +1019,7 @@
if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
return binderStatusFromStatusT(BAD_VALUE);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
mAudioPolicyManager->initStreamVolume(stream, indexMin, indexMax);
return binderStatusFromStatusT(NO_ERROR);
@@ -1043,7 +1043,7 @@
if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
return binderStatusFromStatusT(BAD_VALUE);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
return binderStatusFromStatusT(mAudioPolicyManager->setStreamVolumeIndex(stream,
index,
@@ -1065,7 +1065,7 @@
if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
return binderStatusFromStatusT(BAD_VALUE);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getStreamVolumeIndex(stream, &index, device)));
@@ -1090,7 +1090,7 @@
if (!settingsAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
return binderStatusFromStatusT(
mAudioPolicyManager->setVolumeIndexForAttributes(attributes, index, device));
@@ -1110,7 +1110,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getVolumeIndexForAttributes(attributes, index, device)));
@@ -1129,7 +1129,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getMinVolumeIndexForAttributes(attributes, index)));
@@ -1148,7 +1148,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getMaxVolumeIndexForAttributes(attributes, index)));
@@ -1190,7 +1190,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getDevicesForAttributes(aa, &devices, forVolume)));
@@ -1210,7 +1210,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
legacy2aidl_audio_io_handle_t_int32_t(mAudioPolicyManager->getOutputForEffect(&desc)));
@@ -1235,7 +1235,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
return binderStatusFromStatusT(
mAudioPolicyManager->registerEffect(&desc, io, strategy, session, id));
@@ -1247,7 +1247,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
return binderStatusFromStatusT(mAudioPolicyManager->unregisterEffect(id));
}
@@ -1258,7 +1258,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
return binderStatusFromStatusT(mAudioPolicyManager->setEffectEnabled(id, enabled));
}
@@ -1277,7 +1277,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
return binderStatusFromStatusT(mAudioPolicyManager->moveEffectsToIo(ids, io));
}
@@ -1295,7 +1295,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = mAudioPolicyManager->isStreamActive(stream, inPastMs);
return Status::ok();
@@ -1315,7 +1315,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = mAudioPolicyManager->isStreamActiveRemotely(stream, inPastMs);
return Status::ok();
@@ -1327,7 +1327,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = mAudioPolicyManager->isSourceActive(source);
return Status::ok();
@@ -1339,7 +1339,7 @@
return NO_INIT;
}
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
audioPolicyEffects = mAudioPolicyEffects;
}
if (audioPolicyEffects == 0) {
@@ -1463,7 +1463,7 @@
convertRange(systemUsagesAidl.begin(), systemUsagesAidl.begin() + size,
std::back_inserter(systemUsages), aidl2legacy_AudioUsage_audio_usage_t)));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if(!modifyAudioRoutingAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
@@ -1483,7 +1483,7 @@
audio_flags_mask_t capturePolicy = VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_int32_t_audio_flags_mask_t_mask(capturePolicyAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager == NULL) {
ALOGV("%s() mAudioPolicyManager == NULL", __func__);
return binderStatusFromStatusT(NO_INIT);
@@ -1500,7 +1500,7 @@
ALOGV("mAudioPolicyManager == NULL");
return binderStatusFromStatusT(AUDIO_OFFLOAD_NOT_SUPPORTED);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_offload_mode_t_AudioOffloadMode(
mAudioPolicyManager->getOffloadSupport(info)));
@@ -1525,7 +1525,7 @@
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attributes)));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
*_aidl_return = mAudioPolicyManager->isDirectOutputSupported(config, attributes);
return Status::ok();
}
@@ -1561,7 +1561,7 @@
std::unique_ptr<audio_port_v7[]> ports(new audio_port_v7[num_ports]);
unsigned int generation;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
@@ -1589,7 +1589,7 @@
Status AudioPolicyService::listDeclaredDevicePorts(media::AudioPortRole role,
std::vector<media::AudioPortFw>* _aidl_return) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
@@ -1601,7 +1601,7 @@
Status AudioPolicyService::getAudioPort(int portId,
media::AudioPortFw* _aidl_return) {
audio_port_v7 port{ .id = portId };
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
@@ -1628,7 +1628,7 @@
aidl2legacy_int32_t_audio_port_handle_t(handleAidl));
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(AudioValidator::validateAudioPatch(patch)));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if(!modifyAudioRoutingAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
@@ -1647,7 +1647,7 @@
{
audio_patch_handle_t handle = VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_int32_t_audio_patch_handle_t(handleAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if(!modifyAudioRoutingAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
@@ -1672,7 +1672,7 @@
std::unique_ptr<audio_patch[]> patches(new audio_patch[num_patches]);
unsigned int generation;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
@@ -1710,7 +1710,7 @@
RETURN_IF_BINDER_ERROR(
binderStatusFromStatusT(AudioValidator::validateAudioPortConfig(config)));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if(!modifyAudioRoutingAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
@@ -1728,7 +1728,7 @@
audio_devices_t device;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
@@ -1750,7 +1750,7 @@
{
audio_session_t session = VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_int32_t_audio_session_t(sessionAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
@@ -1769,7 +1769,7 @@
convertRange(mixesAidl.begin(), mixesAidl.begin() + size, std::back_inserter(mixes),
aidl2legacy_AudioMix)));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
// loopback|render only need a MediaProjection (checked in caller AudioService.java)
bool needModifyAudioRouting = std::any_of(mixes.begin(), mixes.end(), [](auto& mix) {
@@ -1812,7 +1812,7 @@
Status AudioPolicyService::updatePolicyMixes(
const ::std::vector<::android::media::AudioMixUpdate>& updates) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
for (const auto& update : updates) {
AudioMix mix = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_AudioMix(update.audioMix));
std::vector<AudioMixMatchCriterion> newCriteria =
@@ -1834,7 +1834,7 @@
convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
aidl2legacy_AudioDeviceTypeAddress));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if(!modifyAudioRoutingAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
@@ -1848,7 +1848,7 @@
Status AudioPolicyService::removeUidDeviceAffinities(int32_t uidAidl) {
uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if(!modifyAudioRoutingAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
@@ -1867,7 +1867,7 @@
convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
aidl2legacy_AudioDeviceTypeAddress));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if(!modifyAudioRoutingAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
@@ -1881,7 +1881,7 @@
Status AudioPolicyService::removeUserIdDeviceAffinities(int32_t userIdAidl) {
int userId = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret<int>(userIdAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if(!modifyAudioRoutingAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
@@ -1905,7 +1905,7 @@
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
AudioValidator::validateAudioAttributes(attributes, "68953950")));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
@@ -1926,7 +1926,7 @@
audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
@@ -1942,7 +1942,7 @@
if (!settingsAllowed()) {
return binderStatusFromStatusT(PERMISSION_DENIED);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
return binderStatusFromStatusT(mAudioPolicyManager->setMasterMono(mono));
}
@@ -1952,7 +1952,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
return binderStatusFromStatusT(mAudioPolicyManager->getMasterMono(_aidl_return));
}
@@ -1970,7 +1970,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = mAudioPolicyManager->getStreamVolumeDB(stream, index, device);
return Status::ok();
@@ -1991,7 +1991,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getSurroundFormats(&numSurroundFormats, surroundFormats.get(),
@@ -2022,7 +2022,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getReportedSurroundFormats(
@@ -2044,7 +2044,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl));
@@ -2064,7 +2064,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
return binderStatusFromStatusT(
mAudioPolicyManager->setSurroundFormatEnabled(audioFormat, enabled));
@@ -2087,7 +2087,7 @@
std::vector<uid_t> uids;
RETURN_IF_BINDER_ERROR(convertInt32VectorToUidVectorWithLimit(uidsAidl, uids));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mUidPolicy->setAssistantUids(uids);
return Status::ok();
}
@@ -2097,7 +2097,7 @@
std::vector<uid_t> activeUids;
RETURN_IF_BINDER_ERROR(convertInt32VectorToUidVectorWithLimit(activeUidsAidl, activeUids));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mUidPolicy->setActiveAssistantUids(activeUids);
return Status::ok();
}
@@ -2107,7 +2107,7 @@
std::vector<uid_t> uids;
RETURN_IF_BINDER_ERROR(convertInt32VectorToUidVectorWithLimit(uidsAidl, uids));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mUidPolicy->setA11yUids(uids);
return Status::ok();
}
@@ -2115,7 +2115,7 @@
Status AudioPolicyService::setCurrentImeUid(int32_t uidAidl)
{
uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mUidPolicy->setCurrentImeUid(uid);
return Status::ok();
}
@@ -2125,7 +2125,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = mAudioPolicyManager->isHapticPlaybackSupported();
return Status::ok();
@@ -2136,7 +2136,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = mAudioPolicyManager->isUltrasoundSupported();
return Status::ok();
@@ -2147,7 +2147,7 @@
if (mAudioPolicyManager == nullptr) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = mAudioPolicyManager->isHotwordStreamSupported(lookbackAudio);
return Status::ok();
@@ -2160,7 +2160,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
RETURN_IF_BINDER_ERROR(
binderStatusFromStatusT(mAudioPolicyManager->listAudioProductStrategies(strategies)));
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
@@ -2180,7 +2180,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getProductStrategyFromAudioAttributes(
aa, productStrategy, fallbackOnDefault)));
@@ -2195,7 +2195,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
RETURN_IF_BINDER_ERROR(
binderStatusFromStatusT(mAudioPolicyManager->listAudioVolumeGroups(groups)));
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
@@ -2214,7 +2214,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
RETURN_IF_BINDER_ERROR(
binderStatusFromStatusT(
mAudioPolicyManager->getVolumeGroupFromAudioAttributes(
@@ -2225,7 +2225,7 @@
Status AudioPolicyService::setRttEnabled(bool enabled)
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mUidPolicy->setRttEnabled(enabled);
return Status::ok();
}
@@ -2235,7 +2235,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
AutoCallerClear acc;
*_aidl_return = mAudioPolicyManager->isCallScreenModeSupported();
return Status::ok();
@@ -2256,7 +2256,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
status_t status = mAudioPolicyManager->setDevicesRoleForStrategy(strategy, role, devices);
if (status == NO_ERROR) {
onCheckSpatializer_l();
@@ -2279,7 +2279,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
status_t status = mAudioPolicyManager->removeDevicesRoleForStrategy(strategy, role, devices);
if (status == NO_ERROR) {
onCheckSpatializer_l();
@@ -2296,7 +2296,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
status_t status = mAudioPolicyManager->clearDevicesRoleForStrategy(strategy, role);
if (status == NO_ERROR) {
onCheckSpatializer_l();
@@ -2317,7 +2317,7 @@
if (mAudioPolicyManager == NULL) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getDevicesForRoleAndStrategy(strategy, role, devices)));
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
@@ -2347,7 +2347,7 @@
if (mAudioPolicyManager == nullptr) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
return binderStatusFromStatusT(
mAudioPolicyManager->setDevicesRoleForCapturePreset(audioSource, role, devices));
}
@@ -2367,7 +2367,7 @@
if (mAudioPolicyManager == nullptr) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
return binderStatusFromStatusT(
mAudioPolicyManager->addDevicesRoleForCapturePreset(audioSource, role, devices));
}
@@ -2387,7 +2387,7 @@
if (mAudioPolicyManager == nullptr) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
return binderStatusFromStatusT(
mAudioPolicyManager->removeDevicesRoleForCapturePreset(audioSource, role, devices));
}
@@ -2402,7 +2402,7 @@
if (mAudioPolicyManager == nullptr) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
return binderStatusFromStatusT(
mAudioPolicyManager->clearDevicesRoleForCapturePreset(audioSource, role));
}
@@ -2420,7 +2420,7 @@
if (mAudioPolicyManager == nullptr) {
return binderStatusFromStatusT(NO_INIT);
}
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices)));
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
@@ -2467,7 +2467,7 @@
convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
aidl2legacy_AudioDeviceTypeAddress));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
*_aidl_return = mAudioPolicyManager->canBeSpatialized(&attr, &config, devices);
return Status::ok();
}
@@ -2486,7 +2486,7 @@
aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
audio_config_t config = VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_AudioConfig_audio_config_t(configAidl, false /*isInput*/));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
*_aidl_return = static_cast<media::AudioDirectMode>(
VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_direct_mode_t_int32_t_mask(
mAudioPolicyManager->getDirectPlaybackSupport(&attr, &config))));
@@ -2503,7 +2503,7 @@
aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
AudioProfileVector audioProfiles;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
mAudioPolicyManager->getDirectProfilesForAttributes(&attr, audioProfiles)));
*_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
@@ -2523,7 +2523,7 @@
aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
std::vector<audio_mixer_attributes_t> mixerAttrs;
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
RETURN_IF_BINDER_ERROR(
binderStatusFromStatusT(mAudioPolicyManager->getSupportedMixerAttributes(
portId, mixerAttrs)));
@@ -2551,7 +2551,7 @@
audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
return binderStatusFromStatusT(
mAudioPolicyManager->setPreferredMixerAttributes(&attr, portId, uid, &mixerAttr));
}
@@ -2569,7 +2569,7 @@
audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
audio_mixer_attributes_t mixerAttr = AUDIO_MIXER_ATTRIBUTES_INITIALIZER;
RETURN_IF_BINDER_ERROR(
binderStatusFromStatusT(mAudioPolicyManager->getPreferredMixerAttributes(
@@ -2593,7 +2593,7 @@
audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
return binderStatusFromStatusT(
mAudioPolicyManager->clearPreferredMixerAttributes(&attr, portId, uid));
}
diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp
index 5d3788d..717640f 100644
--- a/services/audiopolicy/service/AudioPolicyService.cpp
+++ b/services/audiopolicy/service/AudioPolicyService.cpp
@@ -18,9 +18,6 @@
//#define LOG_NDEBUG 0
#include "Configuration.h"
-#undef __STRICT_ANSI__
-#define __STDINT_LIMITS
-#define __STDC_LIMIT_MACROS
#include <stdint.h>
#include <sys/time.h>
#include <dlfcn.h>
@@ -265,7 +262,7 @@
.set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
.record(); });
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
// start audio commands thread
mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
@@ -280,11 +277,11 @@
// load audio processing modules
const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
- sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects(effectsFactoryHal);
- sp<UidPolicy> uidPolicy = new UidPolicy(this);
- sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
+ auto audioPolicyEffects = sp<AudioPolicyEffects>::make(effectsFactoryHal);
+ auto uidPolicy = sp<UidPolicy>::make(this);
+ auto sensorPrivacyPolicy = sp<SensorPrivacyPolicy>::make(this);
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mAudioPolicyEffects = audioPolicyEffects;
mUidPolicy = uidPolicy;
mSensorPrivacyPolicy = sensorPrivacyPolicy;
@@ -294,16 +291,16 @@
// Create spatializer if supported
if (mAudioPolicyManager != nullptr) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
AudioDeviceTypeAddrVector devices;
bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
if (hasSpatializer) {
// Unlock as Spatializer::create() will use the callback and acquire the
// AudioPolicyService_Mutex.
- mLock.unlock();
+ mMutex.unlock();
mSpatializer = Spatializer::create(this, effectsFactoryHal);
- mLock.lock();
+ mMutex.lock();
}
if (mSpatializer == nullptr) {
// No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
@@ -312,9 +309,16 @@
}
}
AudioSystem::audioPolicyReady();
- // AudioFlinger will handle effect creation and register these effects on audio_policy
- // service. Hence, audio_policy service must be ready.
- audioPolicyEffects->setDefaultDeviceEffects();
+}
+
+void AudioPolicyService::onAudioSystemReady() {
+ sp<AudioPolicyEffects> audioPolicyEffects;
+ {
+ audio_utils::lock_guard _l(mMutex);
+
+ audioPolicyEffects = mAudioPolicyEffects;
+ }
+ audioPolicyEffects->initDefaultDeviceEffects();
}
void AudioPolicyService::unloadAudioPolicyManager()
@@ -356,7 +360,7 @@
ALOGW("%s got NULL client", __FUNCTION__);
return Status::ok();
}
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
uid_t uid = IPCThreadState::self()->getCallingUid();
pid_t pid = IPCThreadState::self()->getCallingPid();
@@ -379,7 +383,7 @@
Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
uid_t uid = IPCThreadState::self()->getCallingUid();
pid_t pid = IPCThreadState::self()->getCallingPid();
@@ -394,7 +398,7 @@
Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
uid_t uid = IPCThreadState::self()->getCallingUid();
pid_t pid = IPCThreadState::self()->getCallingPid();
@@ -412,7 +416,7 @@
{
bool hasSameUid = false;
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
int64_t token = ((int64_t)uid<<32) | pid;
mNotificationClients.removeItem(token);
for (size_t i = 0; i < mNotificationClients.size(); i++) {
@@ -423,7 +427,7 @@
}
}
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
if (mAudioPolicyManager && !hasSameUid) {
// called from binder death notification: no need to clear caller identity
mAudioPolicyManager->releaseResourcesForUid(uid);
@@ -438,7 +442,7 @@
void AudioPolicyService::doOnAudioPortListUpdate()
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
for (size_t i = 0; i < mNotificationClients.size(); i++) {
mNotificationClients.valueAt(i)->onAudioPortListUpdate();
}
@@ -451,7 +455,7 @@
void AudioPolicyService::doOnAudioPatchListUpdate()
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
for (size_t i = 0; i < mNotificationClients.size(); i++) {
mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
}
@@ -464,7 +468,7 @@
void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
for (size_t i = 0; i < mNotificationClients.size(); i++) {
mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
}
@@ -479,7 +483,7 @@
void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
for (size_t i = 0; i < mNotificationClients.size(); i++) {
mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
}
@@ -509,7 +513,7 @@
audio_patch_handle_t patchHandle,
audio_source_t source)
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
for (size_t i = 0; i < mNotificationClients.size(); i++) {
mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
@@ -523,7 +527,7 @@
void AudioPolicyService::doOnRoutingUpdated()
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
for (size_t i = 0; i < mNotificationClients.size(); i++) {
mNotificationClients.valueAt(i)->onRoutingUpdated();
}
@@ -536,7 +540,7 @@
void AudioPolicyService::doOnVolumeRangeInitRequest()
{
- Mutex::Autolock _l(mNotificationClientsLock);
+ audio_utils::lock_guard _l(mNotificationClientsMutex);
for (size_t i = 0; i < mNotificationClients.size(); i++) {
mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
}
@@ -544,7 +548,7 @@
void AudioPolicyService::onCheckSpatializer()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
onCheckSpatializer_l();
}
@@ -568,7 +572,7 @@
const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
audio_config_base_t config = mSpatializer->getAudioInConfig();
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
status_t status =
mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
@@ -577,13 +581,13 @@
return;
}
size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
- mLock.unlock();
+ mMutex.unlock();
// It is OK to call detachOutput() is none is already attached.
mSpatializer->detachOutput();
if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
status = mSpatializer->attachOutput(newOutput, numActiveTracks);
}
- mLock.lock();
+ mMutex.lock();
if (status != NO_ERROR) {
mAudioPolicyManager->releaseSpatializerOutput(newOutput);
}
@@ -592,7 +596,7 @@
audio_io_handle_t output = mSpatializer->detachOutput();
if (output != AUDIO_IO_HANDLE_NONE) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mAudioPolicyManager->releaseSpatializerOutput(output);
}
}
@@ -627,7 +631,7 @@
audio_io_handle_t output = mSpatializer->getOutput();
size_t activeClients;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
activeClients = countActiveClientsOnOutput_l(output);
}
mSpatializer->updateActiveTracks(activeClients);
@@ -783,12 +787,8 @@
IPCThreadState::self()->getCallingPid());
}
-static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
-{
- return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
-}
-
-static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
+static void dumpReleaseLock(audio_utils::mutex& mutex, bool locked)
+ RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
{
if (locked) mutex.unlock();
}
@@ -825,7 +825,7 @@
void AudioPolicyService::updateUidStates()
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
updateUidStates_l();
}
@@ -1027,7 +1027,7 @@
bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
- auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
+ auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mMutex) {
uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
recordClient->attributionSource.uid));
bool canCaptureCall = recordClient->canCaptureOutput;
@@ -1205,11 +1205,12 @@
}
status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
+NO_THREAD_SAFETY_ANALYSIS // update for trylock.
{
if (!dumpAllowed()) {
dumpPermissionDenial(fd);
} else {
- const bool locked = dumpTryLock(mLock);
+ const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
if (!locked) {
String8 result(kDeadlockedString);
write(fd, result.c_str(), result.size());
@@ -1238,7 +1239,7 @@
mPackageManager.dump(fd);
- dumpReleaseLock(mLock, locked);
+ dumpReleaseLock(mMutex, locked);
if (mSpatializer != nullptr) {
std::string dumpString = mSpatializer->toString(1 /* level */);
@@ -1483,7 +1484,7 @@
sp<UidPolicy> uidPolicy;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
uidPolicy = mUidPolicy;
}
if (uidPolicy) {
@@ -1512,7 +1513,7 @@
sp<UidPolicy> uidPolicy;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
uidPolicy = mUidPolicy;
}
if (uidPolicy) {
@@ -1541,7 +1542,7 @@
sp<UidPolicy> uidPolicy;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
uidPolicy = mUidPolicy;
}
if (uidPolicy) {
@@ -1579,7 +1580,7 @@
ActivityManager::PROCESS_STATE_UNKNOWN,
String16("audioserver"));
if (!res) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mObserverRegistered = true;
} else {
ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
@@ -1591,12 +1592,12 @@
void AudioPolicyService::UidPolicy::unregisterSelf() {
mAm.unlinkToDeath(this);
mAm.unregisterUidObserver(this);
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mObserverRegistered = false;
}
void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mCachedUids.clear();
mObserverRegistered = false;
}
@@ -1604,7 +1605,7 @@
void AudioPolicyService::UidPolicy::checkRegistered() {
bool needToReregister = false;
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
needToReregister = !mObserverRegistered;
}
if (needToReregister) {
@@ -1617,7 +1618,7 @@
if (isServiceUid(uid)) return true;
checkRegistered();
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
auto overrideIter = mOverrideUids.find(uid);
if (overrideIter != mOverrideUids.end()) {
return overrideIter->second.first;
@@ -1632,7 +1633,7 @@
ActivityManager am;
bool active = am.isUidActive(uid, String16("audioserver"));
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mCachedUids.insert(std::pair<uid_t,
std::pair<bool, int>>(uid, std::pair<bool, int>(active,
ActivityManager::PROCESS_STATE_UNKNOWN)));
@@ -1646,7 +1647,7 @@
}
checkRegistered();
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
auto overrideIter = mOverrideUids.find(uid);
if (overrideIter != mOverrideUids.end()) {
if (overrideIter->second.first) {
@@ -1681,7 +1682,7 @@
state = am.getUidProcessState(uid, String16("audioserver"));
}
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
mCachedUids.insert(std::pair<uid_t,
std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
}
@@ -1736,7 +1737,7 @@
bool wasActive = isUidActive(uid);
int previousState = getUidState(uid);
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
updateUidLocked(uids, uid, active, state, insert);
}
if (wasActive != isUidActive(uid) || state != previousState) {
@@ -1771,7 +1772,7 @@
}
bool AudioPolicyService::UidPolicy::isA11yOnTop() {
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
for (const auto &uid : mCachedUids) {
if (!isA11yUid(uid.first)) {
continue;
@@ -1902,7 +1903,7 @@
{
nsecs_t waitTime = -1;
- mLock.lock();
+ audio_utils::unique_lock ul(mMutex);
while (!exitPending())
{
sp<AudioPolicyService> svc;
@@ -1923,27 +1924,27 @@
VolumeData *data = (VolumeData *)command->mParam.get();
ALOGV("AudioCommandThread() processing set volume stream %d, \
volume %f, output %d", data->mStream, data->mVolume, data->mIO);
- mLock.unlock();
+ ul.unlock();
command->mStatus = AudioSystem::setStreamVolume(data->mStream,
data->mVolume,
data->mIO);
- mLock.lock();
+ ul.lock();
}break;
case SET_PARAMETERS: {
ParametersData *data = (ParametersData *)command->mParam.get();
ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
data->mKeyValuePairs.c_str(), data->mIO);
- mLock.unlock();
+ ul.unlock();
command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
- mLock.lock();
+ ul.lock();
}break;
case SET_VOICE_VOLUME: {
VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
ALOGV("AudioCommandThread() processing set voice volume volume %f",
data->mVolume);
- mLock.unlock();
+ ul.unlock();
command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
- mLock.lock();
+ ul.lock();
}break;
case STOP_OUTPUT: {
StopOutputData *data = (StopOutputData *)command->mParam.get();
@@ -1953,9 +1954,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doStopOutput(data->mPortId);
- mLock.lock();
+ ul.lock();
}break;
case RELEASE_OUTPUT: {
ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
@@ -1965,9 +1966,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doReleaseOutput(data->mPortId);
- mLock.lock();
+ ul.lock();
}break;
case CREATE_AUDIO_PATCH: {
CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
@@ -1976,9 +1977,9 @@
if (af == 0) {
command->mStatus = PERMISSION_DENIED;
} else {
- mLock.unlock();
+ ul.unlock();
command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
- mLock.lock();
+ ul.lock();
}
} break;
case RELEASE_AUDIO_PATCH: {
@@ -1988,9 +1989,9 @@
if (af == 0) {
command->mStatus = PERMISSION_DENIED;
} else {
- mLock.unlock();
+ ul.unlock();
command->mStatus = af->releaseAudioPatch(data->mHandle);
- mLock.lock();
+ ul.lock();
}
} break;
case UPDATE_AUDIOPORT_LIST: {
@@ -1999,9 +2000,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnAudioPortListUpdate();
- mLock.lock();
+ ul.lock();
}break;
case UPDATE_AUDIOPATCH_LIST: {
ALOGV("AudioCommandThread() processing update audio patch list");
@@ -2009,9 +2010,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnAudioPatchListUpdate();
- mLock.lock();
+ ul.lock();
}break;
case CHANGED_AUDIOVOLUMEGROUP: {
AudioVolumeGroupData *data =
@@ -2021,9 +2022,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
- mLock.lock();
+ ul.lock();
}break;
case SET_AUDIOPORT_CONFIG: {
SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
@@ -2032,9 +2033,9 @@
if (af == 0) {
command->mStatus = PERMISSION_DENIED;
} else {
- mLock.unlock();
+ ul.unlock();
command->mStatus = af->setAudioPortConfig(&data->mConfig);
- mLock.lock();
+ ul.lock();
}
} break;
case DYN_POLICY_MIX_STATE_UPDATE: {
@@ -2046,9 +2047,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
- mLock.lock();
+ ul.lock();
} break;
case RECORDING_CONFIGURATION_UPDATE: {
RecordingConfigurationUpdateData *data =
@@ -2058,21 +2059,21 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
&data->mClientConfig, data->mClientEffects,
&data->mDeviceConfig, data->mEffects,
data->mPatchHandle, data->mSource);
- mLock.lock();
+ ul.lock();
} break;
case SET_EFFECT_SUSPENDED: {
SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
ALOGV("AudioCommandThread() processing set effect suspended");
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af != 0) {
- mLock.unlock();
+ ul.unlock();
af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
- mLock.lock();
+ ul.lock();
}
} break;
case AUDIO_MODULES_UPDATE: {
@@ -2081,9 +2082,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnNewAudioModulesAvailable();
- mLock.lock();
+ ul.lock();
} break;
case ROUTING_UPDATED: {
ALOGV("AudioCommandThread() processing routing update");
@@ -2091,9 +2092,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnRoutingUpdated();
- mLock.lock();
+ ul.lock();
} break;
case UPDATE_UID_STATES: {
@@ -2102,9 +2103,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->updateUidStates();
- mLock.lock();
+ ul.lock();
} break;
case CHECK_SPATIALIZER_OUTPUT: {
@@ -2113,9 +2114,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnCheckSpatializer();
- mLock.lock();
+ ul.lock();
} break;
case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
@@ -2124,9 +2125,9 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnUpdateActiveSpatializerTracks();
- mLock.lock();
+ ul.lock();
} break;
case VOL_RANGE_INIT_REQUEST: {
@@ -2135,28 +2136,28 @@
if (svc == 0) {
break;
}
- mLock.unlock();
+ ul.unlock();
svc->doOnVolumeRangeInitRequest();
- mLock.lock();
+ ul.lock();
} break;
default:
ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
}
{
- Mutex::Autolock _l(command->mLock);
+ audio_utils::lock_guard _l(command->mMutex);
if (command->mWaitStatus) {
command->mWaitStatus = false;
- command->mCond.signal();
+ command->mCond.notify_one();
}
}
waitTime = -1;
- // release mLock before releasing strong reference on the service as
+ // release ul before releasing strong reference on the service as
// AudioPolicyService destructor calls AudioCommandThread::exit() which
- // acquires mLock.
- mLock.unlock();
+ // acquires ul.
+ ul.unlock();
svc.clear();
- mLock.lock();
+ ul.lock();
} else {
waitTime = mAudioCommands[0]->mTime - curTime;
break;
@@ -2174,9 +2175,10 @@
if (!exitPending()) {
ALOGV("AudioCommandThread() going to sleep");
if (waitTime == -1) {
- mWaitWorkCV.wait(mLock);
+ mWaitWorkCV.wait(ul);
} else {
- mWaitWorkCV.waitRelative(mLock, waitTime);
+ // discard return value.
+ mWaitWorkCV.wait_for(ul, std::chrono::nanoseconds(waitTime));
}
}
}
@@ -2184,17 +2186,17 @@
if (!mAudioCommands.isEmpty()) {
release_wake_lock(mName.c_str());
}
- mLock.unlock();
return false;
}
status_t AudioPolicyService::AudioCommandThread::dump(int fd)
+NO_THREAD_SAFETY_ANALYSIS // trylock
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
- const bool locked = dumpTryLock(mLock);
+ const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
if (!locked) {
String8 result2(kCmdDeadlockedString);
write(fd, result2.c_str(), result2.size());
@@ -2217,7 +2219,7 @@
write(fd, result.c_str(), result.size());
- dumpReleaseLock(mLock, locked);
+ dumpReleaseLock(mMutex, locked);
return NO_ERROR;
}
@@ -2475,14 +2477,15 @@
status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
{
{
- Mutex::Autolock _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
insertCommand_l(command, delayMs);
- mWaitWorkCV.signal();
+ mWaitWorkCV.notify_one();
}
- Mutex::Autolock _l(command->mLock);
+ audio_utils::unique_lock ul(command->mMutex);
while (command->mWaitStatus) {
nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
- if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
+ if (command->mCond.wait_for(
+ ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
command->mStatus = TIMED_OUT;
command->mWaitStatus = false;
}
@@ -2490,7 +2493,7 @@
return command->mStatus;
}
-// insertCommand_l() must be called with mLock held
+// insertCommand_l() must be called with mMutex held
void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
{
ssize_t i; // not size_t because i will count down to -1
@@ -2678,9 +2681,9 @@
{
ALOGV("AudioCommandThread::exit");
{
- AutoMutex _l(mLock);
+ audio_utils::lock_guard _l(mMutex);
requestExit();
- mWaitWorkCV.signal();
+ mWaitWorkCV.notify_one();
}
// Note that we can call it from the thread loop if all other references have been released
// but it will safely return WOULD_BLOCK in this case
diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h
index aaf0b1b..5adedc6 100644
--- a/services/audiopolicy/service/AudioPolicyService.h
+++ b/services/audiopolicy/service/AudioPolicyService.h
@@ -20,6 +20,7 @@
#include <android/media/BnAudioPolicyService.h>
#include <android/media/GetSpatializerResponse.h>
#include <android-base/thread_annotations.h>
+#include <audio_utils/mutex.h>
#include <cutils/misc.h>
#include <cutils/config_utils.h>
#include <cutils/compiler.h>
@@ -319,6 +320,9 @@
// RefBase
virtual void onFirstRef();
+ // Commence initialization when AudioSystem is ready.
+ void onAudioSystemReady();
+
//
// Helpers for the struct audio_policy_service_ops implementation.
// This is used by the audio policy manager for certain operations that
@@ -387,10 +391,10 @@
* by audio policy manager and attach/detach the spatializer effect accordingly.
*/
void onCheckSpatializer() override;
- void onCheckSpatializer_l() REQUIRES(mLock);
+ void onCheckSpatializer_l() REQUIRES(mMutex);
void doOnCheckSpatializer();
- void onUpdateActiveSpatializerTracks_l() REQUIRES(mLock);
+ void onUpdateActiveSpatializerTracks_l() REQUIRES(mMutex);
void doOnUpdateActiveSpatializerTracks();
@@ -402,14 +406,14 @@
AudioPolicyService() ANDROID_API;
virtual ~AudioPolicyService();
- status_t dumpInternals(int fd) REQUIRES(mLock);
+ status_t dumpInternals(int fd) REQUIRES(mMutex);
// Handles binder shell commands
virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args);
// Sets whether the given UID records only silence
- virtual void setAppState_l(sp<AudioRecordClient> client, app_state_t state) REQUIRES(mLock);
+ virtual void setAppState_l(sp<AudioRecordClient> client, app_state_t state) REQUIRES(mMutex);
// Overrides the UID state as if it is idle
status_t handleSetUidState(Vector<String16>& args, int err);
@@ -435,9 +439,9 @@
const AttributionSourceState& attributionSource);
void updateUidStates();
- void updateUidStates_l() REQUIRES(mLock);
+ void updateUidStates_l() REQUIRES(mMutex);
- void silenceAllRecordings_l() REQUIRES(mLock);
+ void silenceAllRecordings_l() REQUIRES(mMutex);
static bool isVirtualSource(audio_source_t source);
@@ -510,11 +514,11 @@
void checkRegistered();
wp<AudioPolicyService> mService;
- Mutex mLock;
+ audio_utils::mutex mMutex{audio_utils::MutexOrder::kUidPolicy_Mutex};
ActivityManager mAm;
bool mObserverRegistered = false;
- std::unordered_map<uid_t, std::pair<bool, int>> mOverrideUids GUARDED_BY(mLock);
- std::unordered_map<uid_t, std::pair<bool, int>> mCachedUids GUARDED_BY(mLock);
+ std::unordered_map<uid_t, std::pair<bool, int>> mOverrideUids GUARDED_BY(mMutex);
+ std::unordered_map<uid_t, std::pair<bool, int>> mCachedUids GUARDED_BY(mMutex);
std::vector<uid_t> mAssistantUids;
std::vector<uid_t> mActiveAssistantUids;
std::vector<uid_t> mA11yUids;
@@ -641,8 +645,8 @@
int mCommand; // SET_VOLUME, SET_PARAMETERS...
nsecs_t mTime; // time stamp
- Mutex mLock; // mutex associated to mCond
- Condition mCond; // condition for status return
+ audio_utils::mutex mMutex{audio_utils::MutexOrder::kAudioCommand_Mutex};
+ audio_utils::condition_variable mCond; // condition for status return
status_t mStatus; // command status
bool mWaitStatus; // true if caller is waiting for status
sp<AudioCommandData> mParam; // command specific parameter data
@@ -730,8 +734,8 @@
bool mSuspended;
};
- Mutex mLock;
- Condition mWaitWorkCV;
+ mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kCommandThread_Mutex};
+ audio_utils::condition_variable mWaitWorkCV;
Vector < sp<AudioCommand> > mAudioCommands; // list of pending commands
sp<AudioCommand> mLastCommand; // last processed command (used by dump)
String8 mName; // string used by wake lock fo delayed commands
@@ -996,12 +1000,12 @@
* @return the number of active tracks.
*/
size_t countActiveClientsOnOutput_l(
- audio_io_handle_t output, bool spatializedOnly = true) REQUIRES(mLock);
+ audio_io_handle_t output, bool spatializedOnly = true) REQUIRES(mMutex);
- mutable Mutex mLock; // prevents concurrent access to AudioPolicy manager functions changing
- // device connection state or routing
- // Note: lock acquisition order is always mLock > mEffectsLock:
- // mLock protects AudioPolicyManager methods that can call into audio flinger
+ mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kAudioPolicyService_Mutex};
+ // prevents concurrent access to AudioPolicy manager functions changing
+ // device connection state or routing.
+ // mMutex protects AudioPolicyManager methods that can call into audio flinger
// and possibly back in to audio policy service and acquire mEffectsLock.
sp<AudioCommandThread> mAudioCommandThread; // audio commands thread
sp<AudioCommandThread> mOutputCommandThread; // process stop and release output
@@ -1009,29 +1013,30 @@
AudioPolicyClient *mAudioPolicyClient;
std::vector<audio_usage_t> mSupportedSystemUsages;
- Mutex mNotificationClientsLock;
+ mutable audio_utils::mutex mNotificationClientsMutex{
+ audio_utils::MutexOrder::kAudioPolicyService_NotificationClientsMutex};
DefaultKeyedVector<int64_t, sp<NotificationClient>> mNotificationClients
- GUARDED_BY(mNotificationClientsLock);
+ GUARDED_BY(mNotificationClientsMutex);
// Manage all effects configured in audio_effects.conf
- // never hold AudioPolicyService::mLock when calling AudioPolicyEffects methods as
+ // never hold AudioPolicyService::mMutex when calling AudioPolicyEffects methods as
// those can call back into AudioPolicyService methods and try to acquire the mutex
- sp<AudioPolicyEffects> mAudioPolicyEffects GUARDED_BY(mLock);
- audio_mode_t mPhoneState GUARDED_BY(mLock);
- uid_t mPhoneStateOwnerUid GUARDED_BY(mLock);
+ sp<AudioPolicyEffects> mAudioPolicyEffects GUARDED_BY(mMutex);
+ audio_mode_t mPhoneState GUARDED_BY(mMutex);
+ uid_t mPhoneStateOwnerUid GUARDED_BY(mMutex);
- sp<UidPolicy> mUidPolicy GUARDED_BY(mLock);
- sp<SensorPrivacyPolicy> mSensorPrivacyPolicy GUARDED_BY(mLock);
+ sp<UidPolicy> mUidPolicy GUARDED_BY(mMutex);
+ sp<SensorPrivacyPolicy> mSensorPrivacyPolicy GUARDED_BY(mMutex);
DefaultKeyedVector<audio_port_handle_t, sp<AudioRecordClient>> mAudioRecordClients
- GUARDED_BY(mLock);
+ GUARDED_BY(mMutex);
DefaultKeyedVector<audio_port_handle_t, sp<AudioPlaybackClient>> mAudioPlaybackClients
- GUARDED_BY(mLock);
+ GUARDED_BY(mMutex);
MediaPackageManager mPackageManager; // To check allowPlaybackCapture
CaptureStateNotifier mCaptureStateNotifier;
- // created in onFirstRef() and never cleared: does not need to be guarded by mLock
+ // created in onFirstRef() and never cleared: does not need to be guarded by mMutex
sp<Spatializer> mSpatializer;
void *mLibraryHandle = nullptr;
diff --git a/services/audiopolicy/service/Spatializer.cpp b/services/audiopolicy/service/Spatializer.cpp
index 83030a3..cc191ca 100644
--- a/services/audiopolicy/service/Spatializer.cpp
+++ b/services/audiopolicy/service/Spatializer.cpp
@@ -229,7 +229,7 @@
return;
}
auto latencyModesStrs = android::sysprop::BluetoothProperties::dsa_transport_preference();
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
// First load preferred low latency modes ordered from the property
for (auto str : latencyModesStrs) {
if (!str.has_value()) continue;
@@ -461,7 +461,7 @@
/** Gets the channel mask, sampling rate and format set for the spatializer input. */
audio_config_base_t Spatializer::getAudioInConfig() const {
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
// For now use highest supported channel count
config.channel_mask = getMaxChannelMask(mChannelMasks, FCC_LIMIT);
@@ -470,7 +470,7 @@
status_t Spatializer::registerCallback(
const sp<media::INativeSpatializerCallback>& callback) {
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (callback == nullptr) {
return BAD_VALUE;
}
@@ -498,7 +498,7 @@
// IBinder::DeathRecipient
void Spatializer::binderDied(__unused const wp<IBinder> &who) {
{
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
mLevel = Spatialization::Level::NONE;
mSpatializerCallback.clear();
}
@@ -527,7 +527,7 @@
sp<media::INativeSpatializerCallback> callback;
bool levelChanged = false;
{
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
levelChanged = mLevel != level;
mLevel = level;
callback = mSpatializerCallback;
@@ -551,7 +551,7 @@
if (level == nullptr) {
return binderStatusFromStatusT(BAD_VALUE);
}
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
*level = mLevel;
ALOGV("%s level %d", __func__, (int)*level);
return Status::ok();
@@ -562,14 +562,14 @@
if (supports == nullptr) {
return binderStatusFromStatusT(BAD_VALUE);
}
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
*supports = mSupportsHeadTracking;
return Status::ok();
}
Status Spatializer::getSupportedHeadTrackingModes(
std::vector<HeadTracking::Mode>* modes) {
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
ALOGV("%s", __func__);
if (modes == nullptr) {
return binderStatusFromStatusT(BAD_VALUE);
@@ -585,7 +585,7 @@
return binderStatusFromStatusT(INVALID_OPERATION);
}
mLocalLog.log("%s with %s", __func__, ToString(mode).c_str());
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
switch (mode) {
case HeadTracking::Mode::OTHER:
return binderStatusFromStatusT(BAD_VALUE);
@@ -610,7 +610,7 @@
if (mode == nullptr) {
return binderStatusFromStatusT(BAD_VALUE);
}
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
*mode = mActualHeadTrackingMode;
ALOGV("%s mode %d", __func__, (int)*mode);
return Status::ok();
@@ -620,7 +620,7 @@
if (!mSupportsHeadTracking) {
return binderStatusFromStatusT(INVALID_OPERATION);
}
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (mPoseController != nullptr) {
mPoseController->recenter();
}
@@ -637,7 +637,7 @@
ALOGW("Invalid screenToStage vector.");
return binderStatusFromStatusT(BAD_VALUE);
}
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (mPoseController != nullptr) {
mLocalLog.log("%s with screenToStage %s", __func__,
media::VectorRecorder::toString<float>(screenToStage).c_str());
@@ -650,7 +650,7 @@
ALOGV("%s", __func__);
bool levelChanged = false;
{
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (mSpatializerCallback == nullptr) {
return binderStatusFromStatusT(INVALID_OPERATION);
}
@@ -674,7 +674,7 @@
if (!mSupportsHeadTracking) {
return binderStatusFromStatusT(INVALID_OPERATION);
}
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (mHeadSensor != sensorHandle) {
mLocalLog.log("%s with 0x%08x", __func__, sensorHandle);
mHeadSensor = sensorHandle;
@@ -689,7 +689,7 @@
if (!mSupportsHeadTracking) {
return binderStatusFromStatusT(INVALID_OPERATION);
}
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (mScreenSensor != sensorHandle) {
mLocalLog.log("%s with 0x%08x", __func__, sensorHandle);
mScreenSensor = sensorHandle;
@@ -708,7 +708,7 @@
// It is possible due to numerical inaccuracies to exceed the boundaries of 0 to 2 * M_PI.
ALOGI_IF(angle != physicalToLogicalAngle,
"%s: clamping %f to %f", __func__, physicalToLogicalAngle, angle);
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
mDisplayOrientation = angle;
if (mPoseController != nullptr) {
// This turns on the rate-limiter.
@@ -728,7 +728,7 @@
// It is possible due to numerical inaccuracies to exceed the boundaries of 0 to 2 * M_PI.
ALOGI_IF(angle != hingeAngle,
"%s: clamping %f to %f", __func__, hingeAngle, angle);
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
mHingeAngle = angle;
if (mEngine != nullptr) {
setEffectParameter_l(SPATIALIZER_PARAM_HINGE_ANGLE, std::vector<float>{angle});
@@ -739,7 +739,7 @@
Status Spatializer::setFoldState(bool folded) {
ALOGV("%s foldState %d", __func__, (int)folded);
mLocalLog.log("%s with %d", __func__, (int)folded);
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
mFoldedState = folded;
if (mEngine != nullptr) {
// we don't suppress multiple calls with the same folded state - that's
@@ -761,7 +761,7 @@
Status Spatializer::registerHeadTrackingCallback(
const sp<media::ISpatializerHeadTrackingCallback>& callback) {
ALOGV("%s callback %p", __func__, callback.get());
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (!mSupportsHeadTracking) {
return binderStatusFromStatusT(INVALID_OPERATION);
}
@@ -771,7 +771,7 @@
Status Spatializer::setParameter(int key, const std::vector<unsigned char>& value) {
ALOGV("%s key %d", __func__, key);
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
status_t status = INVALID_OPERATION;
if (mEngine != nullptr) {
status = setEffectParameter_l(key, value);
@@ -785,7 +785,7 @@
if (value == nullptr) {
return binderStatusFromStatusT(BAD_VALUE);
}
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
status_t status = INVALID_OPERATION;
if (mEngine != nullptr) {
ALOGV("%s key %d mEngine %p", __func__, key, mEngine.get());
@@ -799,7 +799,7 @@
if (output == nullptr) {
binderStatusFromStatusT(BAD_VALUE);
}
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
*output = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_io_handle_t_int32_t(mOutput));
ALOGV("%s got output %d", __func__, *output);
return Status::ok();
@@ -837,7 +837,7 @@
ALOGV("%s", __func__);
sp<media::ISpatializerHeadTrackingCallback> callback;
{
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
callback = mHeadTrackingCallback;
if (mEngine != nullptr) {
setEffectParameter_l(SPATIALIZER_PARAM_HEAD_TO_STAGE, headToStage);
@@ -865,7 +865,7 @@
sp<media::ISpatializerHeadTrackingCallback> callback;
HeadTracking::Mode spatializerMode;
{
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (!mSupportsHeadTracking) {
spatializerMode = HeadTracking::Mode::DISABLED;
} else {
@@ -932,7 +932,7 @@
sp<media::INativeSpatializerCallback> callback;
{
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
ALOGV("%s output %d mOutput %d", __func__, (int)output, (int)mOutput);
mLocalLog.log("%s with output %d tracks %zu (mOutput %d)", __func__, (int)output,
numActiveTracks, (int)mOutput);
@@ -998,7 +998,7 @@
sp<media::INativeSpatializerCallback> callback;
{
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
mLocalLog.log("%s with output %d tracks %zu", __func__, (int)mOutput, mNumActiveTracks);
ALOGV("%s mOutput %d", __func__, (int)mOutput);
if (mOutput == AUDIO_IO_HANDLE_NONE) {
@@ -1032,7 +1032,7 @@
void Spatializer::onSupportedLatencyModesChangedMsg(
audio_io_handle_t output, std::vector<audio_latency_mode_t>&& modes) {
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
ALOGV("%s output %d mOutput %d num modes %zu",
__func__, (int)output, (int)mOutput, modes.size());
if (output == mOutput) {
@@ -1043,7 +1043,7 @@
}
void Spatializer::updateActiveTracks(size_t numActiveTracks) {
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (mNumActiveTracks != numActiveTracks) {
mLocalLog.log("%s from %zu to %zu", __func__, mNumActiveTracks, numActiveTracks);
mNumActiveTracks = numActiveTracks;
@@ -1174,7 +1174,7 @@
void Spatializer::calculateHeadPose() {
ALOGV("%s", __func__);
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
if (mPoseController != nullptr) {
mPoseController->calculateAsync();
}
@@ -1193,7 +1193,7 @@
bool needUnlock = false;
prefixSpace += ' ';
- if (!mLock.try_lock()) {
+ if (!mMutex.try_lock()) {
// dumpsys even try_lock failed, information dump can be useful although may not accurate
ss.append(prefixSpace).append("try_lock failed, dumpsys below maybe INACCURATE!\n");
} else {
@@ -1258,7 +1258,7 @@
}
if (needUnlock) {
- mLock.unlock();
+ mMutex.unlock();
}
return ss;
}
diff --git a/services/audiopolicy/service/Spatializer.h b/services/audiopolicy/service/Spatializer.h
index 123517e..24788dc 100644
--- a/services/audiopolicy/service/Spatializer.h
+++ b/services/audiopolicy/service/Spatializer.h
@@ -23,6 +23,7 @@
#include <android/media/audio/common/AudioLatencyMode.h>
#include <android/media/audio/common/HeadTracking.h>
#include <android/media/audio/common/Spatialization.h>
+#include <audio_utils/mutex.h>
#include <audio_utils/SimpleLog.h>
#include <math.h>
#include <media/AudioEffect.h>
@@ -148,7 +149,7 @@
/** Level getter for use by local classes. */
media::audio::common::Spatialization::Level getLevel() const {
- std::lock_guard lock(mLock);
+ audio_utils::lock_guard lock(mMutex);
return mLevel;
}
@@ -161,7 +162,7 @@
*/
audio_io_handle_t detachOutput();
/** Returns the output stream the spatializer is attached to. */
- audio_io_handle_t getOutput() const { std::lock_guard lock(mLock); return mOutput; }
+ audio_io_handle_t getOutput() const { audio_utils::lock_guard lock(mMutex); return mOutput; }
void updateActiveTracks(size_t numActiveTracks);
@@ -261,7 +262,7 @@
* according to values vector size.
*/
template<typename T>
- status_t setEffectParameter_l(uint32_t type, const std::vector<T>& values) REQUIRES(mLock) {
+ status_t setEffectParameter_l(uint32_t type, const std::vector<T>& values) REQUIRES(mMutex) {
static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values.size()];
@@ -286,7 +287,7 @@
* The variant is for compound parameters with two values of different base types
*/
template<typename P1, typename P2>
- status_t setEffectParameter_l(uint32_t type, const P1 val1, const P2 val2) REQUIRES(mLock) {
+ status_t setEffectParameter_l(uint32_t type, const P1 val1, const P2 val2) REQUIRES(mMutex) {
static_assert(sizeof(P1) <= sizeof(uint32_t), "The size of P1 must less than 32 bits");
static_assert(sizeof(P2) <= sizeof(uint32_t), "The size of P2 must less than 32 bits");
@@ -314,7 +315,7 @@
* by specifying values vector size.
*/
template<typename T>
- status_t getEffectParameter_l(uint32_t type, std::vector<T> *values) REQUIRES(mLock) {
+ status_t getEffectParameter_l(uint32_t type, std::vector<T> *values) REQUIRES(mMutex) {
static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values->size()];
@@ -345,7 +346,7 @@
* The variant is for compound parameters with two values of different base types
*/
template<typename P1, typename P2>
- status_t getEffectParameter_l(uint32_t type, P1 *val1, P2 *val2) REQUIRES(mLock) {
+ status_t getEffectParameter_l(uint32_t type, P1 *val1, P2 *val2) REQUIRES(mMutex) {
static_assert(sizeof(P1) <= sizeof(uint32_t), "The size of P1 must less than 32 bits");
static_assert(sizeof(P2) <= sizeof(uint32_t), "The size of P2 must less than 32 bits");
@@ -375,25 +376,25 @@
* spatializer state and playback activity and configures the pose controller
* accordingly.
*/
- void checkSensorsState_l() REQUIRES(mLock);
+ void checkSensorsState_l() REQUIRES(mMutex);
/**
* Checks if the head pose controller should be created or destroyed according
* to desired head tracking mode.
*/
- void checkPoseController_l() REQUIRES(mLock);
+ void checkPoseController_l() REQUIRES(mMutex);
/**
* Checks if the spatializer effect should be enabled based on
* playback activity and requested level.
*/
- void checkEngineState_l() REQUIRES(mLock);
+ void checkEngineState_l() REQUIRES(mMutex);
/**
* Reset head tracking mode and recenter pose in engine: Called when the head tracking
* is disabled.
*/
- void resetEngineHeadPose_l() REQUIRES(mLock);
+ void resetEngineHeadPose_l() REQUIRES(mMutex);
/** Read bluetooth.core.le.dsa_transport_preference property and populate the ordered list of
* preferred low latency modes in mOrderedLowLatencyModes.
@@ -406,7 +407,7 @@
* Note: Because MODE_FREE is not in mOrderedLowLatencyModes, it will always be at
* the end of the list.
*/
- void sortSupportedLatencyModes_l() REQUIRES(mLock);
+ void sortSupportedLatencyModes_l() REQUIRES(mMutex);
/**
* Called after enabling head tracking in the spatializer engine to indicate which
@@ -415,14 +416,14 @@
* When the connection mode is direct to the sensor, the sensor ID is also communicated
* to the spatializer engine.
*/
- void setEngineHeadtrackingConnectionMode_l() REQUIRES(mLock);
+ void setEngineHeadtrackingConnectionMode_l() REQUIRES(mMutex);
/**
* Select the desired head tracking connection mode for the spatializer engine among the list
* stored in mSupportedHeadtrackingConnectionModes at init time.
* Also returns the desired low latency mode according to selected connection mode.
*/
- audio_latency_mode_t selectHeadtrackingConnectionMode_l() REQUIRES(mLock);
+ audio_latency_mode_t selectHeadtrackingConnectionMode_l() REQUIRES(mMutex);
/** Effect engine descriptor */
const effect_descriptor_t mEngineDescriptor;
@@ -435,48 +436,48 @@
const std::string mMetricsId = kDefaultMetricsId;
/** Mutex protecting internal state */
- mutable std::mutex mLock;
+ mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kSpatializer_Mutex};
/** Client AudioEffect for the engine */
- sp<AudioEffect> mEngine GUARDED_BY(mLock);
+ sp<AudioEffect> mEngine GUARDED_BY(mMutex);
/** Output stream the spatializer mixer thread is attached to */
- audio_io_handle_t mOutput GUARDED_BY(mLock) = AUDIO_IO_HANDLE_NONE;
+ audio_io_handle_t mOutput GUARDED_BY(mMutex) = AUDIO_IO_HANDLE_NONE;
/** Callback interface to the client (AudioService) controlling this`Spatializer */
- sp<media::INativeSpatializerCallback> mSpatializerCallback GUARDED_BY(mLock);
+ sp<media::INativeSpatializerCallback> mSpatializerCallback GUARDED_BY(mMutex);
/** Callback interface for head tracking */
- sp<media::ISpatializerHeadTrackingCallback> mHeadTrackingCallback GUARDED_BY(mLock);
+ sp<media::ISpatializerHeadTrackingCallback> mHeadTrackingCallback GUARDED_BY(mMutex);
/** Requested spatialization level */
- media::audio::common::Spatialization::Level mLevel GUARDED_BY(mLock) =
+ media::audio::common::Spatialization::Level mLevel GUARDED_BY(mMutex) =
media::audio::common::Spatialization::Level::NONE;
/** Control logic for head-tracking, etc. */
- std::shared_ptr<SpatializerPoseController> mPoseController GUARDED_BY(mLock);
+ std::shared_ptr<SpatializerPoseController> mPoseController GUARDED_BY(mMutex);
/** Last requested head tracking mode */
- media::HeadTrackingMode mDesiredHeadTrackingMode GUARDED_BY(mLock)
+ media::HeadTrackingMode mDesiredHeadTrackingMode GUARDED_BY(mMutex)
= media::HeadTrackingMode::STATIC;
/** Last-reported actual head-tracking mode. */
- media::audio::common::HeadTracking::Mode mActualHeadTrackingMode GUARDED_BY(mLock)
+ media::audio::common::HeadTracking::Mode mActualHeadTrackingMode GUARDED_BY(mMutex)
= media::audio::common::HeadTracking::Mode::DISABLED;
/** Selected Head pose sensor */
- int32_t mHeadSensor GUARDED_BY(mLock) = SpatializerPoseController::INVALID_SENSOR;
+ int32_t mHeadSensor GUARDED_BY(mMutex) = SpatializerPoseController::INVALID_SENSOR;
/** Selected Screen pose sensor */
- int32_t mScreenSensor GUARDED_BY(mLock) = SpatializerPoseController::INVALID_SENSOR;
+ int32_t mScreenSensor GUARDED_BY(mMutex) = SpatializerPoseController::INVALID_SENSOR;
/** Last display orientation received */
- float mDisplayOrientation GUARDED_BY(mLock) = 0.f; // aligned to natural up orientation.
+ float mDisplayOrientation GUARDED_BY(mMutex) = 0.f; // aligned to natural up orientation.
/** Last folded state */
- bool mFoldedState GUARDED_BY(mLock) = false; // foldable: true means folded.
+ bool mFoldedState GUARDED_BY(mMutex) = false; // foldable: true means folded.
/** Last hinge angle */
- float mHingeAngle GUARDED_BY(mLock) = 0.f; // foldable: 0.f is closed, M_PI flat open.
+ float mHingeAngle GUARDED_BY(mMutex) = 0.f; // foldable: 0.f is closed, M_PI flat open.
std::vector<media::audio::common::Spatialization::Level> mLevels;
std::vector<media::audio::common::HeadTracking::Mode> mHeadTrackingModes;
@@ -497,8 +498,8 @@
sp<ALooper> mLooper;
sp<EngineCallbackHandler> mHandler;
- size_t mNumActiveTracks GUARDED_BY(mLock) = 0;
- std::vector<audio_latency_mode_t> mSupportedLatencyModes GUARDED_BY(mLock);
+ size_t mNumActiveTracks GUARDED_BY(mMutex) = 0;
+ std::vector<audio_latency_mode_t> mSupportedLatencyModes GUARDED_BY(mMutex);
/** preference order for low latency modes according to persist.bluetooth.hid.transport */
std::vector<audio_latency_mode_t> mOrderedLowLatencyModes;
/** string to latency mode map used to parse bluetooth.core.le.dsa_transport_preference */
@@ -514,10 +515,10 @@
* Dump to local log with max/average pose angle every mPoseRecordThreshold.
*/
// Record one log line per second (up to mMaxLocalLogLine) to capture most recent sensor data.
- media::VectorRecorder mPoseRecorder GUARDED_BY(mLock) {
+ media::VectorRecorder mPoseRecorder GUARDED_BY(mMutex) {
6 /* vectorSize */, std::chrono::seconds(1), mMaxLocalLogLine, { 3 } /* delimiterIdx */};
// Record one log line per minute (up to mMaxLocalLogLine) to capture durable sensor data.
- media::VectorRecorder mPoseDurableRecorder GUARDED_BY(mLock) {
+ media::VectorRecorder mPoseDurableRecorder GUARDED_BY(mMutex) {
6 /* vectorSize */, std::chrono::minutes(1), mMaxLocalLogLine, { 3 } /* delimiterIdx */};
}; // Spatializer
diff --git a/services/mediametrics/AudioPowerUsage.cpp b/services/mediametrics/AudioPowerUsage.cpp
index 630a436..7dc445b 100644
--- a/services/mediametrics/AudioPowerUsage.cpp
+++ b/services/mediametrics/AudioPowerUsage.cpp
@@ -549,7 +549,7 @@
int slot = 1;
std::stringstream ss;
- ss << "AudioPowerUsage:\n";
+ ss << "AudioPowerUsage interval " << mIntervalHours << " hours:\n";
for (const auto &item : mItems) {
if (slot >= limit - 1) {
ss << "-- AudioPowerUsage may be truncated!\n";
diff --git a/services/mediametrics/include/mediametricsservice/TimedAction.h b/services/mediametrics/include/mediametricsservice/TimedAction.h
index c7ef585..8b53ded 100644
--- a/services/mediametrics/include/mediametricsservice/TimedAction.h
+++ b/services/mediametrics/include/mediametricsservice/TimedAction.h
@@ -25,6 +25,12 @@
namespace android::mediametrics {
class TimedAction {
+ // Use system_clock instead of steady_clock to include suspend time.
+ using TimerClock = class std::chrono::system_clock;
+
+ // Define granularity of wakeup to prevent delayed events if
+ // device is suspended.
+ static constexpr auto kWakeupInterval = std::chrono::minutes(3);
public:
TimedAction() : mThread{[this](){threadLoop();}} {}
@@ -35,7 +41,7 @@
// TODO: return a handle for cancelling the action?
template <typename T> // T is in units of std::chrono::duration.
void postIn(const T& time, std::function<void()> f) {
- postAt(std::chrono::steady_clock::now() + time, f);
+ postAt(TimerClock::now() + time, f);
}
template <typename T> // T is in units of std::chrono::time_point
@@ -75,16 +81,21 @@
void threadLoop() NO_THREAD_SAFETY_ANALYSIS { // thread safety doesn't cover unique_lock
std::unique_lock l(mLock);
while (!mQuit) {
- auto sleepUntilTime = std::chrono::time_point<std::chrono::steady_clock>::max();
+ auto sleepUntilTime = std::chrono::time_point<TimerClock>::max();
if (!mMap.empty()) {
sleepUntilTime = mMap.begin()->first;
- if (sleepUntilTime <= std::chrono::steady_clock::now()) {
+ const auto now = TimerClock::now();
+ if (sleepUntilTime <= now) {
auto node = mMap.extract(mMap.begin()); // removes from mMap.
l.unlock();
node.mapped()();
l.lock();
continue;
}
+ // Bionic uses CLOCK_MONOTONIC for its pthread_mutex regardless
+ // of REALTIME specification, use kWakeupInterval to ensure minimum
+ // granularity if suspended.
+ sleepUntilTime = std::min(sleepUntilTime, now + kWakeupInterval);
}
mCondition.wait_until(l, sleepUntilTime);
}
@@ -93,7 +104,7 @@
mutable std::mutex mLock;
std::condition_variable mCondition GUARDED_BY(mLock);
bool mQuit GUARDED_BY(mLock) = false;
- std::multimap<std::chrono::time_point<std::chrono::steady_clock>, std::function<void()>>
+ std::multimap<std::chrono::time_point<TimerClock>, std::function<void()>>
mMap GUARDED_BY(mLock); // multiple functions could execute at the same time.
// needs to be initialized after the variables above, done in constructor initializer list.