diff --git a/frameworks/native/audioadapter/src/pulse_audio_service_adapter_impl.cpp b/frameworks/native/audioadapter/src/pulse_audio_service_adapter_impl.cpp index 70913cca4a3a97556ba69cb10e2807ca20c50c9b..b067333e4836d10caefa48c42727c4d05e262ccc 100644 --- a/frameworks/native/audioadapter/src/pulse_audio_service_adapter_impl.cpp +++ b/frameworks/native/audioadapter/src/pulse_audio_service_adapter_impl.cpp @@ -174,7 +174,7 @@ Fail: uint32_t PulseAudioServiceAdapterImpl::OpenAudioPort(string audioPortName, string moduleArgs) { - AUDIO_PRERELEASE_LOGI("OpenAudioPort enter."); + AUDIO_PRERELEASE_LOGI("Enter, port name: %{public}s", audioPortName.c_str()); AudioXCollie audioXCollie("PulseAudioServiceAdapterImpl::OpenAudioPort", PA_SERVICE_IMPL_TIMEOUT, [](void *) { AUDIO_ERR_LOG("OpenAudioPort timeout"); diff --git a/frameworks/native/audiocapturer/BUILD.gn b/frameworks/native/audiocapturer/BUILD.gn index c6620584685f3e85e1ba77a2388f80f8ae19a92f..84720390474a7695a999a426da8b94b89ca0bc47 100644 --- a/frameworks/native/audiocapturer/BUILD.gn +++ b/frameworks/native/audiocapturer/BUILD.gn @@ -34,6 +34,7 @@ config("audio_external_library_config") { "include", "../../../interfaces/inner_api/native/audiocapturer/include", "../../../interfaces/inner_api/native/audiocommon/include", + "../../../frameworks/native/audiodefinitions/include", "../../../frameworks/native/audiostream/include", "../../../services/audio_service/client/include", "../../../interfaces/kits/c/common", @@ -69,6 +70,7 @@ ohos_shared_library("audio_capturer") { deps = [ "../../../services/audio_policy:audio_policy_client", "../../../services/audio_service:audio_client", + "../audiodefinitions:audio_definitions", "../audioutils:audio_utils", ] diff --git a/frameworks/native/audiocapturer/include/audio_capturer_private.h b/frameworks/native/audiocapturer/include/audio_capturer_private.h index 0b64796a078bb9a8dfaa22d93548257c799a7c3e..cc297c2a909481db10db9621f7b94b8c622037df 100644 --- a/frameworks/native/audiocapturer/include/audio_capturer_private.h +++ b/frameworks/native/audiocapturer/include/audio_capturer_private.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 Huawei Device Co., Ltd. * 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 @@ -22,6 +22,7 @@ #include "audio_concurrency_callback.h" #include "audio_interrupt_callback.h" #include "i_audio_stream.h" +#include "audio_stream_descriptor.h" #include "audio_capturer_proxy_obj.h" namespace OHOS { @@ -126,8 +127,9 @@ public: private: int32_t CheckAndRestoreAudioCapturer(std::string callingFunc); int32_t InitAudioInterruptCallback(); + std::shared_ptr ConvertToStreamDescriptor(const AudioStreamParams &audioStreamParams); + void SetClientInfo(uint32_t flag, IAudioStream::StreamClass &streamClass); int32_t InitInputDeviceChangeCallback(); - IAudioStream::StreamClass GetTargetStreamClass(int32_t streamFlag); int32_t SetSwitchInfo(IAudioStream::SwitchInfo info, std::shared_ptr audioStream); void InitSwitchInfo(IAudioStream::StreamClass targetClass, IAudioStream::SwitchInfo &info); bool ContinueAfterConcede(IAudioStream::StreamClass &targetClass, RestoreInfo restoreInfo); @@ -150,6 +152,7 @@ private: CapturerState GetStatusInner() const; std::shared_ptr GetInnerStream() const; IAudioStream::StreamClass GetPreferredStreamClass(AudioStreamParams audioStreamParams); + IAudioStream::StreamClass SetCaptureInfo(AudioStreamParams &audioStreamParams); std::shared_ptr inputDeviceChangeCallback_ = nullptr; bool isSwitching_ = false; mutable std::shared_mutex switchStreamMutex_; diff --git a/frameworks/native/audiocapturer/src/audio_capturer.cpp b/frameworks/native/audiocapturer/src/audio_capturer.cpp index d8784c32526869479b6b5716571ed6ff4c7a978c..2a4b4194e993d4a0006ebe8f5171c48ea2bedd25 100644 --- a/frameworks/native/audiocapturer/src/audio_capturer.cpp +++ b/frameworks/native/audiocapturer/src/audio_capturer.cpp @@ -27,6 +27,7 @@ #include "audio_policy_manager.h" #include "media_monitor_manager.h" +#include "audio_stream_descriptor.h" namespace OHOS { namespace AudioStandard { @@ -48,6 +49,19 @@ std::map AudioCapturerPrivate::streamToSource_ = { {AudioStreamType::STREAM_SOURCE_VOICE_CALL, SourceType::SOURCE_TYPE_VOICE_CALL}, }; +static const std::map AUDIO_INPUT_FLAG_GROUP_MAP = { + {AUDIO_INPUT_FLAG_NORMAL, IAudioStream::StreamClass::PA_STREAM}, + {AUDIO_INPUT_FLAG_FAST, IAudioStream::StreamClass::FAST_STREAM}, + {AUDIO_INPUT_FLAG_VOIP_FAST, IAudioStream::StreamClass::VOIP_STREAM}, + {AUDIO_INPUT_FLAG_WAKEUP, IAudioStream::StreamClass::PA_STREAM}, +}; + +static const std::map INPUT_ROUTE_TO_STREAM_MAP = { + {AUDIO_OUTPUT_FLAG_NORMAL, AUDIO_FLAG_NORMAL}, + {AUDIO_OUTPUT_FLAG_DIRECT, AUDIO_FLAG_DIRECT}, + {AUDIO_OUTPUT_FLAG_FAST, AUDIO_FLAG_MMAP}, +}; + AudioCapturer::~AudioCapturer() = default; AudioCapturerPrivate::~AudioCapturerPrivate() @@ -141,6 +155,7 @@ std::shared_ptr AudioCapturer::CreateCapturer(const AudioCapturer params.audioEncoding = capturerOptions.streamInfo.encoding; params.channelLayout = capturerOptions.streamInfo.channelLayout; auto capturer = std::make_shared(audioStreamType, appInfo, false); + if (capturer == nullptr) { AudioCapturer::SendCapturerCreateError(sourceType, ERR_OPERATION_FAILED); AUDIO_ERR_LOG("Failed to create capturer object"); @@ -265,19 +280,18 @@ int32_t AudioCapturerPrivate::SetParams(const AudioCapturerParams params) std::shared_lock lockShared(capturerMutex_); AudioStreamParams audioStreamParams = ConvertToAudioStreamParams(params); - - IAudioStream::StreamClass streamClass = IAudioStream::PA_STREAM; - if (capturerInfo_.sourceType != SOURCE_TYPE_PLAYBACK_CAPTURE) { -#ifdef SUPPORT_LOW_LATENCY - streamClass = GetPreferredStreamClass(audioStreamParams); -#else - capturerInfo_.originalFlag = AUDIO_FLAG_FORCED_NORMAL; - capturerInfo_.capturerFlags = AUDIO_FLAG_NORMAL; - streamClass = IAudioStream::PA_STREAM; -#endif - } - ActivateAudioConcurrency(streamClass); - + IAudioStream::StreamClass streamClass = SetCaptureInfo(audioStreamParams); + + // Create Client + std::shared_ptr streamDesc = ConvertToStreamDescriptor(audioStreamParams); + uint32_t flag = AUDIO_INPUT_FLAG_NORMAL; + int32_t ret = AudioPolicyManager::GetInstance().CreateCapturerClient( + streamDesc, flag, audioStreamParams.originalSessionId); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "CreateRendererClient failed"); + AUDIO_INFO_LOG("StreamClientState for Capturer::CreateClient. id %{public}u, flag :%{public}u", + audioStreamParams.originalSessionId, flag); + + SetClientInfo(flag, streamClass); // check AudioStreamParams for fast stream if (audioStream_ == nullptr) { audioStream_ = IAudioStream::GetRecordStream(streamClass, audioStreamParams, audioStreamType_, @@ -285,7 +299,7 @@ int32_t AudioCapturerPrivate::SetParams(const AudioCapturerParams params) CHECK_AND_RETURN_RET_LOG(audioStream_ != nullptr, ERR_INVALID_PARAM, "SetParams GetRecordStream faied."); AUDIO_INFO_LOG("IAudioStream::GetStream success"); } - int32_t ret = InitAudioStream(audioStreamParams); + ret = InitAudioStream(audioStreamParams); // When the fast stream creation fails, a normal stream is created if (ret != SUCCESS && streamClass == IAudioStream::FAST_STREAM) { AUDIO_INFO_LOG("Create fast Stream fail, record by normal stream"); @@ -315,6 +329,58 @@ int32_t AudioCapturerPrivate::SetParams(const AudioCapturerParams params) return InitAudioInterruptCallback(); } +IAudioStream::StreamClass AudioCapturerPrivate::SetCaptureInfo(AudioStreamParams &audioStreamParams) +{ + IAudioStream::StreamClass streamClass = IAudioStream::PA_STREAM; + if (capturerInfo_.sourceType != SOURCE_TYPE_PLAYBACK_CAPTURE) { +#ifdef SUPPORT_LOW_LATENCY + streamClass = GetPreferredStreamClass(audioStreamParams); +#else + capturerInfo_.originalFlag = AUDIO_FLAG_FORCED_NORMAL; + capturerInfo_.capturerFlags = AUDIO_FLAG_NORMAL; + streamClass = IAudioStream::PA_STREAM; +#endif + } + return streamClass; +} + +std::shared_ptr AudioCapturerPrivate::ConvertToStreamDescriptor( + const AudioStreamParams &audioStreamParams) +{ + std::shared_ptr streamDesc = std::make_shared(); + streamDesc->streamInfo_.format = static_cast(audioStreamParams.format); + streamDesc->streamInfo_.samplingRate = static_cast(audioStreamParams.samplingRate); + streamDesc->streamInfo_.channels = static_cast(audioStreamParams.channels); + streamDesc->streamInfo_.encoding = static_cast(audioStreamParams.encoding); + streamDesc->streamInfo_.channelLayout = static_cast(audioStreamParams.channelLayout); + streamDesc->audioMode_ = AUDIO_MODE_RECORD; + streamDesc->startTimeStamp_ = ClockTime::GetCurNano(); + streamDesc->capturerInfo_ = capturerInfo_; + streamDesc->appInfo_ = appInfo_; + streamDesc->callerUid_ = getuid(); + return streamDesc; +} + +void AudioCapturerPrivate::SetClientInfo(uint32_t flag, IAudioStream::StreamClass &streamClass) +{ + if (flag & AUDIO_INPUT_FLAG_FAST) { + if (flag & AUDIO_INPUT_FLAG_VOIP) { + streamClass = IAudioStream::StreamClass::VOIP_STREAM; + capturerInfo_.originalFlag = AUDIO_FLAG_VOIP_FAST; + capturerInfo_.capturerFlags = AUDIO_FLAG_VOIP_FAST; + capturerInfo_.pipeType = PIPE_TYPE_CALL_IN; + } else { + streamClass = IAudioStream::StreamClass::FAST_STREAM; + capturerInfo_.capturerFlags = AUDIO_FLAG_MMAP; + capturerInfo_.pipeType = PIPE_TYPE_LOWLATENCY_IN; + } + } else { + streamClass = IAudioStream::StreamClass::PA_STREAM; + capturerInfo_.capturerFlags = AUDIO_FLAG_NORMAL; + capturerInfo_.pipeType = PIPE_TYPE_NORMAL_IN; + } +} + int32_t AudioCapturerPrivate::InitInputDeviceChangeCallback() { CHECK_AND_RETURN_RET_LOG(GetCurrentInputDevicesInner(currentDeviceInfo_) == SUCCESS, ERROR, @@ -564,26 +630,6 @@ void AudioCapturerPrivate::UnsetCapturerPeriodPositionCallback() currentStream->UnsetCapturerPeriodPositionCallback(); } -IAudioStream::StreamClass AudioCapturerPrivate::GetTargetStreamClass(int32_t streamFlag) -{ - IAudioStream::StreamClass targetClass = IAudioStream::PA_STREAM; - switch (streamFlag) { - case AUDIO_FLAG_NORMAL: - capturerInfo_.capturerFlags = AUDIO_FLAG_NORMAL; - targetClass = IAudioStream::PA_STREAM; - break; - case AUDIO_FLAG_MMAP: - capturerInfo_.capturerFlags = AUDIO_FLAG_MMAP; - targetClass = IAudioStream::FAST_STREAM; - break; - case AUDIO_FLAG_VOIP_FAST: - capturerInfo_.capturerFlags = AUDIO_FLAG_VOIP_FAST; - targetClass = IAudioStream::VOIP_STREAM; - break; - } - return targetClass; -} - int32_t AudioCapturerPrivate::CheckAndRestoreAudioCapturer(std::string callingFunc) { std::lock_guard lock(capturerMutex_); @@ -602,7 +648,8 @@ int32_t AudioCapturerPrivate::CheckAndRestoreAudioCapturer(std::string callingFu // Get restore info and target stream class for switching. RestoreInfo restoreInfo; audioStream_->GetRestoreInfo(restoreInfo); - IAudioStream::StreamClass targetClass = GetTargetStreamClass(restoreInfo.targetStreamFlag); + IAudioStream::StreamClass targetClass = IAudioStream::StreamClass::PA_STREAM; + SetClientInfo(restoreInfo.routeFlag, targetClass); // Block interrupt calback, avoid pausing wrong stream. std::shared_ptr interruptCbImpl = nullptr; @@ -989,22 +1036,6 @@ int32_t AudioCapturerPrivate::SetCaptureMode(AudioCaptureMode captureMode) audioCaptureMode_ = captureMode; std::shared_ptr currentStream = GetInnerStream(); CHECK_AND_RETURN_RET_LOG(currentStream != nullptr, ERROR_ILLEGAL_STATE, "audioStream_ is nullptr"); - if (capturerInfo_.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION && captureMode == CAPTURE_MODE_CALLBACK && - AudioPolicyManager::GetInstance().GetPreferredInputStreamType(capturerInfo_) == AUDIO_FLAG_VOIP_FAST && - firstConcurrencyResult_ == SUCCESS) { - AUDIO_INFO_LOG("Switch to fast voip stream"); - uint32_t sessionId = 0; - int32_t ret = currentStream->GetAudioSessionID(sessionId); - CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Get audio session Id failed"); - RestoreInfo restoreInfo; - if (!SwitchToTargetStream(IAudioStream::VOIP_STREAM, restoreInfo)) { - AUDIO_ERR_LOG("Switch to target stream failed"); - return ERROR; - } - // audioStream_ has been updated by SwitchToTargetStream. Update currentStream before SetRenderMode. - currentStream = GetInnerStream(); - } - return currentStream->SetCaptureMode(captureMode); } @@ -1453,6 +1484,7 @@ void AudioCapturerPrivate::HandleAudioInterruptWhenServerDied() void AudioCapturerPrivate::ActivateAudioConcurrency(IAudioStream::StreamClass &streamClass) { + AUDIO_INFO_LOG("in"); capturerInfo_.pipeType = PIPE_TYPE_NORMAL_IN; if (capturerInfo_.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) { capturerInfo_.pipeType = PIPE_TYPE_CALL_IN; diff --git a/frameworks/native/audiodefinitions/BUILD.gn b/frameworks/native/audiodefinitions/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c15ed8f4eea05ec2e0bea52c524ebe312f90e29a --- /dev/null +++ b/frameworks/native/audiodefinitions/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# 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. + +import("//build/ohos.gni") +import("../../../config.gni") +config("audio_utils_public_config") { + include_dirs = [ "./include" ] + + cflags_cc = [ "-std=c++20" ] +} + +ohos_shared_library("audio_definitions") { + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + cfi_vcall_icall_only = true + debug = false + } + public_configs = [ ":audio_utils_public_config" ] + install_enable = true + include_dirs = [ + "./include", + "../../../interfaces/inner_api/native/audiocommon/include", + "../../../services/audio_policy/server/include/service/common/", + ] + + sources = [ + "../../../services/audio_policy/server/src/service/device/audio_device_descriptor.cpp", + "./src/audio_pipe_info.cpp", + "./src/audio_stream_descriptor.cpp", + ] + + public_external_deps = [ "bounds_checking_function:libsec_shared" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [] + + if (build_variant == "user") { + defines += [ "AUDIO_BUILD_VARIANT_USER" ] + } else if (build_variant == "root") { + defines += [ "AUDIO_BUILD_VARIANT_ROOT" ] + } + + subsystem_name = "multimedia" + innerapi_tags = [ "platformsdk_indirect" ] + part_name = "audio_framework" +} diff --git a/frameworks/native/audiodefinitions/include/audio_pipe_info.h b/frameworks/native/audiodefinitions/include/audio_pipe_info.h new file mode 100644 index 0000000000000000000000000000000000000000..202dba43cf41cd3ccdccf460266e1aa6aeb44241 --- /dev/null +++ b/frameworks/native/audiodefinitions/include/audio_pipe_info.h @@ -0,0 +1,64 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef PIPE_INFO_H +#define PIPE_INFO_H +#define HDI_INVALID_ID 0xFFFFFFFF + +#include +#include "parcel.h" + +#include "audio_module_info.h" +#include "audio_stream_descriptor.h" + +namespace OHOS { +namespace AudioStandard { + +enum AudioPipeAction { + PIPE_ACTION_DEFAULT = 0, + PIPE_ACTION_NEW, + PIPE_ACTION_UPDATE, + PIPE_ACTION_RELOAD, +}; + +class AudioPipeInfo { +public: + uint32_t id_ = HDI_INVALID_ID; + + uint32_t paIndex_ = 0; + + AudioPipeRole pipeRole_ = PIPE_ROLE_OUTPUT; + + uint32_t routeFlag_ = 0; + + std::string adapterName_ = ""; + + AudioModuleInfo moduleInfo_ = {}; + + AudioPipeAction pipeAction_ = PIPE_ACTION_DEFAULT; + + std::vector> streamDescriptors_ = {}; + + std::unordered_map> streamDescMap_ = {}; + + AudioPipeInfo(); + + virtual ~AudioPipeInfo(); + + AudioPipeInfo(const std::shared_ptr pipeInfo); +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // PIPE_INFO_H diff --git a/frameworks/native/audiodefinitions/include/audio_stream_descriptor.h b/frameworks/native/audiodefinitions/include/audio_stream_descriptor.h new file mode 100644 index 0000000000000000000000000000000000000000..ca68e5f36f886e30bbb311f65c3af69d43d38c78 --- /dev/null +++ b/frameworks/native/audiodefinitions/include/audio_stream_descriptor.h @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef AUDIO_STREAM_DESCRIPTOR_H +#define AUDIO_STREAM_DESCRIPTOR_H + +#include +#include "parcel.h" +#include "audio_device_descriptor.h" +#include "audio_stream_enum.h" +#include "audio_info.h" + +namespace OHOS { +namespace AudioStandard { +enum AudioStreamAction : uint32_t { + AUDIO_STREAM_ACTION_DEFAULT = 0, + AUDIO_STREAM_ACTION_NEW, + AUDIO_STREAM_ACTION_MOVE, + AUDIO_STREAM_ACTION_RECREATE, +}; + +class AudioStreamDescriptor { +public: + AudioStreamInfo streamInfo_; + AudioMode audioMode_ = AUDIO_MODE_PLAYBACK; + AudioFlag audioFlag_ = AUDIO_FLAG_NONE; + uint32_t routeFlag_ = AUDIO_FLAG_NONE; + int64_t startTimeStamp_ = 0; + AudioRendererInfo rendererInfo_ = {}; + AudioCapturerInfo capturerInfo_ = {}; + AppInfo appInfo_ = {}; + uint32_t sessionId_ = 0; + int32_t callerUid_ = -1; + AudioStreamStatus streamStatus_ = STREAM_STATUS_NEW; + AudioStreamAction streamAction_ = AUDIO_STREAM_ACTION_DEFAULT; + mutable std::vector> oldDeviceDescs_ = {}; + mutable std::vector> newDeviceDescs_ = {}; + + AudioStreamDescriptor(); + virtual ~AudioStreamDescriptor(); + + bool Marshalling(Parcel &parcel) const; + void Unmarshalling(Parcel &parcel); + bool WriteDeviceDescVectorToParcel( + Parcel &parcel, std::vector> &descs) const; + void UnmarshallingDeviceDescVector(Parcel &parcel, std::vector> &descs); + void Dump(std::string &dumpString); +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // AUDIO_STREAM_DESCRIPTOR_H diff --git a/frameworks/native/audiodefinitions/include/audio_stream_enum.h b/frameworks/native/audiodefinitions/include/audio_stream_enum.h new file mode 100644 index 0000000000000000000000000000000000000000..f10d0dd78a7ba45339fccae7c0b81505637d67fd --- /dev/null +++ b/frameworks/native/audiodefinitions/include/audio_stream_enum.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef AUDIO_STREAM_ENUM_H +#define AUDIO_STREAM_ENUM_H + +#include + +enum StreamClass : uint32_t { + PA_STREAM = 0, + FAST_STREAM, + VOIP_STREAM, +}; + +enum AudioFlag : uint32_t { + AUDIO_FLAG_NONE = 0x0, // select + AUDIO_OUTPUT_FLAG_NORMAL = 0x1, // route + AUDIO_OUTPUT_FLAG_DIRECT = 0x2, // route + AUDIO_OUTPUT_FLAG_HD = 0x4, // select + AUDIO_OUTPUT_FLAG_MULTICHANNEL = 0x8, // select, route + AUDIO_OUTPUT_FLAG_LOWPOWER = 0x10, // select, route + AUDIO_OUTPUT_FLAG_FAST = 0x20, // select, route + AUDIO_OUTPUT_FLAG_VOIP = 0x40, // select + AUDIO_OUTPUT_FLAG_VOIP_FAST = 0x80, // select, route + AUDIO_OUTPUT_FLAG_HWDECODING = 0x100, // select, route + AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD = 0x200, // select, route + AUDIO_INPUT_FLAG_NORMAL = 0x1000, // route + AUDIO_INPUT_FLAG_FAST = 0x2000, // select, route + AUDIO_INPUT_FLAG_VOIP = 0x4000, // select + AUDIO_INPUT_FLAG_VOIP_FAST = 0x8000, // select, route + AUDIO_INPUT_FLAG_WAKEUP = 0x10000, // select, route + AUDIO_FLAG_MAX, +}; + +enum AudioStreamStatus : uint32_t { + STREAM_STATUS_NEW = 0, + STREAM_STATUS_STARTTING, + STREAM_STATUS_PAUSED, + STREAM_STATUS_STOPPED, + STREAM_STATUS_RELEASED, +}; +#endif // AUDIO_STREAM_ENUM_H \ No newline at end of file diff --git a/frameworks/native/audiodefinitions/include/hdi_adapter_type.h b/frameworks/native/audiodefinitions/include/hdi_adapter_type.h new file mode 100644 index 0000000000000000000000000000000000000000..cfaa4296f48be72668fe484532e3e3ae86755fc7 --- /dev/null +++ b/frameworks/native/audiodefinitions/include/hdi_adapter_type.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HDI_ADAPTER_TYPE_H +#define HDI_ADAPTER_TYPE_H + +#include +#include +#include "audio_info.h" + +namespace OHOS { +namespace AudioStandard { +// if attr struct change, please check ipc serialize and deserialize code +typedef struct IAudioSinkAttr { + const char *adapterName = nullptr; + uint32_t openMicSpeaker = 0; + AudioSampleFormat format = AudioSampleFormat::INVALID_WIDTH; + uint32_t sampleRate = 0; + uint32_t channel = 0; + float volume = 0.0f; + const char *filePath = nullptr; + const char *deviceNetworkId = nullptr; + int32_t deviceType = 0; + uint64_t channelLayout = 0; + int32_t audioStreamFlag = 0; + std::string address; + const char *aux; +} IAudioSinkAttr; + +typedef struct IAudioSourceAttr { + const char *adapterName = nullptr; + uint32_t openMicSpeaker = 0; + AudioSampleFormat format = AudioSampleFormat::INVALID_WIDTH; + uint32_t sampleRate = 0; + uint32_t channel = 0; + float volume = 0.0f; + uint32_t bufferSize = 0; + bool isBigEndian = false; + const char *filePath = nullptr; + const char *deviceNetworkId = nullptr; + int32_t deviceType = 0; + int32_t sourceType = 0; + uint64_t channelLayout = 0; + int32_t audioStreamFlag = 0; + bool hasEcConfig = false; + AudioSampleFormat formatEc = AudioSampleFormat::INVALID_WIDTH; + uint32_t sampleRateEc = 0; + uint32_t channelEc = 0; +} IAudioSourceAttr; + +typedef struct FrameDesc { + char *frame; + uint64_t frameLen; +} FrameDesc; + +} // namespace AudioStandard +} // namespace OHOS + +#endif // HDI_ADAPTER_TYPE_H diff --git a/frameworks/native/audiodefinitions/src/audio_pipe_info.cpp b/frameworks/native/audiodefinitions/src/audio_pipe_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b21f2592c46c4d9e52b958def2b5e938ed6b4928 --- /dev/null +++ b/frameworks/native/audiodefinitions/src/audio_pipe_info.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * 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 "audio_pipe_info.h" + +namespace OHOS { +namespace AudioStandard { +AudioPipeInfo::AudioPipeInfo() +{ +} + +AudioPipeInfo::~AudioPipeInfo() +{ +} + +AudioPipeInfo::AudioPipeInfo(const std::shared_ptr pipeInfo) +{ + id_ = pipeInfo->id_; + paIndex_ = pipeInfo->paIndex_; + pipeRole_ = pipeInfo->pipeRole_; + routeFlag_ = pipeInfo->routeFlag_; + adapterName_ = pipeInfo->adapterName_; + moduleInfo_ = pipeInfo->moduleInfo_; + pipeAction_ = pipeInfo->pipeAction_; + streamDescriptors_ = pipeInfo->streamDescriptors_; + streamDescMap_ = pipeInfo->streamDescMap_; +} +} // AudioStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/audiodefinitions/src/audio_stream_descriptor.cpp b/frameworks/native/audiodefinitions/src/audio_stream_descriptor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2d7c9b3a9822304a4198303dae9118591c8710 --- /dev/null +++ b/frameworks/native/audiodefinitions/src/audio_stream_descriptor.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * 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 "audio_stream_descriptor.h" +#include "audio_common_log.h" + +namespace OHOS { +namespace AudioStandard { +static const int32_t MAX_STREAM_DESCRIPTORS_SIZE = 1000; + +AudioStreamDescriptor::AudioStreamDescriptor() +{ +} + +AudioStreamDescriptor::~AudioStreamDescriptor() +{ +} + +bool AudioStreamDescriptor::Marshalling(Parcel &parcel) const +{ + return streamInfo_.Marshalling(parcel) && + parcel.WriteUint32(audioMode_) && + parcel.WriteUint32(audioFlag_) && + parcel.WriteUint32(routeFlag_) && + parcel.WriteInt64(startTimeStamp_) && + rendererInfo_.Marshalling(parcel) && + capturerInfo_.Marshalling(parcel) && + parcel.WriteInt32(appInfo_.appUid) && + parcel.WriteUint32(appInfo_.appTokenId) && + parcel.WriteInt32(appInfo_.appPid) && + parcel.WriteUint64(appInfo_.appFullTokenId) && + parcel.WriteUint32(sessionId_) && + parcel.WriteInt32(callerUid_) && + parcel.WriteUint32(streamAction_) && + WriteDeviceDescVectorToParcel(parcel, oldDeviceDescs_) && + WriteDeviceDescVectorToParcel(parcel, newDeviceDescs_); +} + +void AudioStreamDescriptor::Unmarshalling(Parcel &parcel) +{ + streamInfo_.Unmarshalling(parcel); + audioMode_ = static_cast(parcel.ReadUint32()); + audioFlag_ = static_cast(parcel.ReadUint32()); + routeFlag_ = static_cast(parcel.ReadUint32()); + startTimeStamp_ = parcel.ReadInt64(); + rendererInfo_.Unmarshalling(parcel); + capturerInfo_.Unmarshalling(parcel); + appInfo_.appUid = parcel.ReadInt32(); + appInfo_.appTokenId = parcel.ReadUint32(); + appInfo_.appPid = parcel.ReadInt32(); + appInfo_.appFullTokenId = parcel.ReadUint64(); + sessionId_ = parcel.ReadUint32(); + callerUid_ = parcel.ReadInt32(); + streamAction_ = static_cast(parcel.ReadUint32()); + UnmarshallingDeviceDescVector(parcel, oldDeviceDescs_); + UnmarshallingDeviceDescVector(parcel, newDeviceDescs_); +} + +bool AudioStreamDescriptor::WriteDeviceDescVectorToParcel( + Parcel &parcel, std::vector> &descs) const +{ + size_t size = descs.size(); + if (size > MAX_STREAM_DESCRIPTORS_SIZE) { + return parcel.WriteInt32(-1); + } + bool ret = parcel.WriteInt32(static_cast(size)); + CHECK_AND_RETURN_RET_LOG(ret, false, "write vector size failed"); + + for (auto desc : descs) { + ret = desc->Marshalling(parcel); + CHECK_AND_RETURN_RET_LOG(ret, false, "Marshalling device desc failed"); + } + return true; +} + +void AudioStreamDescriptor::UnmarshallingDeviceDescVector( + Parcel &parcel, std::vector> &descs) +{ + int32_t size = 0; + parcel.ReadInt32(size); + if (size == -1) { + AUDIO_ERR_LOG("Invalid vector size"); + return; + } + for (int32_t i = 0; i < size; i++) { + descs.push_back(AudioDeviceDescriptor::UnmarshallingPtr(parcel)); + } +} + +void AudioStreamDescriptor::Dump(std::string &dumpString) +{ + dumpString += "\nstreamId: " + std::to_string(sessionId_) + "\t\tcallerUid: " + std::to_string(callerUid_); + dumpString += "\nSampleRate: " + std::to_string(streamInfo_.samplingRate) + + " Channels: " + std::to_string(streamInfo_.channels) + " Format: " + std::to_string(streamInfo_.format) + + " Encoding: " + std::to_string(streamInfo_.encoding) + + " ChannelLayout: " + std::to_string(streamInfo_.channelLayout); + + dumpString += "\naudioMode: "; + if (audioMode_ == AUDIO_MODE_PLAYBACK) { + dumpString += "PLAYBACK"; + dumpString += "\n\tstreamUsage: " + std::to_string(rendererInfo_.streamUsage); + dumpString += "\n\toriginalFlag: " + std::to_string(rendererInfo_.originalFlag) + + "rendererFlags: " + std::to_string(rendererInfo_.rendererFlags); + dumpString += "\n\tisOffloadAllowed: "; + dumpString += (rendererInfo_.isOffloadAllowed ? "true" : "false"); + } else { + dumpString += "RECORD"; + dumpString += "\n\tsourceType: " + std::to_string(capturerInfo_.sourceType); + dumpString += "\n\toriginalFlag: " + std::to_string(capturerInfo_.originalFlag) + + "capturerFlags: " + std::to_string(capturerInfo_.capturerFlags); + } + + dumpString += "\naudioFlag: " + std::to_string(audioFlag_); + dumpString += "\nrouteFlag: " + std::to_string(routeFlag_); + dumpString += "\nstartTimeStamp: " + std::to_string(startTimeStamp_); + dumpString += "\nstreamStatus: " + std::to_string(streamStatus_); + dumpString += "\nstreamAction: " + std::to_string(streamAction_); + dumpString += "appUid: " + std::to_string(appInfo_.appUid) + "appTokenId: " + std::to_string(appInfo_.appTokenId) + + "appPid: " + std::to_string(appInfo_.appPid) + "appFullTokenId: " + std::to_string(appInfo_.appFullTokenId); + dumpString += "\noldDevices:\n"; + for (size_t idx = 0; idx < oldDeviceDescs_.size(); ++idx) { + dumpString += "\t" + std::to_string(idx + 1) + ". "; + oldDeviceDescs_[idx]->Dump(dumpString); + } + dumpString += "\nnewDevices:\n"; + for (size_t idx = 0; idx < newDeviceDescs_.size(); ++idx) { + dumpString += "\t" + std::to_string(idx + 1) + ". "; + newDeviceDescs_[idx]->Dump(dumpString); + } +} + +} // AudioStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/audioeffect/src/audio_effect_chain_manager.cpp b/frameworks/native/audioeffect/src/audio_effect_chain_manager.cpp index 04f704f6755dec2b6904f1883709f0371d7a6744..576772478512cc30d9e53c63702757c4a53943a0 100644 --- a/frameworks/native/audioeffect/src/audio_effect_chain_manager.cpp +++ b/frameworks/native/audioeffect/src/audio_effect_chain_manager.cpp @@ -778,6 +778,9 @@ int32_t AudioEffectChainManager::QueryHdiSupportedChannelInfo(uint32_t &channels std::lock_guard lock(dynamicMutex_); uint32_t tmpChannelCount = DEFAULT_NUM_CHANNEL; uint64_t tmpChannelLayout = DEFAULT_NUM_CHANNELLAYOUT; + if (sceneTypeToSessionIDMap_.size() == 0) { + return SUCCESS; + } for (auto it = sceneTypeToSessionIDMap_.begin(); it != sceneTypeToSessionIDMap_.end(); it++) { std::set sessions = sceneTypeToSessionIDMap_[it->first]; for (auto s = sessions.begin(); s != sessions.end(); ++s) { diff --git a/frameworks/native/audiopolicy/include/audio_policy_manager.h b/frameworks/native/audiopolicy/include/audio_policy_manager.h index beea67625d06674f96e5ba1c776a9a8abe186f81..0877af17d44d69ba2b0dc7c14aa7d34dc972a593 100644 --- a/frameworks/native/audiopolicy/include/audio_policy_manager.h +++ b/frameworks/native/audiopolicy/include/audio_policy_manager.h @@ -38,6 +38,7 @@ #include "audio_spatialization_state_change_listener_stub.h" #include "i_standard_spatialization_state_change_listener.h" #include "audio_combine_denoising_manager.h" +#include "audio_stream_descriptor.h" namespace OHOS { namespace AudioStandard { @@ -236,6 +237,12 @@ public: int32_t GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo); + int32_t CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId); + + int32_t CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId); + int32_t RegisterAudioRendererEventListener(const std::shared_ptr &callback); int32_t UnregisterAudioRendererEventListener( diff --git a/frameworks/native/audiorenderer/BUILD.gn b/frameworks/native/audiorenderer/BUILD.gn index 8b11df517b340f02056415858de280e57fb2a868..251abc3e99f346bceba3611b06ed5337fb901611 100644 --- a/frameworks/native/audiorenderer/BUILD.gn +++ b/frameworks/native/audiorenderer/BUILD.gn @@ -53,6 +53,7 @@ ohos_shared_library("audio_renderer") { deps = [ "../../../services/audio_policy:audio_policy_client", "../../../services/audio_service:audio_client", + "../audiodefinitions:audio_definitions", "../audioutils:audio_utils", ] external_deps = [ diff --git a/frameworks/native/audiorenderer/include/audio_renderer_private.h b/frameworks/native/audiorenderer/include/audio_renderer_private.h index 7cd3841dfa776aa0e30683ab768076a7d4407fe4..08439d4ebee5c70ba5cf3abafb0312f6dd696caf 100644 --- a/frameworks/native/audiorenderer/include/audio_renderer_private.h +++ b/frameworks/native/audiorenderer/include/audio_renderer_private.h @@ -27,6 +27,7 @@ #include "audio_renderer_proxy_obj.h" #include "audio_utils.h" #include "i_audio_stream.h" +#include "audio_stream_descriptor.h" namespace OHOS { namespace AudioStandard { @@ -100,7 +101,6 @@ public: float GetMaxStreamVolume() const override; int32_t GetCurrentOutputDevices(AudioDeviceDescriptor &deviceInfo) const override; uint32_t GetUnderflowCount() const override; - IAudioStream::StreamClass GetTargetStreamClass(int32_t streamFlag); int32_t RegisterOutputDeviceChangeWithInfoCallback( const std::shared_ptr &callback) override; @@ -177,8 +177,12 @@ protected: private: int32_t CheckAndRestoreAudioRenderer(std::string callingFunc); - int32_t PrepareAudioStream(const AudioStreamParams &audioStreamParams, + int32_t PrepareAudioStream(AudioStreamParams &audioStreamParams, const AudioStreamType &audioStreamType, IAudioStream::StreamClass &streamClass); + std::shared_ptr ConvertToStreamDescriptor(const AudioStreamParams &audioStreamParams); + std::shared_ptr GetStreamDescBySwitchInfo( + const IAudioStream::SwitchInfo &switchInfo, const RestoreInfo &restoreInfo); + void SetClientInfo(uint32_t flag, IAudioStream::StreamClass &streamClass); int32_t InitAudioInterruptCallback(bool isRestoreAudio = false); int32_t InitOutputDeviceChangeCallback(); int32_t InitAudioStream(AudioStreamParams audioStreamParams); diff --git a/frameworks/native/audiorenderer/src/audio_renderer.cpp b/frameworks/native/audiorenderer/src/audio_renderer.cpp index 48cc983ee30ab4e6391fac7155709d9a17a8d7f1..40272fcc28decf82445fb3b1846a60648ddf00ae 100644 --- a/frameworks/native/audiorenderer/src/audio_renderer.cpp +++ b/frameworks/native/audiorenderer/src/audio_renderer.cpp @@ -28,6 +28,7 @@ #include "audio_policy_manager.h" #include "media_monitor_manager.h" +#include "audio_stream_descriptor.h" #include "audio_scope_exit.h" namespace OHOS { @@ -73,6 +74,21 @@ static const std::map STREAM_TYPE_USAGE_MAP = { {STREAM_VOICE_RING, STREAM_USAGE_VOICE_RINGTONE}, }; +static const std::map OUTPUT_ROUTE_TO_STREAM_MAP = { + {AUDIO_OUTPUT_FLAG_NORMAL, AUDIO_FLAG_NORMAL}, + {AUDIO_OUTPUT_FLAG_DIRECT, AUDIO_FLAG_DIRECT}, + {AUDIO_OUTPUT_FLAG_FAST, AUDIO_FLAG_MMAP}, +}; + +static const std::map AUDIO_OUTPUT_FLAG_GROUP_MAP = { + {AUDIO_OUTPUT_FLAG_NORMAL, IAudioStream::StreamClass::PA_STREAM}, + {AUDIO_OUTPUT_FLAG_DIRECT, IAudioStream::StreamClass::PA_STREAM}, + {AUDIO_OUTPUT_FLAG_MULTICHANNEL, IAudioStream::StreamClass::PA_STREAM}, + {AUDIO_OUTPUT_FLAG_LOWPOWER, IAudioStream::StreamClass::PA_STREAM}, + {AUDIO_OUTPUT_FLAG_FAST, IAudioStream::StreamClass::FAST_STREAM}, + {AUDIO_OUTPUT_FLAG_HWDECODING, IAudioStream::StreamClass::PA_STREAM}, +}; + static const std::vector AUDIO_DEFAULT_OUTPUT_DEVICE_SUPPORTED_STREAM_USAGES { STREAM_USAGE_VOICE_COMMUNICATION, STREAM_USAGE_VOICE_MESSAGE, @@ -582,15 +598,24 @@ int32_t AudioRendererPrivate::SetParams(const AudioRendererParams params) return InitAudioInterruptCallback(); } -int32_t AudioRendererPrivate::PrepareAudioStream(const AudioStreamParams &audioStreamParams, +int32_t AudioRendererPrivate::PrepareAudioStream(AudioStreamParams &audioStreamParams, const AudioStreamType &audioStreamType, IAudioStream::StreamClass &streamClass) { AUDIO_INFO_LOG("Create stream with flag: %{public}d, original flag: %{public}d, streamClass: %{public}d", rendererInfo_.rendererFlags, rendererInfo_.originalFlag, streamClass); - // check AudioStreamParams for fast stream - // As fast stream only support specified audio format, we should call GetPlaybackStream with audioStreamParams. - ActivateAudioConcurrency(audioStreamParams, audioStreamType, streamClass); + // Create Client + std::shared_ptr streamDesc = ConvertToStreamDescriptor(audioStreamParams); + uint32_t flag = AUDIO_OUTPUT_FLAG_NORMAL; + + int32_t ret = AudioPolicyManager::GetInstance().CreateRendererClient( + streamDesc, flag, audioStreamParams.originalSessionId); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "CreateRendererClient failed"); + AUDIO_INFO_LOG("StreamClientState for Renderer::CreateClient. id %{public}u, flag: %{public}u", + audioStreamParams.originalSessionId, flag); + + SetClientInfo(flag, streamClass); + if (audioStream_ == nullptr) { audioStream_ = IAudioStream::GetPlaybackStream(streamClass, audioStreamParams, audioStreamType, appInfo_.appUid); @@ -601,6 +626,64 @@ int32_t AudioRendererPrivate::PrepareAudioStream(const AudioStreamParams &audioS return SUCCESS; } +std::shared_ptr AudioRendererPrivate::ConvertToStreamDescriptor( + const AudioStreamParams &audioStreamParams) +{ + std::shared_ptr streamDesc = std::make_shared(); + streamDesc->streamInfo_.format = static_cast(audioStreamParams.format); + streamDesc->streamInfo_.samplingRate = static_cast(audioStreamParams.samplingRate); + streamDesc->streamInfo_.channels = static_cast(audioStreamParams.channels); + streamDesc->streamInfo_.encoding = static_cast(audioStreamParams.encoding); + streamDesc->streamInfo_.channelLayout = static_cast(audioStreamParams.channelLayout); + streamDesc->audioMode_ = AUDIO_MODE_PLAYBACK; + streamDesc->startTimeStamp_ = ClockTime::GetCurNano(); + streamDesc->rendererInfo_ = rendererInfo_; + streamDesc->appInfo_ = appInfo_; + streamDesc->callerUid_ = getuid(); + return streamDesc; +} + +void AudioRendererPrivate::SetClientInfo(uint32_t flag, IAudioStream::StreamClass &streamClass) +{ + if (flag & AUDIO_OUTPUT_FLAG_FAST) { + if (flag & AUDIO_OUTPUT_FLAG_VOIP) { + streamClass = IAudioStream::StreamClass::VOIP_STREAM; + rendererInfo_.originalFlag = AUDIO_FLAG_VOIP_FAST; + rendererInfo_.rendererFlags = AUDIO_FLAG_VOIP_FAST; + rendererInfo_.pipeType = PIPE_TYPE_LOWLATENCY_OUT; + } else { + streamClass = IAudioStream::StreamClass::FAST_STREAM; + rendererInfo_.rendererFlags = AUDIO_FLAG_VOIP_FAST; + rendererInfo_.pipeType = PIPE_TYPE_LOWLATENCY_OUT; + } + } else if (flag & AUDIO_OUTPUT_FLAG_DIRECT) { + if (flag & AUDIO_OUTPUT_FLAG_VOIP) { + streamClass = IAudioStream::StreamClass::PA_STREAM; + rendererInfo_.originalFlag = AUDIO_FLAG_VOIP_DIRECT; + rendererInfo_.rendererFlags = AUDIO_FLAG_VOIP_DIRECT; + rendererInfo_.pipeType = PIPE_TYPE_CALL_OUT; + } else { + streamClass = IAudioStream::StreamClass::PA_STREAM; + rendererInfo_.rendererFlags = AUDIO_FLAG_DIRECT; + rendererInfo_.pipeType = PIPE_TYPE_DIRECT_OUT; + } + } else if (flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { + streamClass = IAudioStream::StreamClass::PA_STREAM; + rendererInfo_.rendererFlags = AUDIO_FLAG_NORMAL; + rendererInfo_.pipeType = PIPE_TYPE_OFFLOAD; + } else if (flag & AUDIO_OUTPUT_FLAG_MULTICHANNEL) { + streamClass = IAudioStream::StreamClass::PA_STREAM; + rendererInfo_.rendererFlags = AUDIO_FLAG_NORMAL; + rendererInfo_.pipeType = PIPE_TYPE_MULTICHANNEL; + } else { + streamClass = IAudioStream::StreamClass::PA_STREAM; + rendererInfo_.rendererFlags = AUDIO_FLAG_NORMAL; + rendererInfo_.pipeType = PIPE_TYPE_NORMAL_OUT; + } + AUDIO_INFO_LOG("Route flag: %{public}u, streamClass: %{public}d, rendererFlag: %{public}d, pipeType: %{public}d", + flag, streamClass, rendererInfo_.rendererFlags, rendererInfo_.pipeType); +} + int32_t AudioRendererPrivate::GetParams(AudioRendererParams ¶ms) const { AudioStreamParams audioStreamParams; @@ -773,7 +856,8 @@ int32_t AudioRendererPrivate::CheckAndRestoreAudioRenderer(std::string callingFu // Get restore info and target stream class for switching. RestoreInfo restoreInfo; audioStream_->GetRestoreInfo(restoreInfo); - IAudioStream::StreamClass targetClass = GetTargetStreamClass(restoreInfo.targetStreamFlag); + IAudioStream::StreamClass targetClass = IAudioStream::PA_STREAM; + SetClientInfo(restoreInfo.routeFlag, targetClass); // Switch to target audio stream. Deactivate audio interrupt if switch failed. AUDIO_INFO_LOG("Before %{public}s, restore audiorenderer %{public}u", callingFunc.c_str(), sessionID_); @@ -1388,33 +1472,6 @@ int32_t AudioRendererPrivate::SetRenderMode(AudioRenderMode renderMode) audioRenderMode_ = renderMode; std::shared_ptr currentStream = GetInnerStream(); CHECK_AND_RETURN_RET_LOG(currentStream != nullptr, ERROR_ILLEGAL_STATE, "audioStream_ is nullptr"); - if (renderMode == RENDER_MODE_CALLBACK && rendererInfo_.originalFlag != AUDIO_FLAG_FORCED_NORMAL && - (rendererInfo_.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION || - rendererInfo_.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION)) { - // both fast and direct VoIP renderer can only use RENDER_MODE_CALLBACK; - int32_t flags = AudioPolicyManager::GetInstance().GetPreferredOutputStreamType(rendererInfo_); - uint32_t sessionId = 0; - int32_t ret = currentStream->GetAudioSessionID(sessionId); - CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Get audio session Id failed"); - IAudioStream::StreamClass streamClass = IAudioStream::PA_STREAM; - if (flags == AUDIO_FLAG_VOIP_FAST) { - AUDIO_INFO_LOG("Switch to fast voip stream"); - streamClass = IAudioStream::VOIP_STREAM; - } else if (flags == AUDIO_FLAG_VOIP_DIRECT && isDirectVoipSupported_) { - AUDIO_INFO_LOG("Switch to direct voip stream"); - rendererInfo_.rendererFlags = AUDIO_FLAG_VOIP_DIRECT; - streamClass = IAudioStream::PA_STREAM; - } - RestoreInfo restoreInfo; - if (!SwitchToTargetStream(streamClass, restoreInfo)) { - AUDIO_ERR_LOG("Switch to target stream failed"); - return ERROR; - } - // audioStream_ has been updated by SwitchToTargetStream. Update currentStream before SetRenderMode. - currentStream = GetInnerStream(); - CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Register device change callback for new session failed"); - } - return currentStream->SetRenderMode(renderMode); } @@ -1941,6 +1998,13 @@ bool AudioRendererPrivate::SwitchToTargetStream(IAudioStream::StreamClass target switchResult = FinishOldStream(targetClass, restoreInfo, previousState, switchInfo); CHECK_AND_RETURN_RET_LOG(switchResult, false, "Finish old stream failed"); + // Create stream and pipe + std::shared_ptr streamDesc = GetStreamDescBySwitchInfo(switchInfo, restoreInfo); + uint32_t flag = AUDIO_OUTPUT_FLAG_NORMAL; + uint32_t ret = AudioPolicyManager::GetInstance().CreateRendererClient( + streamDesc, flag, switchInfo.params.originalSessionId); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "CreateRendererClient failed"); + // Create and start new stream. switchResult = GenerateNewStream(targetClass, restoreInfo, previousState, switchInfo); CHECK_AND_RETURN_RET_LOG(switchResult, false, "Generate new stream failed"); @@ -1956,6 +2020,26 @@ bool AudioRendererPrivate::SwitchToTargetStream(IAudioStream::StreamClass target return switchResult; } +std::shared_ptr AudioRendererPrivate::GetStreamDescBySwitchInfo( + const IAudioStream::SwitchInfo &switchInfo, const RestoreInfo &restoreInfo) +{ + std::shared_ptr streamDesc = std::make_shared(); + streamDesc->streamInfo_.format = static_cast(switchInfo.params.format); + streamDesc->streamInfo_.samplingRate = static_cast(switchInfo.params.samplingRate); + streamDesc->streamInfo_.channels = static_cast(switchInfo.params.channels); + streamDesc->streamInfo_.encoding = static_cast(switchInfo.params.encoding); + streamDesc->streamInfo_.channelLayout = static_cast(switchInfo.params.channelLayout); + + streamDesc->audioMode_ = AUDIO_MODE_PLAYBACK; + streamDesc->startTimeStamp_ = ClockTime::GetCurNano(); + streamDesc->rendererInfo_ = switchInfo.rendererInfo; + streamDesc->appInfo_ = AppInfo{switchInfo.appUid, 0, switchInfo.clientPid, 0}; + streamDesc->callerUid_ = switchInfo.clientUid; + streamDesc->sessionId_ = switchInfo.sessionId; + streamDesc->routeFlag_ = restoreInfo.routeFlag; + return streamDesc; +} + void AudioRendererPrivate::HandleAudioInterruptWhenServerDied() { InitAudioInterruptCallback(true); // Register audio interrupt callback again. @@ -1981,42 +2065,6 @@ void AudioRendererPrivate::WriteSwitchStreamLogMsg() Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); } -IAudioStream::StreamClass AudioRendererPrivate::GetTargetStreamClass(int32_t streamFlag) -{ - IAudioStream::StreamClass targetClass = IAudioStream::PA_STREAM; - switch (streamFlag) { - case AUDIO_FLAG_NORMAL: - rendererInfo_.rendererFlags = AUDIO_FLAG_NORMAL; - targetClass = IAudioStream::PA_STREAM; - break; - case AUDIO_FLAG_MMAP: - rendererInfo_.rendererFlags = AUDIO_FLAG_MMAP; - targetClass = IAudioStream::FAST_STREAM; - break; - case AUDIO_FLAG_VOIP_FAST: - rendererInfo_.rendererFlags = AUDIO_FLAG_VOIP_FAST; - targetClass = IAudioStream::VOIP_STREAM; - break; - case AUDIO_FLAG_VOIP_DIRECT: - rendererInfo_.rendererFlags = (isDirectVoipSupported_ && audioRenderMode_ == RENDER_MODE_CALLBACK) ? - AUDIO_FLAG_VOIP_DIRECT : AUDIO_FLAG_NORMAL; - targetClass = IAudioStream::PA_STREAM; - break; - case AUDIO_FLAG_DIRECT: - rendererInfo_.rendererFlags = AUDIO_FLAG_DIRECT; - break; - default: - AUDIO_INFO_LOG("unknown stream flag"); - break; - } - if (rendererInfo_.originalFlag == AUDIO_FLAG_FORCED_NORMAL) { - rendererInfo_.rendererFlags = AUDIO_FLAG_NORMAL; - targetClass = IAudioStream::PA_STREAM; - } - return targetClass; -} - - void OutputDeviceChangeWithInfoCallbackImpl::OnDeviceChangeWithInfo( const uint32_t sessionId, const AudioDeviceDescriptor &deviceInfo, const AudioStreamDeviceChangeReasonExt reason) { diff --git a/frameworks/native/audiorenderer/test/unittest/renderer_test/BUILD.gn b/frameworks/native/audiorenderer/test/unittest/renderer_test/BUILD.gn index 3aec682b8ddcce126de5697d50745a763df074f8..49bfff99194cbff89fab9e817473ee28b022e3f8 100644 --- a/frameworks/native/audiorenderer/test/unittest/renderer_test/BUILD.gn +++ b/frameworks/native/audiorenderer/test/unittest/renderer_test/BUILD.gn @@ -22,6 +22,7 @@ ohos_unittest("audio_renderer_unit_test") { include_dirs = [ "./include", "../../../src", + "../../../../audiodefinitions/include", "../../../../audiorenderer/include", "../../../../audiostream/include", "../../../../common/include", @@ -42,6 +43,7 @@ ohos_unittest("audio_renderer_unit_test") { deps = [ "../../../../../../services/audio_policy:audio_policy_client", "../../../../../../services/audio_service:audio_client", + "../../../../audiodefinitions:audio_definitions", "../../../../audiorenderer:audio_renderer", "../../../../audioutils:audio_utils", ] diff --git a/frameworks/native/audiorenderer/test/unittest/renderer_test/src/audio_renderer_unit_test.cpp b/frameworks/native/audiorenderer/test/unittest/renderer_test/src/audio_renderer_unit_test.cpp index 52a2260adad8d4ea8b89124742e1b32821b0e26c..d42849bf8229bd13f60df6c2480596d30e3145c8 100644 --- a/frameworks/native/audiorenderer/test/unittest/renderer_test/src/audio_renderer_unit_test.cpp +++ b/frameworks/native/audiorenderer/test/unittest/renderer_test/src/audio_renderer_unit_test.cpp @@ -7939,7 +7939,7 @@ HWTEST(AudioRendererUnitTest, PrepareAudioStream_001, TestSize.Level1) std::shared_ptr audioRendererPrivate = std::make_shared(AudioStreamType::STREAM_MEDIA, appInfo); audioRendererPrivate->audioStream_ = nullptr; - const AudioStreamParams audioStreamParams; + AudioStreamParams audioStreamParams; const AudioStreamType audioStreamType = STREAM_VOICE_CALL; IAudioStream::StreamClass streamClass; diff --git a/frameworks/native/hdiadapter/common/include/audio_hdiadapter_info.h b/frameworks/native/hdiadapter/common/include/audio_hdiadapter_info.h index 118767043b8467df746d79d8c7207ec460b0296c..ca308656d748bccb328210f80f2f00a349fd4478 100644 --- a/frameworks/native/hdiadapter/common/include/audio_hdiadapter_info.h +++ b/frameworks/native/hdiadapter/common/include/audio_hdiadapter_info.h @@ -16,7 +16,9 @@ #ifndef AUDIO_HDIADAPTER_INFO_H #define AUDIO_HDIADAPTER_INFO_H +#ifndef MAX_MIX_CHANNELS #define MAX_MIX_CHANNELS 128 +#endif #define PA_MAX_OUTPUTS_PER_SOURCE 256 #include diff --git a/frameworks/native/hdiadapter_new/BUILD.gn b/frameworks/native/hdiadapter_new/BUILD.gn index 1aad77d5375d4b3240d3da506e84498b4c7e5b76..926b2249fb705133ca28f334d39d9f8dbf5ea9e4 100644 --- a/frameworks/native/hdiadapter_new/BUILD.gn +++ b/frameworks/native/hdiadapter_new/BUILD.gn @@ -41,6 +41,7 @@ ohos_shared_library("hdiadapter_new") { "../../../services/audio_service/common/include", "../../../interfaces/inner_api/native/audiocommon/include", "../audioutils/include", + "../audiodefinitions/include", "../audioeffect/include", "../audioschedule/include", ] @@ -126,6 +127,7 @@ ohos_unittest("hdiadapter_unit_test") { include_dirs = [ "include", "../../../interfaces/inner_api/native/audiocommon/include", + "../audiodefinitions/include", "../audioutils/include", ] diff --git a/frameworks/native/hdiadapter_new/adapter/bluetooth_device_manager.cpp b/frameworks/native/hdiadapter_new/adapter/bluetooth_device_manager.cpp index f829ce86fcda77406d35a7ca07204800e078c480..7f150767b9bd2ad8b7d6e58a7d88bd37f8c96397 100644 --- a/frameworks/native/hdiadapter_new/adapter/bluetooth_device_manager.cpp +++ b/frameworks/native/hdiadapter_new/adapter/bluetooth_device_manager.cpp @@ -268,7 +268,10 @@ std::shared_ptr BluetoothDeviceManager::GetAdapter(cons if (!tryCreate) { return nullptr; } - LoadAdapter(adapterName); + if (LoadAdapter(adapterName) != SUCCESS) { + AUDIO_ERR_LOG("LoadAdapter %{public}s failed", adapterName.c_str()); + return nullptr; + } std::lock_guard lock(adapterMtx_); return adapters_.count(adapterName) == 0 ? nullptr : adapters_[adapterName]; } diff --git a/frameworks/native/hdiadapter_new/adapter/local_device_manager.cpp b/frameworks/native/hdiadapter_new/adapter/local_device_manager.cpp index 6e157c7a92da5f011bbc4e1380f610f655524c01..95a0e355490aabb4b33fb8fdc2959851fe4cff78 100644 --- a/frameworks/native/hdiadapter_new/adapter/local_device_manager.cpp +++ b/frameworks/native/hdiadapter_new/adapter/local_device_manager.cpp @@ -471,7 +471,7 @@ int32_t LocalDeviceManager::SetOutputPortPin(DeviceType outputDevice, AudioRoute int32_t LocalDeviceManager::SetInputPortPin(DeviceType inputDevice, AudioRouteNode &source) { int32_t ret = SUCCESS; - + AUDIO_INFO_LOG("Input device type %{public}d", inputDevice); switch (inputDevice) { case DEVICE_TYPE_MIC: case DEVICE_TYPE_EARPIECE: diff --git a/frameworks/native/hdiadapter_new/include/manager/hdi_adapter_manager.h b/frameworks/native/hdiadapter_new/include/manager/hdi_adapter_manager.h index 64358adf7722753fb76d6c39145d38d5110ad426..33f529c004d4d31135b39e29d2eb160aed0d9ec3 100644 --- a/frameworks/native/hdiadapter_new/include/manager/hdi_adapter_manager.h +++ b/frameworks/native/hdiadapter_new/include/manager/hdi_adapter_manager.h @@ -50,8 +50,12 @@ public: bool isResident = false); uint32_t GetRenderIdByDeviceClass(const std::string &deviceClass, const std::string &info = HDI_ID_INFO_DEFAULT, bool isResident = false); + uint32_t GetRenderIdByDeviceClass(HdiIdBase idBase, HdiIdType idType, const std::string &info, + bool isResident); uint32_t GetCaptureIdByDeviceClass(const std::string &deviceClass, const SourceType sourceType, const std::string &info = HDI_ID_INFO_DEFAULT, bool isResident = false); + uint32_t GetCaptureIdByDeviceClass(HdiIdBase idBase, HdiIdType idType, const SourceType sourceType, + const std::string &info, bool isResident); void ReleaseId(uint32_t &id); std::shared_ptr GetRenderSink(uint32_t renderId, bool tryCreate = false); diff --git a/frameworks/native/hdiadapter_new/include/sink/i_audio_render_sink.h b/frameworks/native/hdiadapter_new/include/sink/i_audio_render_sink.h index 6a52e5ac123cd43bc73b39f35ed192b6565e8497..6e49230653d0783d2453f3df4516521f6983e66f 100644 --- a/frameworks/native/hdiadapter_new/include/sink/i_audio_render_sink.h +++ b/frameworks/native/hdiadapter_new/include/sink/i_audio_render_sink.h @@ -22,28 +22,13 @@ #include "audio_info.h" #include "audio_errors.h" #include "common/hdi_adapter_info.h" +#include "hdi_adapter_type.h" #define SUCCESS_RET { return SUCCESS; } #define NOT_SUPPORT_RET { return ERR_NOT_SUPPORTED; } namespace OHOS { namespace AudioStandard { -typedef struct IAudioSinkAttr { - const char *adapterName = ""; - uint32_t openMicSpeaker = 0; - AudioSampleFormat format = AudioSampleFormat::INVALID_WIDTH; - uint32_t sampleRate = 0; - uint32_t channel = 0; - float volume = 0.0f; - const char *filePath = nullptr; - const char *deviceNetworkId = nullptr; - int32_t deviceType = 0; - uint64_t channelLayout = 0; - int32_t audioStreamFlag = 0; - std::string address; - const char *aux; -} IAudioSinkAttr; - class IAudioSinkCallback { public: virtual ~IAudioSinkCallback() = default; diff --git a/frameworks/native/hdiadapter_new/include/source/i_audio_capture_source.h b/frameworks/native/hdiadapter_new/include/source/i_audio_capture_source.h index 4e7c0993b0233641d009fa7a3e83c3083b76e3b6..77b8178572bec23785460763d3aa76a669aefdb1 100644 --- a/frameworks/native/hdiadapter_new/include/source/i_audio_capture_source.h +++ b/frameworks/native/hdiadapter_new/include/source/i_audio_capture_source.h @@ -21,38 +21,13 @@ #include "audio_info.h" #include "audio_errors.h" #include "common/hdi_adapter_info.h" +#include "hdi_adapter_type.h" #define SUCCESS_RET { return SUCCESS; } #define NOT_SUPPORT_RET { return ERR_NOT_SUPPORTED; } namespace OHOS { namespace AudioStandard { -typedef struct IAudioSourceAttr { - const char *adapterName = ""; - uint32_t openMicSpeaker = 0; - AudioSampleFormat format = AudioSampleFormat::INVALID_WIDTH; - uint32_t sampleRate = 0; - uint32_t channel = 0; - float volume = 0.0f; - uint32_t bufferSize = 0; - bool isBigEndian = false; - const char *filePath = nullptr; - const char *deviceNetworkId = nullptr; - int32_t deviceType = 0; - int32_t sourceType = 0; - uint64_t channelLayout = 0; - int32_t audioStreamFlag = 0; - bool hasEcConfig = false; - AudioSampleFormat formatEc = AudioSampleFormat::INVALID_WIDTH; - uint32_t sampleRateEc = 0; - uint32_t channelEc = 0; -} IAudioSourceAttr; - -typedef struct FrameDesc { - char *frame; - uint64_t frameLen; -} FrameDesc; - class IAudioSourceCallback { public: virtual ~IAudioSourceCallback() = default; diff --git a/frameworks/native/hdiadapter_new/manager/hdi_adapter_factory.cpp b/frameworks/native/hdiadapter_new/manager/hdi_adapter_factory.cpp index 28aa70abba8dc365724b150da85d81a61d4f85fd..8cb4e9abad3e08a213094fbb966c2350faa4ede6 100644 --- a/frameworks/native/hdiadapter_new/manager/hdi_adapter_factory.cpp +++ b/frameworks/native/hdiadapter_new/manager/hdi_adapter_factory.cpp @@ -56,6 +56,7 @@ std::shared_ptr HdiAdapterFactory::CreateRenderSink(uint32_t r CHECK_AND_RETURN_RET(idHandler.CheckId(renderId, HDI_ID_BASE_RENDER), nullptr); uint32_t type = idHandler.ParseType(renderId); std::string info = idHandler.ParseInfo(renderId); + AUDIO_INFO_LOG("Type: %{public}u, info: %{public}s", type, info.c_str()); std::shared_ptr sink = nullptr; switch (type) { diff --git a/frameworks/native/hdiadapter_new/manager/hdi_adapter_manager.cpp b/frameworks/native/hdiadapter_new/manager/hdi_adapter_manager.cpp index d67d5b7c3eda5090b564f0990200401e35fa4772..e0f64ad3852df1d4198dbc1fcfb46bcd9d8b8639 100644 --- a/frameworks/native/hdiadapter_new/manager/hdi_adapter_manager.cpp +++ b/frameworks/native/hdiadapter_new/manager/hdi_adapter_manager.cpp @@ -76,12 +76,13 @@ void HdiAdapterManager::ReleaseDeviceManager(HdiDeviceManagerType type) uint32_t HdiAdapterManager::GetId(HdiIdBase base, HdiIdType type, const std::string &info, bool isResident) { uint32_t id = IdHandler::GetInstance().GetId(base, type, info); + AUDIO_INFO_LOG("Base: %{public}u, type: %{public}u, info: %{public}s, id: %{public}u, isResident :%{public}d", + base, type, info.c_str(), id, isResident); CHECK_AND_RETURN_RET(id != HDI_INVALID_ID, HDI_INVALID_ID); if (renderSinks_.count(id) == 0 && captureSources_.count(id) == 0) { IdHandler::GetInstance().IncInfoIdUseCount(id); } CHECK_AND_RETURN_RET(isResident, id); - AUDIO_INFO_LOG("base: %{public}u, type: %{public}u, info: %{public}s", base, type, info.c_str()); IncRefCount(id); return id; } @@ -90,12 +91,28 @@ uint32_t HdiAdapterManager::GetRenderIdByDeviceClass(const std::string &deviceCl bool isResident) { uint32_t id = IdHandler::GetInstance().GetRenderIdByDeviceClass(deviceClass, info); + AUDIO_INFO_LOG("Device class: %{public}s, info: %{public}s, id: %{public}u", + deviceClass.c_str(), info.c_str(), id); + CHECK_AND_RETURN_RET(id != HDI_INVALID_ID, HDI_INVALID_ID); + if (renderSinks_.count(id) == 0 && captureSources_.count(id) == 0) { + IdHandler::GetInstance().IncInfoIdUseCount(id); + } + CHECK_AND_RETURN_RET(isResident, id); + IncRefCount(id); + return id; +} + +uint32_t HdiAdapterManager::GetRenderIdByDeviceClass(HdiIdBase idBase, HdiIdType idType, const std::string &info, + bool isResident) +{ + uint32_t id = IdHandler::GetInstance().GetId(idBase, idType, info); + AUDIO_INFO_LOG("Base: %{public}u, type: %{public}u, info: %{public}s, id: %{public}u", + idBase, idType, info.c_str(), id); CHECK_AND_RETURN_RET(id != HDI_INVALID_ID, HDI_INVALID_ID); if (renderSinks_.count(id) == 0 && captureSources_.count(id) == 0) { IdHandler::GetInstance().IncInfoIdUseCount(id); } CHECK_AND_RETURN_RET(isResident, id); - AUDIO_INFO_LOG("deviceClass: %{public}s, info: %{public}s", deviceClass.c_str(), info.c_str()); IncRefCount(id); return id; } @@ -104,13 +121,28 @@ uint32_t HdiAdapterManager::GetCaptureIdByDeviceClass(const std::string &deviceC const std::string &info, bool isResident) { uint32_t id = IdHandler::GetInstance().GetCaptureIdByDeviceClass(deviceClass, sourceType, info); + AUDIO_INFO_LOG("Device class: %{public}s, sourceType: %{public}d, info: %{public}s, id: %{public}u", + deviceClass.c_str(), sourceType, info.c_str(), id); + CHECK_AND_RETURN_RET(id != HDI_INVALID_ID, HDI_INVALID_ID); + if (renderSinks_.count(id) == 0 && captureSources_.count(id) == 0) { + IdHandler::GetInstance().IncInfoIdUseCount(id); + } + CHECK_AND_RETURN_RET(isResident, id); + IncRefCount(id); + return id; +} + +uint32_t HdiAdapterManager::GetCaptureIdByDeviceClass(HdiIdBase idBase, HdiIdType idType, const SourceType sourceType, + const std::string &info, bool isResident) +{ + uint32_t id = IdHandler::GetInstance().GetId(idBase, idType, info); + AUDIO_INFO_LOG("Base: %{public}u, type: %{public}u, sourceType: %{public}d, info: %{public}s, id: %{public}u", + idBase, idType, sourceType, info.c_str(), id); CHECK_AND_RETURN_RET(id != HDI_INVALID_ID, HDI_INVALID_ID); if (renderSinks_.count(id) == 0 && captureSources_.count(id) == 0) { IdHandler::GetInstance().IncInfoIdUseCount(id); } CHECK_AND_RETURN_RET(isResident, id); - AUDIO_INFO_LOG("deviceClass: %{public}s, sourceType: %{public}d, info: %{public}s", deviceClass.c_str(), sourceType, - info.c_str()); IncRefCount(id); return id; } diff --git a/frameworks/native/hdiadapter_new/sink/audio_render_sink.cpp b/frameworks/native/hdiadapter_new/sink/audio_render_sink.cpp index 7248e8d7c9027cb196961a4aac54404fa8ad0457..c9cb48901aa1ee715c42f80126954c6a3273a692 100644 --- a/frameworks/native/hdiadapter_new/sink/audio_render_sink.cpp +++ b/frameworks/native/hdiadapter_new/sink/audio_render_sink.cpp @@ -451,7 +451,8 @@ int32_t AudioRenderSink::SetAudioScene(AudioScene audioScene, std::vector &outputDevic { CHECK_AND_RETURN_RET_LOG(!outputDevices.empty() && outputDevices.size() <= AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT, ERR_INVALID_PARAM, "invalid device"); + AUDIO_INFO_LOG("currentActiveDevice: %{public}d, outputDevices %{public}d", + currentActiveDevice_, outputDevices[0]); if (currentActiveDevice_ == outputDevices[0] && outputDevices.size() == static_cast(currentDevicesSize_) && !forceSetRouteFlag_) { AUDIO_INFO_LOG("output device not change, device: %{public}d", outputDevices[0]); @@ -853,6 +856,7 @@ int32_t AudioRenderSink::CreateRender(void) int32_t AudioRenderSink::DoSetOutputRoute(std::vector &outputDevices) { + AUDIO_INFO_LOG("Adapter name: %{public}s", adapterNameCase_.c_str()); HdiAdapterManager &manager = HdiAdapterManager::GetInstance(); std::shared_ptr deviceManager = manager.GetDeviceManager(HDI_DEVICE_MANAGER_TYPE_LOCAL); CHECK_AND_RETURN_RET(deviceManager != nullptr, ERR_INVALID_HANDLE); diff --git a/frameworks/native/hdiadapter_new/source/audio_capture_source.cpp b/frameworks/native/hdiadapter_new/source/audio_capture_source.cpp index cd0e3f23b900932946a520dab8bd9ea8fcb571c7..141f3494e55b139eff4b055913e7e29aef77f074 100644 --- a/frameworks/native/hdiadapter_new/source/audio_capture_source.cpp +++ b/frameworks/native/hdiadapter_new/source/audio_capture_source.cpp @@ -47,6 +47,7 @@ AudioCaptureSource::~AudioCaptureSource() int32_t AudioCaptureSource::Init(const IAudioSourceAttr &attr) { + AUDIO_INFO_LOG("In, attr's adapter name: %{public}s", adapterNameCase_.c_str()); std::lock_guard lock(statusMutex_); if (attr.sourceType == SOURCE_TYPE_MIC_REF || attr.sourceType == SOURCE_TYPE_EC) { InitEcOrMicRefAttr(attr); @@ -421,10 +422,8 @@ int32_t AudioCaptureSource::SetAudioScene(AudioScene audioScene, DeviceType acti { CHECK_AND_RETURN_RET_LOG(audioScene >= AUDIO_SCENE_DEFAULT && audioScene < AUDIO_SCENE_MAX, ERR_INVALID_PARAM, "invalid scene"); - AUDIO_INFO_LOG("scene: %{public}d, device: %{public}d", audioScene, activeDevice); - if (!openMic_) { - return SUCCESS; - } + AUDIO_INFO_LOG("scene: %{public}d, current scene : %{public}d, device: %{public}d", + audioScene, currentAudioScene_, activeDevice); if (audioScene != currentAudioScene_) { struct AudioSceneDescriptor sceneDesc; @@ -825,6 +824,8 @@ int32_t AudioCaptureSource::DoSetInputRoute(DeviceType inputDevice) CHECK_AND_RETURN_RET(deviceManager != nullptr, ERR_INVALID_HANDLE); int32_t streamId = static_cast(GetUniqueIdBySourceType()); int32_t inputType = static_cast(ConvertToHDIAudioInputType(attr_.sourceType)); + AUDIO_INFO_LOG("adapterName: %{public}s, inputDevice: %{public}d, streamId: %{public}d, inputType: %{public}d", + attr_.adapterName, inputDevice, streamId, inputType); int32_t ret = deviceManager->SetInputRoute(adapterNameCase_, inputDevice, streamId, inputType); return ret; } @@ -835,7 +836,7 @@ int32_t AudioCaptureSource::InitCapture(void) AUDIO_INFO_LOG("capture already inited"); return SUCCESS; } - + AUDIO_INFO_LOG("In, openMicL %{public}u, halName: %{public}s", openMic_, halName_.c_str()); int32_t ret = CreateCapture(); CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_NOT_STARTED, "create capture fail"); if (openMic_) { @@ -1019,6 +1020,7 @@ void AudioCaptureSource::CaptureThreadLoop(void) int32_t AudioCaptureSource::UpdateActiveDeviceWithoutLock(DeviceType inputDevice) { + AUDIO_INFO_LOG("current active device: %{public}d, inputDevice: %{public}d", currentActiveDevice_, inputDevice); if (currentActiveDevice_ == inputDevice) { AUDIO_INFO_LOG("input device not change, device: %{public}d, sourceType: %{public}d", inputDevice, attr_.sourceType); diff --git a/frameworks/native/hdiadapter_new/source/fast_audio_capture_source.cpp b/frameworks/native/hdiadapter_new/source/fast_audio_capture_source.cpp index aeb446123ee66fdd030355d35b887bc78b4f1bdc..79b1a9e3fe25a3ce2cdb6e15b4f47501579f0a18 100644 --- a/frameworks/native/hdiadapter_new/source/fast_audio_capture_source.cpp +++ b/frameworks/native/hdiadapter_new/source/fast_audio_capture_source.cpp @@ -34,7 +34,7 @@ FastAudioCaptureSource::~FastAudioCaptureSource() int32_t FastAudioCaptureSource::Init(const IAudioSourceAttr &attr) { - AUDIO_INFO_LOG("in, flag: %{public}d", attr.audioStreamFlag); + AUDIO_INFO_LOG("In, flag: %{public}d", attr.audioStreamFlag); attr_ = attr; int32_t ret = CreateCapture(); @@ -517,6 +517,8 @@ int32_t FastAudioCaptureSource::DoSetInputRoute(DeviceType inputDevice) CHECK_AND_RETURN_RET(deviceManager != nullptr, ERR_INVALID_HANDLE); int32_t streamId = static_cast(GenerateUniqueID(AUDIO_HDI_CAPTURE_ID_BASE, HDI_CAPTURE_OFFSET_FAST)); int32_t inputType = static_cast(ConvertToHDIAudioInputType(attr_.sourceType)); + AUDIO_INFO_LOG("adapterName: %{public}s, inputDevice: %{public}d, streamId: %{public}d, input :%{public}d", + attr_.adapterName, inputDevice, streamId, inputType); int32_t ret = deviceManager->SetInputRoute(attr_.adapterName, inputDevice, streamId, inputType); return ret; } diff --git a/frameworks/native/hdiadapter_new/util/id_handler.cpp b/frameworks/native/hdiadapter_new/util/id_handler.cpp index 31ac02d847eb4b901bccbab47e44b77fb27f42fb..42aea199ee146dcde8af226640faac6b4f80ce0c 100644 --- a/frameworks/native/hdiadapter_new/util/id_handler.cpp +++ b/frameworks/native/hdiadapter_new/util/id_handler.cpp @@ -122,18 +122,20 @@ uint32_t IdHandler::GetCaptureIdByDeviceClass(const std::string &deviceClass, co void IdHandler::IncInfoIdUseCount(uint32_t id) { uint32_t infoId = id & HDI_ID_INFO_MASK; - CHECK_AND_RETURN_LOG(infoIdMap_.count(infoId) != 0, "invalid id %{public}u", id); std::lock_guard lock(infoIdMtx_); + CHECK_AND_RETURN_LOG(infoIdMap_.count(infoId) != 0, "invalid id %{public}u", id); infoIdMap_[infoId].useCount_++; + AUDIO_INFO_LOG("id: %{public}u, use count: %{public}u", id, infoIdMap_[infoId].useCount_.load()); } void IdHandler::DecInfoIdUseCount(uint32_t id) { uint32_t infoId = id & HDI_ID_INFO_MASK; - CHECK_AND_RETURN_LOG(infoIdMap_.count(infoId) != 0, "invalid id %{public}u", id); std::lock_guard lock(infoIdMtx_); + CHECK_AND_RETURN_LOG(infoIdMap_.count(infoId) != 0, "invalid id %{public}u", id); if (infoIdMap_[infoId].useCount_.load() > 0) { infoIdMap_[infoId].useCount_--; + AUDIO_WARNING_LOG("id: %{public}u, use count: %{public}u", id, infoIdMap_[infoId].useCount_.load()); if (infoIdMap_[infoId].useCount_.load() > 0) { AUDIO_DEBUG_LOG("info: %{public}s, useCount: %{public}u", infoIdMap_[infoId].info_.c_str(), infoIdMap_[infoId].useCount_.load()); @@ -143,6 +145,7 @@ void IdHandler::DecInfoIdUseCount(uint32_t id) infoIdMap_.erase(infoId); std::lock_guard freeLock(freeInfoIdMtx_); freeInfoIdSet_.emplace(infoId); + AUDIO_INFO_LOG("DecInfoIdUseCount reach 0, erase id"); } bool IdHandler::CheckId(uint32_t id, HdiIdBase requireBase) diff --git a/frameworks/native/pulseaudio/modules/hdi/hdi_adapter_intf/BUILD.gn b/frameworks/native/pulseaudio/modules/hdi/hdi_adapter_intf/BUILD.gn index 01bff23dfbae18bb475bd5a3c6bd3394f325929c..c76f1c4547f38d41bf876d696f3c9c61288fc50d 100644 --- a/frameworks/native/pulseaudio/modules/hdi/hdi_adapter_intf/BUILD.gn +++ b/frameworks/native/pulseaudio/modules/hdi/hdi_adapter_intf/BUILD.gn @@ -34,6 +34,7 @@ ohos_shared_library("sink_adapter") { include_dirs = [ "include", "../../../../../../interfaces/inner_api/native/audiocommon/include", + "../../../../audiodefinitions/include", "../../../../hdiadapter_new/include", ] @@ -73,6 +74,7 @@ ohos_shared_library("source_adapter") { include_dirs = [ "include", "../../../../../../interfaces/inner_api/native/audiocommon/include", + "../../../../audiodefinitions/include", "../../../../hdiadapter_new/include", ] diff --git a/frameworks/native/pulseaudio/modules/hdi/hdi_adapter_intf/sink/sink_adapter.cpp b/frameworks/native/pulseaudio/modules/hdi/hdi_adapter_intf/sink/sink_adapter.cpp index de9c9a512ca02fd1f766cebb2986e26ffb0330cf..c22902981b041c5e5ae971082bc9ee762aeaa9ca 100644 --- a/frameworks/native/pulseaudio/modules/hdi/hdi_adapter_intf/sink/sink_adapter.cpp +++ b/frameworks/native/pulseaudio/modules/hdi/hdi_adapter_intf/sink/sink_adapter.cpp @@ -39,6 +39,7 @@ static inline std::shared_ptr GetRenderSink(uint32_t renderId) int32_t InitSinkAdapter(struct SinkAdapter *adapter, const char *deviceClass, const char *info) { + AUDIO_INFO_LOG("In, deviceClass: %{public}s, info: %{public}s", deviceClass, info); CHECK_AND_RETURN_RET_LOG(adapter != nullptr, ERR_INVALID_HANDLE, "adapter is nullptr"); adapter->renderId = HDI_INVALID_ID; @@ -73,6 +74,7 @@ void DeInitSinkAdapter(struct SinkAdapter *adapter) int32_t SinkAdapterInit(struct SinkAdapter *adapter, const struct SinkAdapterAttr *attr) { + AUDIO_INFO_LOG("In"); CHECK_AND_RETURN_RET_LOG(adapter != nullptr && adapter->renderId != HDI_INVALID_ID, ERR_INVALID_HANDLE, "invalid adapter"); CHECK_AND_RETURN_RET_LOG(attr != nullptr, ERR_INVALID_PARAM, "attr is nullptr"); @@ -100,6 +102,7 @@ int32_t SinkAdapterInit(struct SinkAdapter *adapter, const struct SinkAdapterAtt void SinkAdapterDeInit(struct SinkAdapter *adapter) { + AUDIO_INFO_LOG("In"); CHECK_AND_RETURN_LOG(adapter != nullptr && adapter->renderId != HDI_INVALID_ID, "invalid adapter"); std::shared_ptr sink = GetRenderSink(adapter->renderId); CHECK_AND_RETURN_LOG(sink != nullptr, "get sink fail"); diff --git a/frameworks/native/pulseaudio/modules/hdi/hdi_sink.c b/frameworks/native/pulseaudio/modules/hdi/hdi_sink.c index c6992dab25037a3eb5f9e9a554cfa20489c4924e..a37fe71d9f8c660cc3fc73e34550dc673cd9c258 100644 --- a/frameworks/native/pulseaudio/modules/hdi/hdi_sink.c +++ b/frameworks/native/pulseaudio/modules/hdi/hdi_sink.c @@ -4509,7 +4509,7 @@ static int32_t PaHdiSinkNewInitUserData(pa_module *m, pa_modargs *ma, struct Use return -1; } - AUDIO_DEBUG_LOG("Load sink adapter"); + AUDIO_INFO_LOG("Load sink adapter"); const char *deviceClass = pa_modargs_get_value(ma, "device_class", DEFAULT_DEVICE_CLASS); u->primary.sinkAdapter = GetSinkAdapter(deviceClass, pa_modargs_get_value(ma, "network_id", DEFAULT_DEVICE_NETWORKID)); @@ -4639,6 +4639,7 @@ static int32_t PaHdiSinkNewInitUserDataAndSink(pa_module *m, pa_modargs *ma, con pa_sink *PaHdiSinkNew(pa_module *m, pa_modargs *ma, const char *driver) { + AUDIO_INFO_LOG("In"); struct Userdata *u = NULL; char *hdiThreadName = NULL; char *hdiThreadNameMch = NULL; @@ -4798,6 +4799,7 @@ static void FreeLimiter(struct Userdata *u) static void UserdataFree(struct Userdata *u) { + AUDIO_INFO_LOG("In"); if (u == NULL) { AUDIO_INFO_LOG("Userdata is null, free done"); return; @@ -4861,7 +4863,7 @@ static void UserdataFree(struct Userdata *u) void PaHdiSinkFree(pa_sink *s) { AUTO_CTRACE("PaHdiSinkFree"); - AUDIO_INFO_LOG("PaHdiSinkFree, free userdata"); + AUDIO_INFO_LOG("In, PaHdiSinkFree, free userdata"); struct Userdata *u = NULL; pa_sink_assert_ref(s); diff --git a/frameworks/native/pulseaudio/modules/hdi/module_hdi_sink.c b/frameworks/native/pulseaudio/modules/hdi/module_hdi_sink.c index 6de73e1663026cd0232e3be4dd34e5346373d681..6ac5305bca67a2f46ef3600a3f43df9aa81d5942 100644 --- a/frameworks/native/pulseaudio/modules/hdi/module_hdi_sink.c +++ b/frameworks/native/pulseaudio/modules/hdi/module_hdi_sink.c @@ -245,6 +245,7 @@ int pa__get_n_used(pa_module *m) void pa__done(pa_module *m) { + AUDIO_INFO_LOG("In"); CHECK_AND_RETURN_LOG(m != NULL, "pa module is null"); pa_sink *sink = NULL; diff --git a/frameworks/native/toneplayer/BUILD.gn b/frameworks/native/toneplayer/BUILD.gn index d04af5d7ae6d84e391487929964ade9045b307bc..9748a243b78dfb12f15e337b4b131c3256c93671 100644 --- a/frameworks/native/toneplayer/BUILD.gn +++ b/frameworks/native/toneplayer/BUILD.gn @@ -17,6 +17,7 @@ import("../../../config.gni") config("audio_toneplayer_config") { include_dirs = [ "include", + "../audiodefinitions/include", "../audiostream/include", "../audioutils/include", "../audiorenderer/include", diff --git a/interfaces/inner_api/native/audiocommon/include/audio_device_descriptor.h b/interfaces/inner_api/native/audiocommon/include/audio_device_descriptor.h index 1c2198ff555a706cfd9893045a00aef0a8c385c1..9a854dabf7a60e67ab705f75289acc5782108ea8 100644 --- a/interfaces/inner_api/native/audiocommon/include/audio_device_descriptor.h +++ b/interfaces/inner_api/native/audiocommon/include/audio_device_descriptor.h @@ -117,12 +117,16 @@ public: bool IsSameDeviceDesc(const AudioDeviceDescriptor &deviceDescriptor) const; + bool IsSameDeviceDescPtr(std::shared_ptr deviceDescriptor) const; + bool IsSameDeviceInfo(const AudioDeviceDescriptor &deviceInfo) const; bool IsPairedDeviceDesc(const AudioDeviceDescriptor &deviceDescriptor) const; DeviceType MapInternalToExternalDeviceType() const; + void Dump(std::string &dumpString); + struct AudioDeviceDescriptorHash { size_t operator()(const std::shared_ptr &deviceDescriptor) const { diff --git a/interfaces/inner_api/native/audiocommon/include/audio_device_info.h b/interfaces/inner_api/native/audiocommon/include/audio_device_info.h index c9042bf02d458d8ea435b3d6492e8dc9617f61bb..a59a888398854baffc49cf2fcf65e770782a161a 100644 --- a/interfaces/inner_api/native/audiocommon/include/audio_device_info.h +++ b/interfaces/inner_api/native/audiocommon/include/audio_device_info.h @@ -502,4 +502,4 @@ private: }; } // namespace AudioStandard } // namespace OHOS -#endif // AUDIO_DEVICE_INFO_H \ No newline at end of file +#endif // AUDIO_DEVICE_INFO_H diff --git a/interfaces/inner_api/native/audiocommon/include/audio_info.h b/interfaces/inner_api/native/audiocommon/include/audio_info.h index c0aece3e77337ea7aa731eeec15eca33a4528617..15d97d33f2a602c4b5a9d0ef8a0299895e6ec60d 100644 --- a/interfaces/inner_api/native/audiocommon/include/audio_info.h +++ b/interfaces/inner_api/native/audiocommon/include/audio_info.h @@ -941,10 +941,12 @@ enum AudioPin { AUDIO_PIN_OUT_HDMI = 1 << 3, // HDMI output pin AUDIO_PIN_OUT_USB = 1 << 4, // USB output pin AUDIO_PIN_OUT_USB_EXT = 1 << 5, // Extended USB output pin + AUDIO_PIN_OUT_EARPIECE = 1 << 5 | 1 << 4, // Earpiece output pin AUDIO_PIN_OUT_BLUETOOTH_SCO = 1 << 6, // Bluetooth SCO output pin AUDIO_PIN_OUT_DAUDIO_DEFAULT = 1 << 7, // Daudio default output pin AUDIO_PIN_OUT_HEADPHONE = 1 << 8, // Wired headphone output pin AUDIO_PIN_OUT_USB_HEADSET = 1 << 9, // Arm usb output pin + AUDIO_PIN_OUT_BLUETOOTH_A2DP = 1 << 10, // Bluetooth A2dp output pin AUDIO_PIN_OUT_DP = 1 << 11, AUDIO_PIN_IN_MIC = 1 << 27 | 1 << 0, // Microphone input pin AUDIO_PIN_IN_HS_MIC = 1 << 27 | 1 << 1, // Wired headset microphone pin for input @@ -1315,6 +1317,7 @@ struct RestoreInfo { RestoreReason restoreReason = DEFAULT_REASON; int32_t deviceChangeReason = 0; int32_t targetStreamFlag = AUDIO_FLAG_NORMAL; + uint32_t routeFlag = 0; }; } // namespace AudioStandard } // namespace OHOS diff --git a/interfaces/inner_api/native/audiocommon/include/audio_stream_info.h b/interfaces/inner_api/native/audiocommon/include/audio_stream_info.h index deb297aa9936cfb1501cbbd2e602f8cc87f79181..640a4e4e53a65c116c66e81b486c1664a3a8194c 100644 --- a/interfaces/inner_api/native/audiocommon/include/audio_stream_info.h +++ b/interfaces/inner_api/native/audiocommon/include/audio_stream_info.h @@ -250,6 +250,12 @@ enum AudioPipeType { PIPE_TYPE_DIRECT_VOIP = 14, }; +enum AudioPreloadType { + PRELOAD_TYPE_UNKNOWN = -1, + PRELOAD_TYPE_NOTSUPPORT = 0, + PRELOAD_TYPE_SUPPORT = 1, +}; + struct AudioStreamParams { uint32_t samplingRate = 0; uint8_t encoding = 0; @@ -296,6 +302,7 @@ enum AudioSampleFormat : uint8_t { // channel enum AudioChannel : uint8_t { + CHANNEL_UNKNOW = 0, MONO = 1, STEREO = 2, CHANNEL_3 = 3, diff --git a/services/audio_policy/BUILD.gn b/services/audio_policy/BUILD.gn index 9351940b62b747a4259bc2c96816e4c4c86d1712..971976b919e9ff1a903dd2d260b9e4032620b998 100644 --- a/services/audio_policy/BUILD.gn +++ b/services/audio_policy/BUILD.gn @@ -41,6 +41,7 @@ group("audio_policy_packages") { config("audio_policy_public_config") { include_dirs = [ "util/include", + "common/definitions/include", "common/include", "client/include", "server/include", @@ -59,6 +60,9 @@ config("audio_policy_public_config") { "server/src/service/concurrency", "server/src/service/interrupt", "server/src/service/session", + "services/core/config/include", + "services/core/include", + "services/pipe/include", "safe_volume_notification/include", "../audio_service/client/include", "../audio_service/common/include", @@ -66,10 +70,12 @@ config("audio_policy_public_config") { "../../frameworks/native/audioinnercall/include", "../../frameworks/native/audiorenderer/include", "../../frameworks/native/audioadapter/include", + "../../frameworks/native/audiodefinitions/include", "../../frameworks/native/audiopolicy/include", "../../frameworks/native/audioutils/include", "../../frameworks/native/bluetoothclient", "../../frameworks/native/hdiadapter_new/include", + "../../frameworks/native/hdiadapter_new/include/common", "../../interfaces/inner_api/native/audiocommon/include", "../../interfaces/inner_api/native/audiomanager/include", ] @@ -156,10 +162,13 @@ audio_ohos_library("audio_policy_service") { sources = [ "../audio_service/client/src/audio_filter.cpp", "../audio_service/client/src/audio_manager_listener_stub.cpp", + "../audio_service/client/src/core_service_provider_stub.cpp", "../audio_service/client/src/microphone_descriptor.cpp", "../audio_service/client/src/policy_provider_stub.cpp", "client/src/audio_interrupt_group_info.cpp", "client/src/audio_volume_group_info.cpp", + "common/definitions/src/audio_definition_adapter_info.cpp", + "common/definitions/src/audio_definition_policy_utils.cpp", "server/src/app_state_listener.cpp", "server/src/audio_anahs_manager_listener_proxy.cpp", "server/src/audio_client_tracker_callback_proxy.cpp", @@ -244,6 +253,13 @@ audio_ohos_library("audio_policy_service") { "server/src/service/session/audio_session_service.cpp", "server/src/service/session/audio_session_state_monitor.cpp", "server/src/service/spatialization/audio_spatialization_service.cpp", + "services/core/config/src/audio_policy_config_manager.cpp", + "services/core/config/src/audio_policy_config_parser.cpp", + "services/core/src/audio_core_service.cpp", + "services/core/src/audio_core_service_entry.cpp", + "services/core/src/audio_core_service_private.cpp", + "services/pipe/src/audio_pipe_manager.cpp", + "services/pipe/src/audio_pipe_selector.cpp", "util/src/audio_ability_manager.cpp", ] @@ -288,6 +304,7 @@ audio_ohos_library("audio_policy_service") { deps = [ "../../frameworks/native/audioadapter:pulse_audio_service_adapter", + "../../frameworks/native/audiodefinitions:audio_definitions", "../../frameworks/native/audioinnercall:audio_inner_call", "../../frameworks/native/audioutils:audio_utils", "../../frameworks/native/audioutils:audio_xml_utils", @@ -482,6 +499,7 @@ config("audio_policy_client_config") { "server/include", "../audio_service/client/include", "../audio_service/common/include", + "../../frameworks/native/audiodefinitions/include", "../../frameworks/native/audiopolicy/include", "../../interfaces/inner_api/native/audiocommon/include", "../../interfaces/inner_api/native/audiomanager/include", @@ -531,7 +549,10 @@ audio_ohos_library("audio_policy_client") { "client/src/proxy/audio_policy_volume_proxy.cpp", ] - deps = [ "../../frameworks/native/audioutils:audio_utils" ] + deps = [ + "../../frameworks/native/audiodefinitions:audio_definitions", + "../../frameworks/native/audioutils:audio_utils", + ] public_configs = [ ":audio_policy_client_config" ] @@ -675,7 +696,12 @@ ohos_shared_library("audio_foundation") { } config("audio_manager_client_public_config") { - include_dirs = [ "util/include" ] + include_dirs = [ + "util/include", + "../../frameworks/native/audiodefinitions/include", + "../../frameworks/native/audiodefinitions/include/common", + "../../frameworks/native/hdiadapter_new/include/common", + ] } ohos_shared_library("audio_manager_client") { diff --git a/services/audio_policy/client/include/audio_policy_base.h b/services/audio_policy/client/include/audio_policy_base.h index a0dd72d1aec59f70bd7d68b60bcd509fc849b227..edc6a26845853ff290e6813346382b1b56401f42 100644 --- a/services/audio_policy/client/include/audio_policy_base.h +++ b/services/audio_policy/client/include/audio_policy_base.h @@ -25,6 +25,7 @@ #include "audio_system_manager.h" #include "audio_effect.h" #include "microphone_descriptor.h" +#include "audio_stream_descriptor.h" namespace OHOS { namespace AudioStandard { @@ -168,6 +169,12 @@ public: virtual int32_t GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo) = 0; + virtual int32_t CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) = 0; + + virtual int32_t CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) = 0; + virtual int32_t RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, const sptr &object) = 0; diff --git a/services/audio_policy/client/include/audio_policy_manager_stub.h b/services/audio_policy/client/include/audio_policy_manager_stub.h index 455f64a9a2b6199cd90d8bcfd6b36c6598955a18..1abbadca126a68993bfba6a13ed737b9c431433b 100644 --- a/services/audio_policy/client/include/audio_policy_manager_stub.h +++ b/services/audio_policy/client/include/audio_policy_manager_stub.h @@ -81,6 +81,8 @@ private: void ReconfigureAudioChannelInternal(MessageParcel &data, MessageParcel &reply); void GetPreferredOutputStreamTypeInternal(MessageParcel &data, MessageParcel &reply); void GetPreferredInputStreamTypeInternal(MessageParcel &data, MessageParcel &reply); + void CreateRendererClientInternal(MessageParcel &data, MessageParcel &reply); + void CreateCapturerClientInternal(MessageParcel &data, MessageParcel &reply); void RegisterTrackerInternal(MessageParcel &data, MessageParcel &reply); void UpdateTrackerInternal(MessageParcel &data, MessageParcel &reply); void GetRendererChangeInfosInternal(MessageParcel &data, MessageParcel &reply); diff --git a/services/audio_policy/client/include/audio_policy_proxy.h b/services/audio_policy/client/include/audio_policy_proxy.h index 6ae4ddfd84dc5d6378d2f9c8d1d54a5972bdfc4d..ca4a78fa1b38c51a357b7c9222d3d9eac6fac571 100644 --- a/services/audio_policy/client/include/audio_policy_proxy.h +++ b/services/audio_policy/client/include/audio_policy_proxy.h @@ -176,6 +176,12 @@ public: int32_t GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo) override; + int32_t CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) override; + + int32_t CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) override; + int32_t RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, const sptr &object) override; diff --git a/services/audio_policy/client/src/audio_policy_manager.cpp b/services/audio_policy/client/src/audio_policy_manager.cpp index b3a71a3f41ba897050aacb486dda8fa738234949..8957075dfa8790b4dbca690f6e18a6f971b0aba8 100644 --- a/services/audio_policy/client/src/audio_policy_manager.cpp +++ b/services/audio_policy/client/src/audio_policy_manager.cpp @@ -1168,6 +1168,22 @@ int32_t AudioPolicyManager::GetPreferredInputStreamType(AudioCapturerInfo &captu return gsp->GetPreferredInputStreamType(capturerInfo); } +int32_t AudioPolicyManager::CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) +{ + const sptr gsp = GetAudioPolicyManagerProxy(); + CHECK_AND_RETURN_RET_LOG(gsp != nullptr, AUDIO_FLAG_INVALID, "audio policy manager proxy is NULL."); + return gsp->CreateRendererClient(streamDesc, flag, sessionId); +} + +int32_t AudioPolicyManager::CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) +{ + const sptr gsp = GetAudioPolicyManagerProxy(); + CHECK_AND_RETURN_RET_LOG(gsp != nullptr, AUDIO_FLAG_INVALID, "audio policy manager proxy is NULL."); + return gsp->CreateCapturerClient(streamDesc, flag, sessionId); +} + int32_t AudioPolicyManager::GetCurrentRendererChangeInfos( vector> &audioRendererChangeInfos) { diff --git a/services/audio_policy/client/src/proxy/audio_policy_proxy.cpp b/services/audio_policy/client/src/proxy/audio_policy_proxy.cpp index d7078e177056b673c7759909f59aca8aac76e45f..5b7ace7a2462d7c1b98f7003b1edbcc863aa5cdb 100644 --- a/services/audio_policy/client/src/proxy/audio_policy_proxy.cpp +++ b/services/audio_policy/client/src/proxy/audio_policy_proxy.cpp @@ -987,6 +987,52 @@ int32_t AudioPolicyProxy::GetPreferredInputStreamType(AudioCapturerInfo &capture return reply.ReadInt32(); } +int32_t AudioPolicyProxy::CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + bool ret = data.WriteInterfaceToken(GetDescriptor()); + CHECK_AND_RETURN_RET_LOG(ret, AUDIO_FLAG_INVALID, "WriteInterfaceToken failed"); + + ret = streamDesc->Marshalling(data); + CHECK_AND_RETURN_RET_LOG(ret, AUDIO_FLAG_INVALID, "Marshalling capturerInfo failed"); + + int32_t error = Remote()->SendRequest( + static_cast(AudioPolicyInterfaceCode::CREATE_RENDERER_CLIENT), data, reply, option); + CHECK_AND_RETURN_RET_LOG(error == ERR_NONE, AUDIO_FLAG_INVALID, "Failed to send request, error: %{public}d", error); + + flag = static_cast(reply.ReadUint32()); + sessionId = reply.ReadUint32(); + + return reply.ReadInt32(); +} + +int32_t AudioPolicyProxy::CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + bool ret = data.WriteInterfaceToken(GetDescriptor()); + CHECK_AND_RETURN_RET_LOG(ret, AUDIO_FLAG_INVALID, "WriteInterfaceToken failed"); + + ret = streamDesc->Marshalling(data); + CHECK_AND_RETURN_RET_LOG(ret, AUDIO_FLAG_INVALID, "Marshalling capturerInfo failed"); + + int32_t error = Remote()->SendRequest( + static_cast(AudioPolicyInterfaceCode::CREATE_CAPTURER_CLIENT), data, reply, option); + CHECK_AND_RETURN_RET_LOG(error == ERR_NONE, AUDIO_FLAG_INVALID, "Failed to send request, error: %{public}d", error); + + flag = static_cast(reply.ReadUint32()); + sessionId = reply.ReadUint32(); + + return reply.ReadInt32(); +} + int32_t AudioPolicyProxy::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, const sptr &object) { diff --git a/services/audio_policy/common/definitions/BUILD.GN b/services/audio_policy/common/definitions/BUILD.GN new file mode 100644 index 0000000000000000000000000000000000000000..c4f09101391d6995a56bec4ff8ea6dca317e3fbe --- /dev/null +++ b/services/audio_policy/common/definitions/BUILD.GN @@ -0,0 +1,57 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# 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. + +import("//build/ohos.gni") +import("../../../config.gni") +config("audio_utils_public_config") { + include_dirs = [ "./include" ] + + cflags_cc = [ "-std=c++20" ] +} + +ohos_shared_library("audio_server_definitions") { + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + cfi_vcall_icall_only = true + debug = false + } + public_configs = [ ":audio_utils_public_config" ] + install_enable = true + include_dirs = [ + "./include", + ] + + sources = [ + "./src/audio_service_definiton.cpp", + ] + + public_external_deps = [ "bounds_checking_function:libsec_shared" ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_single", + ] + + defines = [] + + if (build_variant == "user") { + defines += [ "AUDIO_BUILD_VARIANT_USER" ] + } else if (build_variant == "root") { + defines += [ "AUDIO_BUILD_VARIANT_ROOT" ] + } + + subsystem_name = "multimedia" + part_name = "audio_framework" +} diff --git a/services/audio_policy/common/definitions/include/audio_definition_adapter_info.h b/services/audio_policy/common/definitions/include/audio_definition_adapter_info.h index 593b3aaf9be36ae0d565ec6798d7b622d945f47c..ab43dafa545baae553e480f2b3d80d0c6cccbcec 100644 --- a/services/audio_policy/common/definitions/include/audio_definition_adapter_info.h +++ b/services/audio_policy/common/definitions/include/audio_definition_adapter_info.h @@ -117,7 +117,7 @@ public: AudioSampleFormat format_ = INVALID_WIDTH; uint32_t sampleRate_ = 0; AudioChannelLayout channelLayout_ = CH_LAYOUT_UNKNOWN; - AudioChannel channels_ = CHANNEL_UNKNOWN; + AudioChannel channels_ = CHANNEL_UNKNOW; uint32_t bufferSize_ = 0; std::weak_ptr pipeInfo_; @@ -205,7 +205,7 @@ public: std::unordered_map> adapterInfoMap {}; std::unordered_map, - std::vector>, pairHash> deviceInfoMap {}; + std::vector>, PairHash> deviceInfoMap {}; private: AudioPolicyConfigData() = default; AudioPolicyConfigData(const AudioPolicyConfigData&) = delete; diff --git a/services/audio_policy/common/definitions/include/audio_service_enum.h b/services/audio_policy/common/definitions/include/audio_service_enum.h new file mode 100644 index 0000000000000000000000000000000000000000..7a22f39689d2e96c15ee1e156bacd04064f7af9a --- /dev/null +++ b/services/audio_policy/common/definitions/include/audio_service_enum.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef AUDIO_SERVICE_ENUM_H +#define AUDIO_SERVICE_ENUM_H +#include + +namespace OHOS { +namespace AudioStandard { +enum SessionOperation : uint32_t { + SESSION_OPERATION_START = 0, + SESSION_OPERATION_PAUSE, + SESSION_OPERATION_STOP, + SESSION_OPERATION_RELEASE, +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // AUDIO_SERVICE_ENUM_H diff --git a/services/audio_policy/common/definitions/src/audio_definition_adapter_info.cpp b/services/audio_policy/common/definitions/src/audio_definition_adapter_info.cpp index 66253eb20972bd6cc91310bb72c38ff3a229edfd..a627fab37ad6f5a444609c47813c557d409f6fb8 100644 --- a/services/audio_policy/common/definitions/src/audio_definition_adapter_info.cpp +++ b/services/audio_policy/common/definitions/src/audio_definition_adapter_info.cpp @@ -36,12 +36,12 @@ void AudioPolicyConfigData::SetDeviceInfoMap(std::list deviceMapKey = std::make_pair(deviceInfo->type_, deviceInfo->role); + std::pair deviceMapKey = std::make_pair(deviceInfo->type_, deviceInfo->role_); auto deviceInfoIt = deviceInfoMap.find(deviceMapKey); if (deviceInfoIt != deviceInfoMap.end()) { deviceInfoIt->second.push_back(deviceInfo); } else { - std::vector deviceVector; + std::vector> deviceVector; deviceVector.push_back(deviceInfo); deviceInfoMap.insert({deviceMapKey, deviceVector}); } @@ -117,7 +117,7 @@ std::shared_ptr AudioPolicyConfigData::GetAdapterDeviceInfo( // use primary to select device when in remote cast; DeviceType tempType = (type_ == DEVICE_TYPE_REMOTE_CAST ? DEVICE_TYPE_SPEAKER : type_); - std::pair deviceMapKey = std::make_pair(tempType, role); + std::pair deviceMapKey = std::make_pair(tempType, role_); auto deviceVectorIt = deviceInfoMap.find(deviceMapKey); if (deviceVectorIt == deviceInfoMap.end()) { AUDIO_ERR_LOG("Device Not Configured!"); diff --git a/services/audio_policy/common/definitions/src/audio_definition_policy_utils.cpp b/services/audio_policy/common/definitions/src/audio_definition_policy_utils.cpp index 24bce8b41769f5874c002fd128677b00a3984fa7..e5d6cf6e1389dc3429a2b08b5cbb17e7d0bab9f6 100644 --- a/services/audio_policy/common/definitions/src/audio_definition_policy_utils.cpp +++ b/services/audio_policy/common/definitions/src/audio_definition_policy_utils.cpp @@ -193,7 +193,7 @@ uint32_t AudioDefinitionPolicyUtils::PcmFormatToBytes(AudioSampleFormat format) AudioChannel AudioDefinitionPolicyUtils::ConvertLayoutToAudioChannel(AudioChannelLayout layout) { - AudioChannel channel = AudioChannel::CHANNEL_UNKNOWN; + AudioChannel channel = AudioChannel::CHANNEL_UNKNOW; switch (layout) { case AudioChannelLayout::CH_LAYOUT_MONO: channel = AudioChannel::MONO; @@ -230,7 +230,7 @@ AudioChannel AudioDefinitionPolicyUtils::ConvertLayoutToAudioChannel(AudioChanne channel = AudioChannel::CHANNEL_12; break; default: - channel = AudioChannel::CHANNEL_UNKNOWN; + channel = AudioChannel::CHANNEL_UNKNOW; break; } return channel; diff --git a/services/audio_policy/common/include/audio_policy_ipc_interface_code.h b/services/audio_policy/common/include/audio_policy_ipc_interface_code.h index 05b2148d2d2fbecde04859b434ee9ff87779ec39..050f97c42fa885e2421188bd5943e673d0346a16 100644 --- a/services/audio_policy/common/include/audio_policy_ipc_interface_code.h +++ b/services/audio_policy/common/include/audio_policy_ipc_interface_code.h @@ -70,6 +70,8 @@ enum class AudioPolicyInterfaceCode { GET_SINK_LATENCY, GET_PREFERRED_OUTPUT_STREAM_TYPE, GET_PREFERRED_INPUT_STREAM_TYPE, + CREATE_RENDERER_CLIENT, + CREATE_CAPTURER_CLIENT, REGISTER_TRACKER, UPDATE_TRACKER, GET_RENDERER_CHANGE_INFOS, diff --git a/services/audio_policy/server/include/audio_policy_server.h b/services/audio_policy/server/include/audio_policy_server.h index a9b967c5e206649469bd8f85d9db77c41257f146..43df1329f26f3564a0c5e8a387675469edd83b00 100644 --- a/services/audio_policy/server/include/audio_policy_server.h +++ b/services/audio_policy/server/include/audio_policy_server.h @@ -49,6 +49,7 @@ #include "audio_device_manager.h" #include "audio_policy_dump.h" #include "app_state_listener.h" +#include "audio_core_service.h" namespace OHOS { namespace AudioStandard { @@ -246,6 +247,12 @@ public: int32_t GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo) override; + int32_t CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) override; + + int32_t CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) override; + int32_t RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, const sptr &object) override; @@ -510,6 +517,7 @@ public: void EffectManagerInfoDump(std::string &dumpString); void MicrophoneMuteInfoDump(std::string &dumpString); void AudioSessionInfoDump(std::string &dumpString); + void AudioPipeManagerDump(std::string &dumpString); // for hibernate callback void CheckHibernateState(bool hibernate); @@ -649,6 +657,9 @@ private: AudioDeviceManager &audioDeviceManager_; std::shared_ptr interruptService_; + std::shared_ptr coreService_; + std::shared_ptr eventEntry_; + int32_t volumeStep_; std::atomic isFirstAudioServiceStart_ = false; std::atomic isInitMuteState_ = false; diff --git a/services/audio_policy/server/include/audio_policy_server_handler.h b/services/audio_policy/server/include/audio_policy_server_handler.h index 8b65996a91d5713c30dc312638ca61635b0da238..b62dd08a6bd63043b6014ea519381fb6baa1814d 100644 --- a/services/audio_policy/server/include/audio_policy_server_handler.h +++ b/services/audio_policy/server/include/audio_policy_server_handler.h @@ -106,6 +106,7 @@ public: std::unordered_map headTrackingDeviceChangeInfo; AudioStreamDeviceChangeReasonExt reason_ = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN; std::pair sessionDeactivePair; + uint32_t routeFlag; }; struct RendererDeviceChangeEvent { @@ -185,9 +186,9 @@ public: uint64_t sessionId, bool isSync, int32_t &error); bool SendCapturerRemovedEvent(uint64_t sessionId, bool isSync); bool SendWakeupCloseEvent(bool isSync); - bool SendRecreateRendererStreamEvent(int32_t clientId, uint32_t sessionID, int32_t streamFlag, + bool SendRecreateRendererStreamEvent(int32_t clientId, uint32_t sessionID, uint32_t routeFlag, const AudioStreamDeviceChangeReasonExt reason); - bool SendRecreateCapturerStreamEvent(int32_t clientId, uint32_t sessionID, int32_t streamFlag, + bool SendRecreateCapturerStreamEvent(int32_t clientId, uint32_t sessionID, uint32_t routeFlag, const AudioStreamDeviceChangeReasonExt reason); bool SendHeadTrackingDeviceChangeEvent(const std::unordered_map &changeInfo); void AddAudioDeviceRefinerCb(const sptr &callback); diff --git a/services/audio_policy/server/include/audio_stream_collector.h b/services/audio_policy/server/include/audio_stream_collector.h index 7bfb81470927465657f1d2a4db364609ee40b91b..4679db5f5de9091746acb72029b28dc5477636e6 100644 --- a/services/audio_policy/server/include/audio_stream_collector.h +++ b/services/audio_policy/server/include/audio_stream_collector.h @@ -45,8 +45,10 @@ public: int32_t UpdateTrackerInternal(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo); AudioStreamType GetStreamType(ContentType contentType, StreamUsage streamUsage); int32_t UpdateRendererDeviceInfo(int32_t clientUID, int32_t sessionId, AudioDeviceDescriptor &outputDeviceInfo); + int32_t UpdateRendererDeviceInfo(std::shared_ptr outputDeviceInfo); int32_t UpdateRendererPipeInfo(const int32_t sessionId, const AudioPipeType pipeType); int32_t UpdateCapturerDeviceInfo(int32_t clientUID, int32_t sessionId, AudioDeviceDescriptor &inputDeviceInfo); + int32_t UpdateCapturerDeviceInfo(std::shared_ptr inputDeviceInfo); int32_t GetCurrentRendererChangeInfos(std::vector> &rendererChangeInfos); int32_t GetCurrentCapturerChangeInfos(std::vector> &capturerChangeInfos); void RegisteredTrackerClientDied(int32_t uid); @@ -73,6 +75,7 @@ public: int32_t SetAudioConcurrencyCallback(const uint32_t sessionID, const sptr &object); int32_t UnsetAudioConcurrencyCallback(const uint32_t sessionID); int32_t ActivateAudioConcurrency(const AudioPipeType &pipeType); + std::map, ConcurrencyAction>& GetConcurrencyMap(); void ResetRendererStreamDeviceInfo(const AudioDeviceDescriptor& updatedDesc); void ResetCapturerStreamDeviceInfo(const AudioDeviceDescriptor& updatedDesc); StreamUsage GetRunningStreamUsageNoUltrasonic(); diff --git a/services/audio_policy/server/include/service/audio_policy_service.h b/services/audio_policy/server/include/service/audio_policy_service.h index c6e200518edb36359d3eeb5de58b997ccfc0e336..77ca4aed2136541bed9adb047695d519726ea8ab 100644 --- a/services/audio_policy/server/include/service/audio_policy_service.h +++ b/services/audio_policy/server/include/service/audio_policy_service.h @@ -61,7 +61,7 @@ #include "audio_a2dp_offload_manager.h" #include "audio_iohandle_map.h" #include "audio_router_map.h" -#include "audio_config_manager.h" +#include "audio_policy_config_manager.h" #include "audio_connected_device.h" #include "audio_tone_manager.h" #include "audio_microphone_descriptor.h" @@ -508,7 +508,7 @@ private: audioGlobalConfigManager_(AudioGlobalConfigManager::GetAudioGlobalConfigManager()), audioIOHandleMap_(AudioIOHandleMap::GetInstance()), audioRouteMap_(AudioRouteMap::GetInstance()), - audioConfigManager_(AudioConfigManager::GetInstance()), + audioConfigManager_(AudioPolicyConfigManager::GetInstance()), audioConnectedDevice_(AudioConnectedDevice::GetInstance()), audioToneManager_(AudioToneManager::GetInstance()), audioMicrophoneDescriptor_(AudioMicrophoneDescriptor::GetInstance()), @@ -655,7 +655,7 @@ private: AudioIOHandleMap& audioIOHandleMap_; AudioRouteMap& audioRouteMap_; - AudioConfigManager& audioConfigManager_; + AudioPolicyConfigManager& audioConfigManager_; AudioConnectedDevice& audioConnectedDevice_; AudioToneManager& audioToneManager_; AudioMicrophoneDescriptor& audioMicrophoneDescriptor_; diff --git a/services/audio_policy/server/include/service/common/audio_module_info.h b/services/audio_policy/server/include/service/common/audio_module_info.h index d866040f7b04b5aa3ffd945485807faca0e44ae2..510b1b99ea385e61d6caf83233645a1704955c4b 100644 --- a/services/audio_policy/server/include/service/common/audio_module_info.h +++ b/services/audio_policy/server/include/service/common/audio_module_info.h @@ -85,6 +85,12 @@ enum ClassType { TYPE_INVALID }; +enum AudioPipeRole { + PIPE_ROLE_OUTPUT = 0, + PIPE_ROLE_INPUT, + PIPE_ROLE_NONE, +}; + struct AudioModuleInfo { std::string className; std::string name; @@ -125,6 +131,7 @@ struct AudioModuleInfo { std::list ports; std::string extra; + AudioPipeRole pipeRole; }; } // namespace AudioStandard diff --git a/services/audio_policy/server/include/service/interface/iaudio_policy_interface.h b/services/audio_policy/server/include/service/interface/iaudio_policy_interface.h index 16a9917b147ca8830b9caf69515089c9aaf99318..cd5feecbb780d15d1d8dfe51a9da2cd750cf47ac 100644 --- a/services/audio_policy/server/include/service/interface/iaudio_policy_interface.h +++ b/services/audio_policy/server/include/service/interface/iaudio_policy_interface.h @@ -15,6 +15,7 @@ #ifndef I_AUDIO_POLICY_INTERFACE_H #define I_AUDIO_POLICY_INTERFACE_H +#define HDI_INVALID_ID 0xFFFFFFFF #include "audio_adapter_info.h" #include "audio_policy_manager.h" @@ -23,6 +24,7 @@ #include "audio_volume_config.h" #include "volume_data_maintainer.h" #include "audio_manager_base.h" +#include "audio_pipe_info.h" #include #include @@ -76,9 +78,11 @@ public: virtual std::vector GetAllSourceOutputs() = 0; - virtual AudioIOHandle OpenAudioPort(const AudioModuleInfo &audioPortInfo) = 0; + virtual AudioIOHandle OpenAudioPort(std::shared_ptr pipeInfo, uint32_t &paIndex) = 0; - virtual int32_t CloseAudioPort(AudioIOHandle ioHandle, bool isSync = false) = 0; + virtual AudioIOHandle OpenAudioPort(const AudioModuleInfo &audioPortInfo, uint32_t &paIndex) = 0; + + virtual int32_t CloseAudioPort(AudioIOHandle ioHandle, uint32_t paIndex = HDI_INVALID_ID, bool isSync = false) = 0; virtual int32_t SelectDevice(DeviceRole deviceRole, InternalDeviceType deviceType, std::string name) = 0; diff --git a/services/audio_policy/server/include/service/manager/audio_adapter_manager.h b/services/audio_policy/server/include/service/manager/audio_adapter_manager.h index a1f36630cfa5f7f16554fb6eabe78c936d523b06..2dce42b6824cd1fc4fa0beedace0b029d8710b92 100644 --- a/services/audio_policy/server/include/service/manager/audio_adapter_manager.h +++ b/services/audio_policy/server/include/service/manager/audio_adapter_manager.h @@ -30,6 +30,8 @@ #include "audio_volume_config.h" #include "volume_data_maintainer.h" #include "audio_utils.h" +#include "common/hdi_adapter_info.h" +#include "hdi_adapter_type.h" namespace OHOS { namespace AudioStandard { @@ -58,6 +60,11 @@ public: static constexpr uint32_t KVSTORE_CONNECT_RETRY_DELAY_TIME = 200000; static constexpr float MIN_VOLUME = 0.0f; static constexpr uint32_t NUMBER_TWO = 2; + static constexpr float HDI_MAX_SINK_VOLUME_LEVEL = 1.0f; + static constexpr uint32_t HDI_DEFAULT_MULTICHANNEL_CHANNELLAYOUT = 1551; + static constexpr uint32_t HDI_EC_SAME_ADAPTER = 1; + static constexpr std::string_view HDI_AUDIO_PORT_SINK_ROLE = "sink"; + static constexpr std::string_view HDI_AUDIO_PORT_SOURCE_ROLE = "source"; bool Init(); void Deinit(void); void InitKVStore(); @@ -110,9 +117,11 @@ public: std::vector GetAllSourceOutputs(); - AudioIOHandle OpenAudioPort(const AudioModuleInfo &audioModuleInfo); + AudioIOHandle OpenAudioPort(std::shared_ptr pipeInfo, uint32_t &paIndex); - int32_t CloseAudioPort(AudioIOHandle ioHandle, bool isSync = false); + AudioIOHandle OpenAudioPort(const AudioModuleInfo &audioPortInfo, uint32_t &paIndex); + + int32_t CloseAudioPort(AudioIOHandle ioHandle, uint32_t paIndex = HDI_INVALID_ID, bool isSync = false); int32_t SelectDevice(DeviceRole deviceRole, InternalDeviceType deviceType, std::string name); @@ -173,6 +182,16 @@ public: std::string GetModuleArgs(const AudioModuleInfo &audioModuleInfo) const; + std::string GetHdiSinkIdInfo(const AudioModuleInfo &audioModuleInfo) const; + + std::string GetSinkIdInfo(std::shared_ptr pipeInfo) const; + + std::string GetHdiSourceIdInfo(const AudioModuleInfo &audioModuleInfo) const; + + IAudioSinkAttr GetAudioSinkAttr(const AudioModuleInfo &audioModuleInfo) const; + + IAudioSourceAttr GetAudioSourceAttr(const AudioModuleInfo &audioModuleInfo) const; + void ResetRemoteCastDeviceVolume(); int32_t GetStreamVolume(AudioStreamType streamType); @@ -299,6 +318,12 @@ private: void SetVolumeCallbackAfterClone(); void SetFirstBoot(); void MaximizeVoiceAssistantVolume(InternalDeviceType deviceType); + bool IsPaRoute(uint32_t routeFlag); + AudioIOHandle OpenPaAudioPort(std::shared_ptr pipeInfo, uint32_t &paIndex, std::string moduleArgs); + AudioIOHandle OpenNotPaAudioPort(std::shared_ptr pipeInfo, uint32_t &paIndex); + void GetSinkIdInfoAndIdType(std::shared_ptr pipeInfo, std::string &idInfo, HdiIdType &idType); + void GetSourceIdInfoAndIdType(std::shared_ptr pipeInfo, std::string &idInfo, HdiIdType &idType); + template std::vector TransferTypeToByteArray(const T &t) { diff --git a/services/audio_policy/server/include/service/service/audio_a2dp_offload_manager.h b/services/audio_policy/server/include/service/service/audio_a2dp_offload_manager.h index 2fb44e0f2f564e87922b54e67b5f1b256b0ce3c8..f251c482f9909409c74af584da16aab14d6eefb2 100644 --- a/services/audio_policy/server/include/service/service/audio_a2dp_offload_manager.h +++ b/services/audio_policy/server/include/service/service/audio_a2dp_offload_manager.h @@ -42,7 +42,7 @@ #include "audio_volume_manager.h" #include "audio_a2dp_offload_flag.h" #include "audio_iohandle_map.h" -#include "audio_config_manager.h" +#include "audio_policy_config_manager.h" #include "audio_active_device.h" #include "audio_offload_stream.h" @@ -58,7 +58,7 @@ public: audioRouterCenter_(AudioRouterCenter::GetAudioRouterCenter()), audioIOHandleMap_(AudioIOHandleMap::GetInstance()), audioActiveDevice_(AudioActiveDevice::GetInstance()), - audioConfigManager_(AudioConfigManager::GetInstance()), + audioConfigManager_(AudioPolicyConfigManager::GetInstance()), audioVolumeManager_(AudioVolumeManager::GetInstance()), audioOffloadStream_(AudioOffloadStream::GetInstance()), audioDeviceCommon_(AudioDeviceCommon::GetInstance()) @@ -106,7 +106,7 @@ private: AudioRouterCenter& audioRouterCenter_; AudioIOHandleMap& audioIOHandleMap_; AudioActiveDevice& audioActiveDevice_; - AudioConfigManager& audioConfigManager_; + AudioPolicyConfigManager& audioConfigManager_; AudioVolumeManager& audioVolumeManager_; AudioOffloadStream& audioOffloadStream_; AudioDeviceCommon& audioDeviceCommon_; diff --git a/services/audio_policy/server/include/service/service/audio_capturer_session.h b/services/audio_policy/server/include/service/service/audio_capturer_session.h index db636fad3dd5fd749546c0d74caaa7cb14acf929..07c2c2862fafb3720475cce6e7d38522b1ae6893 100644 --- a/services/audio_policy/server/include/service/service/audio_capturer_session.h +++ b/services/audio_policy/server/include/service/service/audio_capturer_session.h @@ -34,7 +34,7 @@ #include "audio_iohandle_map.h" #include "audio_active_device.h" -#include "audio_config_manager.h" +#include "audio_policy_config_manager.h" #include "audio_connected_device.h" #include "audio_ec_manager.h" #include "audio_device_common.h" @@ -71,7 +71,7 @@ private: audioRouterCenter_(AudioRouterCenter::GetAudioRouterCenter()), audioIOHandleMap_(AudioIOHandleMap::GetInstance()), audioActiveDevice_(AudioActiveDevice::GetInstance()), - audioConfigManager_(AudioConfigManager::GetInstance()), + audioConfigManager_(AudioPolicyConfigManager::GetInstance()), audioConnectedDevice_(AudioConnectedDevice::GetInstance()), audioEcManager_(AudioEcManager::GetInstance()), audioDeviceCommon_(AudioDeviceCommon::GetInstance()), @@ -89,7 +89,7 @@ private: bool ConstructWakeupAudioModuleInfo(const AudioStreamInfo &streamInfo, AudioModuleInfo &audioModuleInfo); - bool FillWakeupStreamPropInfo(const AudioStreamInfo &streamInfo, PipeInfo *pipeInfo, + bool FillWakeupStreamPropInfo(const AudioStreamInfo &streamInfo, std::shared_ptr pipeInfo, AudioModuleInfo &audioModuleInfo); int32_t SetWakeUpAudioCapturer(InternalAudioCapturerOptions options); @@ -104,7 +104,7 @@ private: AudioRouterCenter& audioRouterCenter_; AudioIOHandleMap& audioIOHandleMap_; AudioActiveDevice& audioActiveDevice_; - AudioConfigManager& audioConfigManager_; + AudioPolicyConfigManager& audioConfigManager_; AudioConnectedDevice& audioConnectedDevice_; AudioEcManager& audioEcManager_; AudioDeviceCommon& audioDeviceCommon_; diff --git a/services/audio_policy/server/include/service/service/audio_device_common.h b/services/audio_policy/server/include/service/service/audio_device_common.h index 0d8a06f3be5a411e0b2121bacc4153cfb9e70cd9..76618750602e313365431abc6bea3077e5c39b17 100644 --- a/services/audio_policy/server/include/service/service/audio_device_common.h +++ b/services/audio_policy/server/include/service/service/audio_device_common.h @@ -38,7 +38,7 @@ #include "audio_a2dp_device.h" #include "audio_a2dp_offload_flag.h" -#include "audio_config_manager.h" +#include "audio_policy_config_manager.h" #include "audio_active_device.h" #include "audio_iohandle_map.h" #include "audio_router_map.h" @@ -127,7 +127,7 @@ private: audioAffinityManager_(AudioAffinityManager::GetAudioAffinityManager()), audioIOHandleMap_(AudioIOHandleMap::GetInstance()), audioActiveDevice_(AudioActiveDevice::GetInstance()), - audioConfigManager_(AudioConfigManager::GetInstance()), + audioConfigManager_(AudioPolicyConfigManager::GetInstance()), audioSceneManager_(AudioSceneManager::GetInstance()), audioVolumeManager_(AudioVolumeManager::GetInstance()), audioRouteMap_(AudioRouteMap::GetInstance()), @@ -270,7 +270,7 @@ private: AudioAffinityManager &audioAffinityManager_; AudioIOHandleMap& audioIOHandleMap_; AudioActiveDevice& audioActiveDevice_; - AudioConfigManager& audioConfigManager_; + AudioPolicyConfigManager& audioConfigManager_; AudioSceneManager& audioSceneManager_; AudioVolumeManager& audioVolumeManager_; AudioRouteMap& audioRouteMap_; diff --git a/services/audio_policy/server/include/service/service/audio_device_status.h b/services/audio_policy/server/include/service/service/audio_device_status.h index e0c9c06e563c57a5b4f4138cbd30eba330edd10e..0fee22f16c8bd0ec36768521395c2cbe5fc9ba9b 100644 --- a/services/audio_policy/server/include/service/service/audio_device_status.h +++ b/services/audio_policy/server/include/service/service/audio_device_status.h @@ -44,7 +44,7 @@ #include "audio_a2dp_device.h" #include "audio_ec_manager.h" #include "audio_a2dp_offload_flag.h" -#include "audio_config_manager.h" +#include "audio_policy_config_manager.h" #include "audio_router_map.h" #include "audio_a2dp_offload_manager.h" #include "audio_spatialization_service.h" @@ -96,7 +96,7 @@ private: audioA2dpDevice_(AudioA2dpDevice::GetInstance()), audioEcManager_(AudioEcManager::GetInstance()), audioA2dpOffloadFlag_(AudioA2dpOffloadFlag::GetInstance()), - audioConfigManager_(AudioConfigManager::GetInstance()), + audioConfigManager_(AudioPolicyConfigManager::GetInstance()), audioRouteMap_(AudioRouteMap::GetInstance()) {} ~AudioDeviceStatus() {} @@ -171,7 +171,7 @@ private: AudioA2dpDevice& audioA2dpDevice_; AudioEcManager& audioEcManager_; AudioA2dpOffloadFlag& audioA2dpOffloadFlag_; - AudioConfigManager& audioConfigManager_; + AudioPolicyConfigManager& audioConfigManager_; AudioRouteMap& audioRouteMap_; bool remoteCapturerSwitch_ = false; diff --git a/services/audio_policy/server/include/service/service/audio_ec_manager.h b/services/audio_policy/server/include/service/service/audio_ec_manager.h index 8449ebcf7f456e81a4aceb01ad987b4fc59896c1..53f53a3d93d10714bbda1dbc2e80d52a497453ec 100644 --- a/services/audio_policy/server/include/service/service/audio_ec_manager.h +++ b/services/audio_policy/server/include/service/service/audio_ec_manager.h @@ -30,7 +30,7 @@ #include "audio_router_center.h" #include "audio_policy_manager_factory.h" -#include "audio_config_manager.h" +#include "audio_policy_config_manager.h" #include "audio_active_device.h" #include "audio_iohandle_map.h" @@ -46,7 +46,7 @@ public: } void Init(int32_t ecEnableState, int32_t micRefEnableState); - void PrepareAndOpenNormalSource(SessionInfo &sessionInfo, StreamPropInfo &targetInfo, SourceType targetSource); + void PrepareAndOpenNormalSource(SessionInfo &sessionInfo, PipeStreamPropInfo &targetInfo, SourceType targetSource); void CloseNormalSource(); AudioEcInfo GetAudioEcInfo(); void ResetAudioEcInfo(); @@ -56,7 +56,7 @@ public: void CloseUsbArmDevice(const AudioDeviceDescriptor &device); void GetTargetSourceTypeAndMatchingFlag(SourceType source, SourceType &targetSource, bool &useMatchingPropInfo); - int32_t FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo, StreamPropInfo &targetInfo, + int32_t FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo, PipeStreamPropInfo &targetInfo, SourceType &targetSourceType); void ReloadSourceForSession(SessionInfo sessionInfo); @@ -72,11 +72,11 @@ private: audioRouterCenter_(AudioRouterCenter::GetAudioRouterCenter()), audioIOHandleMap_(AudioIOHandleMap::GetInstance()), audioActiveDevice_(AudioActiveDevice::GetInstance()), - audioConfigManager_(AudioConfigManager::GetInstance()) {} + audioConfigManager_(AudioPolicyConfigManager::GetInstance()) {} ~AudioEcManager() {} void UpdateEnhanceEffectState(SourceType source); - void UpdateStreamCommonInfo(AudioModuleInfo &moduleInfo, StreamPropInfo &targetInfo, SourceType sourceType); + void UpdateStreamCommonInfo(AudioModuleInfo &moduleInfo, PipeStreamPropInfo &targetInfo, SourceType sourceType); void UpdateStreamEcInfo(AudioModuleInfo &moduleInfo, SourceType sourceType); void UpdateStreamMicRefInfo(AudioModuleInfo &moduleInfo, SourceType sourceType); void UpdateAudioEcInfo(const AudioDeviceDescriptor &inputDevice, const AudioDeviceDescriptor &outputDevice); @@ -85,11 +85,12 @@ private: std::string ShouldOpenMicRef(SourceType source); EcType GetEcType(const DeviceType inputDevice, const DeviceType outputDevice); - std::string GetEcSamplingRate(const std::string &halName, StreamPropInfo &streamPropInfo); - std::string GetEcFormat(const std::string &halName, StreamPropInfo &streamPropInfo); - std::string GetEcChannels(const std::string &halName, StreamPropInfo &streamPropInfo); + std::string GetEcSamplingRate(const std::string &halName, std::shared_ptr &outModuleInfo); + std::string GetEcFormat(const std::string &halName, std::shared_ptr &outModuleInfo); + std::string GetEcChannels(const std::string &halName, std::shared_ptr &outModuleInfo); - int32_t GetPipeInfoByDeviceTypeForEc(const std::string &role, const DeviceType deviceType, PipeInfo &pipeInfo); + int32_t GetPipeInfoByDeviceTypeForEc(const std::string &role, const DeviceType deviceType, + std::shared_ptr pipeInfo); void UpdateArmModuleInfo(const string &address, const DeviceRole role, AudioModuleInfo &moduleInfo); std::string GetHalNameForDevice(const std::string &role, const DeviceType deviceType); @@ -116,10 +117,9 @@ private: AudioRouterCenter& audioRouterCenter_; AudioIOHandleMap& audioIOHandleMap_; AudioActiveDevice& audioActiveDevice_; - AudioConfigManager& audioConfigManager_; + AudioPolicyConfigManager& audioConfigManager_; }; } } - -#endif \ No newline at end of file +#endif diff --git a/services/audio_policy/server/include/service/service/audio_policy_dump.h b/services/audio_policy/server/include/service/service/audio_policy_dump.h index 0ddd4ed2ffb2eba20f1fa49850dcbdb4565abf7b..08a0fff1d32d01467930428d23ed5ae1a0d5149e 100644 --- a/services/audio_policy/server/include/service/service/audio_policy_dump.h +++ b/services/audio_policy/server/include/service/service/audio_policy_dump.h @@ -32,7 +32,7 @@ #include "audio_effect_service.h" #include "audio_active_device.h" -#include "audio_config_manager.h" +#include "audio_policy_config_manager.h" #include "audio_scene_manager.h" #include "audio_volume_manager.h" #include "audio_connected_device.h" @@ -78,12 +78,13 @@ private: void GetGroupInfoDump(std::string &dumpString); void GetCapturerStreamDump(std::string &dumpString); - + void AudioPolicyParserDumpAdapterInfo(std::string &dumpString, + std::unordered_map>& adapterInfoMap); + void AudioPolicyParserDumpPipeInfo(std::string &dumpString, std::shared_ptr &adapterInfo); void AudioPolicyParserDumpInner(std::string &dumpString, - const std::unordered_map& adapterInfoMap, const std::unordered_map& volumeGroupData, std::unordered_map& interruptGroupData, - GlobalConfigs globalConfigs); + PolicyGlobalConfigs globalConfigs); void GetEffectManagerInfo(); bool IsStreamSupported(AudioStreamType streamType); private: @@ -91,7 +92,7 @@ private: audioEffectService_(AudioEffectService::GetAudioEffectService()), streamCollector_(AudioStreamCollector::GetAudioStreamCollector()), audioActiveDevice_(AudioActiveDevice::GetInstance()), - audioConfigManager_(AudioConfigManager::GetInstance()), + audioConfigManager_(AudioPolicyConfigManager::GetInstance()), audioSceneManager_(AudioSceneManager::GetInstance()), audioVolumeManager_(AudioVolumeManager::GetInstance()), audioConnectedDevice_(AudioConnectedDevice::GetInstance()), @@ -105,7 +106,7 @@ private: AudioEffectService& audioEffectService_; AudioStreamCollector& streamCollector_; AudioActiveDevice& audioActiveDevice_; - AudioConfigManager& audioConfigManager_; + AudioPolicyConfigManager& audioConfigManager_; AudioSceneManager& audioSceneManager_; AudioVolumeManager& audioVolumeManager_; AudioConnectedDevice& audioConnectedDevice_; diff --git a/services/audio_policy/server/include/service/service/audio_policy_utils.h b/services/audio_policy/server/include/service/service/audio_policy_utils.h index 8cc3b431832a964d9d9820e630319edc9be3fbfb..0189ddaa56b847391a2ac58987d97e2210c588b7 100644 --- a/services/audio_policy/server/include/service/service/audio_policy_utils.h +++ b/services/audio_policy/server/include/service/service/audio_policy_utils.h @@ -59,7 +59,8 @@ public: std::string GetNewSinkPortName(DeviceType deviceType); std::string GetSinkPortName(DeviceType deviceType, AudioPipeType pipeType = PIPE_TYPE_UNKNOWN); string ConvertToHDIAudioFormat(AudioSampleFormat sampleFormat); - std::string GetSinkName(const AudioDeviceDescriptor& desc, int32_t sessionId); + std::string GetSinkName(const AudioDeviceDescriptor &desc, int32_t sessionId); + std::string GetSinkName(std::shared_ptr desc, int32_t sessionId); uint32_t PcmFormatToBytes(AudioSampleFormat format); std::string GetSourcePortName(DeviceType deviceType); void UpdateDisplayName(std::shared_ptr deviceDescriptor); diff --git a/services/audio_policy/server/include/service/service/audio_server_proxy.h b/services/audio_policy/server/include/service/service/audio_server_proxy.h index 4437c3c5e7d2d1b8bab69a122e454926748d04b1..eec23ae7c54143acebe692d8ac0dcf56ef23de60 100644 --- a/services/audio_policy/server/include/service/service/audio_server_proxy.h +++ b/services/audio_policy/server/include/service/service/audio_server_proxy.h @@ -28,6 +28,7 @@ #include "audio_manager_base.h" #include "audio_module_info.h" #include "audio_ec_info.h" +#include "hdi_adapter_type.h" #include "datashare_helper.h" #include "audio_errors.h" @@ -83,6 +84,7 @@ public: bool CreateEffectChainManagerProxy(std::vector &effectChains, const EffectChainManagerParam &effectParam, const EffectChainManagerParam &enhanceParam); int32_t RegiestPolicyProviderProxy(const sptr &object); + int32_t RegistCoreServiceProviderProxy(const sptr &object); void SetParameterCallbackProxy(const sptr& object); int32_t SetAudioEffectPropertyProxy(const AudioEffectPropertyArrayV3 &propertyArray, const DeviceType& deviceType = DEVICE_TYPE_NONE); @@ -101,6 +103,11 @@ public: #endif int32_t LoadHdiAdapterProxy(uint32_t devMgrType, const std::string &adapterName); void UnloadHdiAdapterProxy(uint32_t devMgrType, const std::string &adapterName, bool force); + uint32_t CreateHdiSinkPortProxy(const std::string &deviceClass, const std::string &idInfo, + const IAudioSinkAttr &attr); + uint32_t CreateHdiSourcePortProxy(const std::string &deviceClass, const std::string &idInfo, + const IAudioSourceAttr &attr); + void DestroyHdiPortProxy(uint32_t id); void SetDeviceConnectedFlag(bool flag); private: AudioServerProxy() {} diff --git a/services/audio_policy/server/src/audio_policy_manager_stub.cpp b/services/audio_policy/server/src/audio_policy_manager_stub.cpp index deaa84dd9725bce4fcdd695b698dcb9374d49e3e..f745968fe997d629f82b6bed4205af9e1ce11a84 100644 --- a/services/audio_policy/server/src/audio_policy_manager_stub.cpp +++ b/services/audio_policy/server/src/audio_policy_manager_stub.cpp @@ -79,6 +79,8 @@ const char *g_audioPolicyCodeStrs[] = { "GET_SINK_LATENCY", "GET_PREFERRED_OUTPUT_STREAM_TYPE", "GET_PREFERRED_INPUT_STREAM_TYPE", + "CREATE_RENDERER_CLIENT", + "CREATE_CAPTURER_CLIENT", "REGISTER_TRACKER", "UPDATE_TRACKER", "GET_RENDERER_CHANGE_INFOS", @@ -646,6 +648,30 @@ void AudioPolicyManagerStub::GetPreferredInputStreamTypeInternal(MessageParcel & reply.WriteInt32(result); } +void AudioPolicyManagerStub::CreateRendererClientInternal(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr streamDesc = std::make_shared(); + streamDesc->Unmarshalling(data); + uint32_t flag = AUDIO_OUTPUT_FLAG_NORMAL; + uint32_t sessionId = 0; + int32_t ret = CreateRendererClient(streamDesc, flag, sessionId); + reply.WriteUint32(flag); + reply.WriteUint32(sessionId); + reply.WriteInt32(ret); +} + +void AudioPolicyManagerStub::CreateCapturerClientInternal(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr streamDesc = std::make_shared(); + streamDesc->Unmarshalling(data); + uint32_t flag = AUDIO_INPUT_FLAG_NORMAL; + uint32_t sessionId = 0; + int32_t ret = CreateCapturerClient(streamDesc, flag, sessionId); + reply.WriteUint32(flag); + reply.WriteUint32(sessionId); + reply.WriteInt32(ret); +} + void AudioPolicyManagerStub::ReconfigureAudioChannelInternal(MessageParcel &data, MessageParcel &reply) { uint32_t count = data.ReadUint32(); @@ -1573,6 +1599,12 @@ void AudioPolicyManagerStub::OnMiddleSecRemoteRequest( case static_cast(AudioPolicyInterfaceCode::GET_PREFERRED_INPUT_STREAM_TYPE): GetPreferredInputStreamTypeInternal(data, reply); break; + case static_cast(AudioPolicyInterfaceCode::CREATE_RENDERER_CLIENT): + CreateRendererClientInternal(data, reply); + break; + case static_cast(AudioPolicyInterfaceCode::CREATE_CAPTURER_CLIENT): + CreateCapturerClientInternal(data, reply); + break; case static_cast(AudioPolicyInterfaceCode::REGISTER_TRACKER): RegisterTrackerInternal(data, reply); break; diff --git a/services/audio_policy/server/src/audio_policy_server.cpp b/services/audio_policy/server/src/audio_policy_server.cpp index 0da345074a4661b916645b79b054e8df1cbb2b5a..640f078095f59e3fa972a8774067c70c33ac6787 100644 --- a/services/audio_policy/server/src/audio_policy_server.cpp +++ b/services/audio_policy/server/src/audio_policy_server.cpp @@ -182,6 +182,11 @@ void AudioPolicyServer::OnStart() } audioPolicyService_.Init(); + coreService_ = AudioCoreService::GetCoreService(); + coreService_->SetCallbackHandler(audioPolicyServerHandler_); + coreService_->Init(); + eventEntry_ = coreService_->GetEventEntry(); + AddSystemAbilityListeners(); bool res = Publish(this); if (!res) { @@ -240,6 +245,7 @@ void AudioPolicyServer::AddSystemAbilityListeners() void AudioPolicyServer::OnStop() { audioPolicyService_.Deinit(); + coreService_->DeInit(); #ifdef USB_ENABLE AudioUsbManager::GetInstance().Deinit(); #endif @@ -286,7 +292,7 @@ void AudioPolicyServer::OnAddSystemAbility(int32_t systemAbilityId, const std::s break; #ifdef USB_ENABLE case USB_SYSTEM_ABILITY_ID: - AudioUsbManager::GetInstance().Init(&audioPolicyService_); + AudioUsbManager::GetInstance().Init(eventEntry_.get()); // shared_ptr -> * break; #endif default: @@ -571,9 +577,9 @@ void AudioPolicyServer::AddAudioServiceOnStart() { AUDIO_INFO_LOG("OnAddSystemAbility audio service start"); if (!isFirstAudioServiceStart_) { + RegisterParamCallback(); ConnectServiceAdapter(); sessionProcessor_.Start(); - RegisterParamCallback(); LoadEffectLibrary(); isFirstAudioServiceStart_ = true; } else { @@ -679,7 +685,7 @@ void AudioPolicyServer::OnReceiveEvent(const EventFwk::CommonEventData &eventDat } else if (action == "usual.event.bluetooth.remotedevice.NAME_UPDATE") { std::string deviceName = want.GetStringParam("remoteName"); std::string macAddress = want.GetStringParam("deviceAddr"); - audioPolicyService_.OnReceiveBluetoothEvent(macAddress, deviceName); + eventEntry_->OnReceiveBluetoothEvent(macAddress, deviceName); } else if (action == "usual.event.SCREEN_ON") { AUDIO_INFO_LOG("receive SCREEN_ON action, control audio focus if need"); audioPolicyService_.SetFirstScreenOn(); @@ -744,7 +750,7 @@ void AudioPolicyServer::InitKVStore() void AudioPolicyServer::ConnectServiceAdapter() { - if (!audioPolicyService_.ConnectServiceAdapter()) { + if (!eventEntry_->ConnectServiceAdapter()) { AUDIO_ERR_LOG("ConnectServiceAdapter Error in connecting to audio service adapter"); return; } @@ -1274,7 +1280,7 @@ void AudioPolicyServer::UpdateMuteStateAccordingToVolLevel(AudioStreamType strea muteStatus = false; audioPolicyService_.SetStreamMute(streamType, false); } - + if (VolumeUtils::IsPCVolumeEnable()) { // system mute status should be aligned with music mute status. if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC && @@ -1309,7 +1315,7 @@ int32_t AudioPolicyServer::SetAppSingleStreamVolume(int32_t appUid, int32_t volu { int32_t ret = audioPolicyService_.SetAppVolumeLevel(appUid, volumeLevel); CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Fail to set App Volume level"); - + VolumeEvent volumeEvent; volumeEvent.volumeType = STREAM_APP; volumeEvent.volume = volumeLevel; @@ -1395,10 +1401,13 @@ bool AudioPolicyServer::GetStreamMuteInternal(AudioStreamType streamType) bool AudioPolicyServer::IsArmUsbDevice(const AudioDeviceDescriptor &desc) { - if (desc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) return true; - if (desc.deviceType_ != DEVICE_TYPE_USB_HEADSET) return false; - - return audioPolicyService_.IsArmUsbDevice(desc); + if (desc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) { + return true; + } + if (desc.deviceType_ != DEVICE_TYPE_USB_HEADSET) { + return false; + } + return eventEntry_->IsArmUsbDevice(desc); } void AudioPolicyServer::MapExternalToInternalDeviceType(AudioDeviceDescriptor &desc) @@ -1418,8 +1427,7 @@ int32_t AudioPolicyServer::SelectOutputDevice(sptr audioRen { CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_PERMISSION_DENIED, "SelectOutputDevice: No system permission"); - - return audioPolicyService_.SelectOutputDevice(audioRendererFilter, audioDeviceDescriptors); + return eventEntry_->SelectOutputDevice(audioRendererFilter, audioDeviceDescriptors); } std::string AudioPolicyServer::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType) @@ -1432,7 +1440,7 @@ int32_t AudioPolicyServer::SelectInputDevice(sptr audioCapt { CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_PERMISSION_DENIED, "SelectInputDevice: No system permission"); - int32_t ret = audioPolicyService_.SelectInputDevice(audioCapturerFilter, audioDeviceDescriptors); + int32_t ret = eventEntry_->SelectInputDevice(audioCapturerFilter, audioDeviceDescriptors); return ret; } @@ -1441,8 +1449,7 @@ int32_t AudioPolicyServer::ExcludeOutputDevices(AudioDeviceUsage audioDevUsage, { CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_PERMISSION_DENIED, "No system permission"); - - return audioPolicyService_.ExcludeOutputDevices(audioDevUsage, audioDeviceDescriptors); + return eventEntry_->ExcludeOutputDevices(audioDevUsage, audioDeviceDescriptors); } int32_t AudioPolicyServer::UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage, @@ -1481,8 +1488,7 @@ std::vector> AudioPolicyServer::GetDevice break; } - std::vector> deviceDescs = audioPolicyService_.GetDevices(deviceFlag); - + std::vector> deviceDescs = eventEntry_->GetDevices(deviceFlag); if (!hasSystemPermission) { for (std::shared_ptr desc : deviceDescs) { desc->networkId_ = ""; @@ -1567,7 +1573,7 @@ std::vector> AudioPolicyServer::GetPrefer AudioCapturerInfo &captureInfo) { std::vector> deviceDescs = - audioPolicyService_.GetPreferredInputDeviceDescriptors(captureInfo); + eventEntry_->GetPreferredInputDeviceDescriptors(captureInfo); bool hasBTPermission = VerifyBluetoothPermission(); if (!hasBTPermission) { audioPolicyService_.UpdateDescWhenNoBTPermission(deviceDescs); @@ -1604,7 +1610,7 @@ bool AudioPolicyServer::IsStreamActive(AudioStreamType streamType) int32_t AudioPolicyServer::SetDeviceActive(InternalDeviceType deviceType, bool active, const int32_t pid) { - return audioPolicyService_.SetDeviceActive(deviceType, active, pid); + return eventEntry_->SetDeviceActive(deviceType, active, pid); } bool AudioPolicyServer::IsDeviceActive(InternalDeviceType deviceType) @@ -1669,7 +1675,7 @@ int32_t AudioPolicyServer::SetRingerModeInternal(AudioRingerMode inputRingerMode // PC ringmode not support silent or vibrate AudioRingerMode ringerMode = VolumeUtils::IsPCVolumeEnable() ? RINGER_MODE_NORMAL : inputRingerMode; AUDIO_INFO_LOG("Set ringer mode to %{public}d. hasUpdatedVolume %{public}d", ringerMode, hasUpdatedVolume); - int32_t ret = audioPolicyService_.SetRingerMode(ringerMode); + int32_t ret = coreService_->SetRingerMode(ringerMode); CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Fail to set ringer mode!"); if (!hasUpdatedVolume) { @@ -1833,7 +1839,7 @@ int32_t AudioPolicyServer::SetAudioScene(AudioScene audioScene) case AUDIO_SCENE_RINGING: case AUDIO_SCENE_PHONE_CALL: case AUDIO_SCENE_PHONE_CHAT: - return audioPolicyService_.SetAudioScene(audioScene); + return eventEntry_->SetAudioScene(audioScene); default: AUDIO_ERR_LOG("param is invalid: %{public}d", audioScene); @@ -1843,7 +1849,7 @@ int32_t AudioPolicyServer::SetAudioScene(AudioScene audioScene) int32_t AudioPolicyServer::SetAudioSceneInternal(AudioScene audioScene) { - return audioPolicyService_.SetAudioScene(audioScene); + return eventEntry_->SetAudioScene(audioScene); } AudioScene AudioPolicyServer::GetAudioScene() @@ -2100,6 +2106,7 @@ void AudioPolicyServer::InitPolicyDumpMap() dumpFuncMap[u"-e"] = &AudioPolicyServer::EffectManagerInfoDump; dumpFuncMap[u"-ms"] = &AudioPolicyServer::MicrophoneMuteInfoDump; dumpFuncMap[u"-as"] = &AudioPolicyServer::AudioSessionInfoDump; + dumpFuncMap[u"-ap"] = &AudioPolicyServer::AudioPipeManagerDump; } void AudioPolicyServer::PolicyDataDump(std::string &dumpString) @@ -2114,6 +2121,7 @@ void AudioPolicyServer::PolicyDataDump(std::string &dumpString) EffectManagerInfoDump(dumpString); MicrophoneMuteInfoDump(dumpString); AudioSessionInfoDump(dumpString); + AudioPipeManagerDump(dumpString); } void AudioPolicyServer::AudioDevicesDump(std::string &dumpString) @@ -2166,6 +2174,12 @@ void AudioPolicyServer::AudioSessionInfoDump(std::string &dumpString) interruptService_->AudioSessionInfoDump(dumpString); } +void AudioPolicyServer::AudioPipeManagerDump(std::string &dumpString) +{ + dumpString += "\nAudioPipeManager Info\n"; + AudioPipeManager::GetPipeManager()->Dump(dumpString); +} + void AudioPolicyServer::ArgInfoDump(std::string &dumpString, std::queue &argQue) { dumpString += "AudioPolicyServer Data Dump:\n\n"; @@ -2213,14 +2227,26 @@ int32_t AudioPolicyServer::GetPreferredOutputStreamType(AudioRendererInfo &rende if (isFastControlled && rendererInfo.rendererFlags == AUDIO_FLAG_MMAP) { bundleName = GetBundleName(); AUDIO_INFO_LOG("bundleName %{public}s", bundleName.c_str()); - return audioPolicyService_.GetPreferredOutputStreamType(rendererInfo, bundleName); + return eventEntry_->GetPreferredOutputStreamType(rendererInfo, bundleName); } - return audioPolicyService_.GetPreferredOutputStreamType(rendererInfo, ""); + return eventEntry_->GetPreferredOutputStreamType(rendererInfo, ""); } int32_t AudioPolicyServer::GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo) { - return audioPolicyService_.GetPreferredInputStreamType(capturerInfo); + return eventEntry_->GetPreferredInputStreamType(capturerInfo); +} + +int32_t AudioPolicyServer::CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) +{ + return eventEntry_->CreateRendererClient(streamDesc, flag, sessionId); +} + +int32_t AudioPolicyServer::CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) +{ + return eventEntry_->CreateCapturerClient(streamDesc, flag, sessionId); } int32_t AudioPolicyServer::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, @@ -2252,7 +2278,7 @@ int32_t AudioPolicyServer::RegisterTracker(AudioMode &mode, AudioStreamChangeInf } RegisterClientDeathRecipient(object, TRACKER_CLIENT); int32_t apiVersion = GetApiTargerVersion(); - return audioPolicyService_.RegisterTracker(mode, streamChangeInfo, object, apiVersion); + return eventEntry_->RegisterTracker(mode, streamChangeInfo, object, apiVersion); } int32_t AudioPolicyServer::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo) @@ -2279,7 +2305,7 @@ int32_t AudioPolicyServer::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo } int appVolume = GetAppVolumeLevel(streamChangeInfo.audioRendererChangeInfo.clientUID); streamChangeInfo.audioRendererChangeInfo.appVolume = appVolume; - int32_t ret = audioPolicyService_.UpdateTracker(mode, streamChangeInfo); + int32_t ret = eventEntry_->UpdateTracker(mode, streamChangeInfo); if (streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_PAUSED || streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_STOPPED || streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_RELEASED) { @@ -2306,7 +2332,7 @@ void AudioPolicyServer::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamC AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]", streamChangeInfo.audioRendererChangeInfo.clientUID); } - audioPolicyService_.FetchOutputDeviceForTrack(streamChangeInfo, reason); + eventEntry_->FetchOutputDeviceForTrack(streamChangeInfo, reason); } void AudioPolicyServer::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo) @@ -2323,7 +2349,7 @@ void AudioPolicyServer::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamCh AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]", streamChangeInfo.audioCapturerChangeInfo.clientUID); } - audioPolicyService_.FetchInputDeviceForTrack(streamChangeInfo); + eventEntry_->FetchInputDeviceForTrack(streamChangeInfo); } int32_t AudioPolicyServer::GetCurrentRendererChangeInfos( @@ -2334,7 +2360,7 @@ int32_t AudioPolicyServer::GetCurrentRendererChangeInfos( bool hasSystemPermission = PermissionUtil::VerifySystemPermission(); AUDIO_DEBUG_LOG("GetCurrentRendererChangeInfos: System use permission: %{public}d", hasSystemPermission); - return audioPolicyService_.GetCurrentRendererChangeInfos(audioRendererChangeInfos, + return eventEntry_->GetCurrentRendererChangeInfos(audioRendererChangeInfos, hasBTPermission, hasSystemPermission); } @@ -2346,7 +2372,7 @@ int32_t AudioPolicyServer::GetCurrentCapturerChangeInfos( bool hasSystemPermission = PermissionUtil::VerifySystemPermission(); AUDIO_DEBUG_LOG("GetCurrentCapturerChangeInfos: System use permission: %{public}d", hasSystemPermission); - return audioPolicyService_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos, + return eventEntry_->GetCurrentCapturerChangeInfos(audioCapturerChangeInfos, hasBTPermission, hasSystemPermission); } @@ -2388,7 +2414,7 @@ void AudioPolicyServer::RegisteredTrackerClientDied(pid_t pid, pid_t uid) AUDIO_INFO_LOG("RegisteredTrackerClient died: remove entry, pid %{public}d uid %{public}d", pid, uid); audioPolicyService_.RemoveDeviceForUid(uid); std::lock_guard lock(clientDiedListenerStateMutex_); - audioPolicyService_.RegisteredTrackerClientDied(uid); + eventEntry_->RegisteredTrackerClientDied(uid); auto filter = [&uid](int val) { return uid == val; @@ -2462,7 +2488,7 @@ int32_t AudioPolicyServer::GetVolumeGroupInfos(std::string networkId, std::vecto CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED, "No system permission"); - infos = audioPolicyService_.GetVolumeGroupInfos(); + infos = eventEntry_->GetVolumeGroupInfos(); auto filter = [&networkId](const sptr& info) { return networkId != info->networkId_; }; @@ -2473,7 +2499,7 @@ int32_t AudioPolicyServer::GetVolumeGroupInfos(std::string networkId, std::vecto int32_t AudioPolicyServer::GetNetworkIdByGroupId(int32_t groupId, std::string &networkId) { - auto volumeGroupInfos = audioPolicyService_.GetVolumeGroupInfos(); + auto volumeGroupInfos = eventEntry_->GetVolumeGroupInfos(); auto filter = [&groupId](const sptr& info) { return groupId != info->volumeGroupId_; @@ -2592,7 +2618,7 @@ void AudioPolicyServer::RemoteParameterCallback::StateOnChange(const std::string "StateOnChange: Not find daudio device type value, contentDes %{public}s.", contentDesStr.c_str()); if (contentDesStr[devTypeValPos] == DAUDIO_DEV_TYPE_SPK) { - server_->audioPolicyService_.NotifyRemoteRenderState(networkId, contentDesStr, value); + server_->coreService_->NotifyRemoteRenderState(networkId, contentDesStr, value); } else if (contentDesStr[devTypeValPos] == DAUDIO_DEV_TYPE_MIC) { AUDIO_INFO_LOG("StateOnChange: ERR_EVENT of DAUDIO_DEV_TYPE_MIC."); } else { @@ -2678,12 +2704,13 @@ void AudioPolicyServer::RegisterParamCallback() audioPolicyService_.SetParameterCallback(remoteParameterCallback_); // regiest policy provider in audio server audioPolicyService_.RegiestPolicy(); + eventEntry_->RegistCoreService(); } void AudioPolicyServer::RegisterBluetoothListener() { AUDIO_INFO_LOG("OnAddSystemAbility bluetooth service start"); - audioPolicyService_.RegisterBluetoothListener(); + coreService_->RegisterBluetoothListener(); } void AudioPolicyServer::SubscribeAccessibilityConfigObserver() @@ -2757,13 +2784,13 @@ int32_t AudioPolicyServer::GetHardwareOutputSamplingRate(const std::shared_ptr> AudioPolicyServer::GetAudioCapturerMicrophoneDescriptors(int32_t sessionId) { std::vector> micDescs = - audioPolicyService_.GetAudioCapturerMicrophoneDescriptors(sessionId); + coreService_->GetAudioCapturerMicrophoneDescriptors(sessionId); return micDescs; } vector> AudioPolicyServer::GetAvailableMicrophones() { - std::vector> micDescs = audioPolicyService_.GetAvailableMicrophones(); + std::vector> micDescs = eventEntry_->GetAvailableMicrophones(); return micDescs; } @@ -2830,7 +2857,7 @@ std::vector> AudioPolicyServer::GetAvaila return deviceDescs; } - deviceDescs = audioPolicyService_.GetAvailableDevices(usage); + deviceDescs = eventEntry_->GetAvailableDevices(usage); if (!hasSystemPermission) { for (auto &desc : deviceDescs) { @@ -2900,7 +2927,7 @@ int32_t AudioPolicyServer::ConfigDistributedRoutingRole( return ERR_PERMISSION_DENIED; } std::lock_guard lock(descLock_); - audioPolicyService_.ConfigDistributedRoutingRole(descriptor, type); + coreService_->ConfigDistributedRoutingRole(descriptor, type); OnDistributedRoutingRoleChange(descriptor, type); return SUCCESS; } @@ -3267,7 +3294,7 @@ std::shared_ptr AudioPolicyServer::GetActiveBluetoothDevi return make_shared(); } - auto btdevice = audioPolicyService_.GetActiveBluetoothDevice(); + auto btdevice = eventEntry_->GetActiveBluetoothDevice(); bool hasBTPermission = VerifyBluetoothPermission(); if (!hasBTPermission) { @@ -3423,7 +3450,7 @@ int32_t AudioPolicyServer::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt r if (callerUid != UID_AUDIO) { return ERROR; } - return audioPolicyService_.TriggerFetchDevice(reason); + return coreService_->TriggerFetchDevice(reason); } int32_t AudioPolicyServer::SetPreferredDevice(const PreferredType preferredType, @@ -3448,8 +3475,7 @@ void AudioPolicyServer::SaveRemoteInfo(const std::string &networkId, DeviceType std::shared_ptr newMediaDescriptor = audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_MEDIA, -1, ROUTER_TYPE_USER_SELECT).front(); std::shared_ptr newCallDescriptor = - audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_VOICE_COMMUNICATION, -1, - ROUTER_TYPE_USER_SELECT).front(); + audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_VOICE_COMMUNICATION, -1, ROUTER_TYPE_USER_SELECT).front(); if (networkId == newMediaDescriptor->networkId_ && deviceType == newMediaDescriptor->deviceType_) { AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_MEDIA_RENDER, std::make_shared()); @@ -3468,7 +3494,7 @@ int32_t AudioPolicyServer::SetAudioDeviceAnahsCallback(const sptr if (callerUid != UID_AUDIO) { return ERROR; } - return audioPolicyService_.SetAudioDeviceAnahsCallback(object); + return coreService_->SetAudioDeviceAnahsCallback(object); } int32_t AudioPolicyServer::UnsetAudioDeviceAnahsCallback() @@ -3477,7 +3503,7 @@ int32_t AudioPolicyServer::UnsetAudioDeviceAnahsCallback() if (callerUid != UID_AUDIO) { return ERROR; } - return audioPolicyService_.UnsetAudioDeviceAnahsCallback(); + return coreService_->UnsetAudioDeviceAnahsCallback(); } void AudioPolicyServer::NotifyAccountsChanged(const int &id) diff --git a/services/audio_policy/server/src/audio_policy_server_handler.cpp b/services/audio_policy/server/src/audio_policy_server_handler.cpp index bbdbe63e03563dff1fbbe002dfba7d83d8bcc40c..3f992aa405e0cd76789181d2896de203848f1a8a 100644 --- a/services/audio_policy/server/src/audio_policy_server_handler.cpp +++ b/services/audio_policy/server/src/audio_policy_server_handler.cpp @@ -18,6 +18,7 @@ #include "audio_policy_server_handler.h" #include "audio_policy_service.h" +#include "audio_core_service.h" namespace OHOS { namespace AudioStandard { @@ -477,29 +478,27 @@ bool AudioPolicyServerHandler::SendWakeupCloseEvent(bool isSync) } bool AudioPolicyServerHandler::SendRecreateRendererStreamEvent( - int32_t clientId, uint32_t sessionID, int32_t streamFlag, - const AudioStreamDeviceChangeReasonExt reason) + int32_t clientId, uint32_t sessionID, uint32_t routeFlag, const AudioStreamDeviceChangeReasonExt reason) { std::shared_ptr eventContextObj = std::make_shared(); CHECK_AND_RETURN_RET_LOG(eventContextObj != nullptr, false, "EventContextObj get nullptr"); eventContextObj->clientId = clientId; eventContextObj->sessionId = sessionID; - eventContextObj->streamFlag = streamFlag; eventContextObj->reason_ = reason; + eventContextObj->routeFlag = routeFlag; return SendEvent(AppExecFwk::InnerEvent::Get(EventAudioServerCmd::RECREATE_RENDERER_STREAM_EVENT, eventContextObj)); } bool AudioPolicyServerHandler::SendRecreateCapturerStreamEvent( - int32_t clientId, uint32_t sessionID, int32_t streamFlag, - const AudioStreamDeviceChangeReasonExt reason) + int32_t clientId, uint32_t sessionID, uint32_t routeFlag, const AudioStreamDeviceChangeReasonExt reason) { std::shared_ptr eventContextObj = std::make_shared(); CHECK_AND_RETURN_RET_LOG(eventContextObj != nullptr, false, "EventContextObj get nullptr"); eventContextObj->clientId = clientId; eventContextObj->sessionId = sessionID; - eventContextObj->streamFlag = streamFlag; eventContextObj->reason_ = reason; + eventContextObj->routeFlag = routeFlag; return SendEvent(AppExecFwk::InnerEvent::Get(EventAudioServerCmd::RECREATE_CAPTURER_STREAM_EVENT, eventContextObj)); } @@ -1054,7 +1053,7 @@ void AudioPolicyServerHandler::HandleCapturerCreateEvent(const AppExecFwk::Inner SessionInfo sessionInfo{eventContextObj->capturerInfo_.sourceType, eventContextObj->streamInfo_.samplingRate, eventContextObj->streamInfo_.channels}; - eventContextObj->error_ = AudioPolicyService::GetAudioPolicyService().OnCapturerSessionAdded(sessionId, + eventContextObj->error_ = AudioCoreService::GetCoreService()->GetEventEntry()->OnCapturerSessionAdded(sessionId, sessionInfo, eventContextObj->streamInfo_); } @@ -1065,7 +1064,7 @@ void AudioPolicyServerHandler::HandleCapturerRemovedEvent(const AppExecFwk::Inne uint64_t sessionId = *eventContextObj; - AudioPolicyService::GetAudioPolicyService().OnCapturerSessionRemoved(sessionId); + AudioCoreService::GetCoreService()->GetEventEntry()->OnCapturerSessionRemoved(sessionId); } void AudioPolicyServerHandler::HandleWakeupCloseEvent(const AppExecFwk::InnerEvent::Pointer &event) @@ -1080,8 +1079,8 @@ void AudioPolicyServerHandler::HandleSendRecreateRendererStreamEvent(const AppEx std::lock_guard lock(handleMapMutex_); RestoreInfo restoreInfo; restoreInfo.restoreReason = DEVICE_CHANGED; - restoreInfo.targetStreamFlag = eventContextObj->streamFlag; restoreInfo.deviceChangeReason = static_cast(eventContextObj->reason_); + restoreInfo.routeFlag = static_cast(eventContextObj->routeFlag); AudioPolicyService::GetAudioPolicyService().RestoreSession(eventContextObj->sessionId, restoreInfo); } @@ -1092,8 +1091,8 @@ void AudioPolicyServerHandler::HandleSendRecreateCapturerStreamEvent(const AppEx std::lock_guard lock(handleMapMutex_); RestoreInfo restoreInfo; restoreInfo.restoreReason = DEVICE_CHANGED; - restoreInfo.targetStreamFlag = eventContextObj->streamFlag; restoreInfo.deviceChangeReason = static_cast(eventContextObj->reason_); + restoreInfo.routeFlag = static_cast(eventContextObj->routeFlag); AudioPolicyService::GetAudioPolicyService().RestoreSession(eventContextObj->sessionId, restoreInfo); } @@ -1272,6 +1271,7 @@ void AudioPolicyServerHandler::HandleConcurrencyEventWithSessionID(const AppExec RestoreInfo restoreInfo; restoreInfo.restoreReason = STREAM_CONCEDED; restoreInfo.targetStreamFlag = AUDIO_FLAG_FORCED_NORMAL; + restoreInfo.routeFlag = AUDIO_FLAG_NONE; AudioPolicyService::GetAudioPolicyService().RestoreSession(eventContextObj->sessionId, restoreInfo); } diff --git a/services/audio_policy/server/src/audio_stream_collector.cpp b/services/audio_policy/server/src/audio_stream_collector.cpp index a24159261fb00f0587f55e378ebe8b29757acc9b..4542e964d810cdfecbc0148f5e3bb5b91a3708ca 100644 --- a/services/audio_policy/server/src/audio_stream_collector.cpp +++ b/services/audio_policy/server/src/audio_stream_collector.cpp @@ -581,6 +581,29 @@ int32_t AudioStreamCollector::UpdateRendererDeviceInfo(AudioDeviceDescriptor &ou return SUCCESS; } +int32_t AudioStreamCollector::UpdateRendererDeviceInfo(std::shared_ptr outputDeviceInfo) +{ + bool deviceInfoUpdated = false; + + for (auto it = audioRendererChangeInfos_.begin(); it != audioRendererChangeInfos_.end(); it++) { + if (!(*it)->outputDeviceInfo.IsSameDeviceDescPtr(outputDeviceInfo)) { + AUDIO_DEBUG_LOG("UpdateRendererDeviceInfo: old device: %{public}d new device: %{public}d", + (*it)->outputDeviceInfo.deviceType_, outputDeviceInfo->deviceType_); + (*it)->outputDeviceInfo = outputDeviceInfo; + deviceInfoUpdated = true; + } + } + + if (deviceInfoUpdated && audioPolicyServerHandler_ != nullptr) { + audioPolicyServerHandler_->SendRendererInfoEvent(audioRendererChangeInfos_); + } + if (deviceInfoUpdated) { + AudioSpatializationService::GetAudioSpatializationService().UpdateRendererInfo(audioRendererChangeInfos_); + } + + return SUCCESS; +} + int32_t AudioStreamCollector::UpdateCapturerDeviceInfo(AudioDeviceDescriptor &inputDeviceInfo) { bool deviceInfoUpdated = false; @@ -601,6 +624,26 @@ int32_t AudioStreamCollector::UpdateCapturerDeviceInfo(AudioDeviceDescriptor &in return SUCCESS; } +int32_t AudioStreamCollector::UpdateCapturerDeviceInfo(std::shared_ptr inputDeviceInfo) +{ + bool deviceInfoUpdated = false; + + for (auto it = audioCapturerChangeInfos_.begin(); it != audioCapturerChangeInfos_.end(); it++) { + if (!(*it)->inputDeviceInfo.IsSameDeviceDescPtr(inputDeviceInfo)) { + AUDIO_DEBUG_LOG("UpdateCapturerDeviceInfo: old device: %{public}d new device: %{public}d", + (*it)->inputDeviceInfo.deviceType_, inputDeviceInfo->deviceType_); + (*it)->inputDeviceInfo = inputDeviceInfo; + deviceInfoUpdated = true; + } + } + + if (deviceInfoUpdated && audioPolicyServerHandler_ != nullptr) { + SendCapturerInfoEvent(audioCapturerChangeInfos_); + } + + return SUCCESS; +} + int32_t AudioStreamCollector::UpdateRendererDeviceInfo(int32_t clientUID, int32_t sessionId, AudioDeviceDescriptor &outputDeviceInfo) { @@ -1208,6 +1251,11 @@ int32_t AudioStreamCollector::ActivateAudioConcurrency(const AudioPipeType &pipe audioRendererChangeInfos_, audioCapturerChangeInfos_); } +std::map, ConcurrencyAction>& AudioStreamCollector::GetConcurrencyMap() +{ + return audioConcurrencyService_->GetConcurrencyMap(); +} + void AudioStreamCollector::WriterStreamChangeSysEvent(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo) { if (mode == AUDIO_MODE_PLAYBACK) { diff --git a/services/audio_policy/server/src/service/audio_policy_service.cpp b/services/audio_policy/server/src/service/audio_policy_service.cpp index d5d73f0ab6c789b29a1ff686f646ee80af985b57..817a41f5cbe9ed5dab024727e84b2d02521da626 100644 --- a/services/audio_policy/server/src/service/audio_policy_service.cpp +++ b/services/audio_policy/server/src/service/audio_policy_service.cpp @@ -81,14 +81,7 @@ static int16_t IsDistributedOutput(const AudioDeviceDescriptor &desc) { return (desc.deviceType_ == DEVICE_TYPE_SPEAKER && desc.networkId_ != LOCAL_NETWORK_ID) ? 1 : 0; } - -#ifdef BLUETOOTH_ENABLE -static sptr g_btProxy = nullptr; -#endif mutex g_dataShareHelperMutex; -#ifdef BLUETOOTH_ENABLE -mutex g_btProxyMutex; -#endif bool AudioPolicyService::isBtListenerRegistered = false; bool AudioPolicyService::isBtCrashed = false; mutex g_policyMgrListenerMutex; @@ -119,7 +112,6 @@ bool AudioPolicyService::LoadAudioPolicyConfig() bool AudioPolicyService::Init(void) { - serviceFlag_.reset(); audioPolicyManager_.Init(); audioEffectService_.EffectServiceInit(); audioDeviceManager_.ParseDeviceXml(); @@ -128,8 +120,6 @@ bool AudioPolicyService::Init(void) audioPnpServer_.init(); #endif audioGlobalConfigManager_.ParseGlobalConfigXml(); - audioA2dpOffloadManager_ = std::make_shared(); - if (audioA2dpOffloadManager_ != nullptr) {audioA2dpOffloadManager_->Init();} bool ret = LoadAudioPolicyConfig(); if (!ret) { @@ -141,21 +131,6 @@ bool AudioPolicyService::Init(void) CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Tone Load Configuration failed"); #endif - int32_t status = deviceStatusListener_->RegisterDeviceStatusListener(); - if (status != SUCCESS) { - AudioPolicyUtils::GetInstance().WriteServiceStartupError("[Policy Service] Register for device status " - "events failed"); - } - CHECK_AND_RETURN_RET_LOG(status == SUCCESS, false, "[Policy Service] Register for device status events failed"); - - audioVolumeManager_.Init(audioPolicyServerHandler_); - audioDeviceCommon_.Init(audioPolicyServerHandler_); - audioRecoveryDevice_.Init(audioA2dpOffloadManager_); - - audioDeviceStatus_.Init(audioA2dpOffloadManager_, audioPolicyServerHandler_); - audioDeviceLock_.Init(audioA2dpOffloadManager_); - audioCapturerSession_.Init(audioA2dpOffloadManager_); - CreateRecoveryThread(); std::string versionType = OHOS::system::GetParameter("const.logsystem.versiontype", "commercial"); AudioDump::GetInstance().SetVersionType(versionType); @@ -918,28 +893,7 @@ void AudioPolicyService::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isSt void AudioPolicyService::OnServiceConnected(AudioServiceIndex serviceIndex) { - AUDIO_INFO_LOG("[module_load]::OnServiceConnected for [%{public}d]", serviceIndex); - CHECK_AND_RETURN_LOG(serviceIndex >= HDI_SERVICE_INDEX && serviceIndex <= AUDIO_SERVICE_INDEX, "invalid index"); - - // If audio service or hdi service is not ready, donot load default modules - lock_guard lock(serviceFlagMutex_); - serviceFlag_.set(serviceIndex, true); - if (serviceFlag_.count() != MIN_SERVICE_COUNT) { - AUDIO_INFO_LOG("[module_load]::hdi service or audio service not up. Cannot load default module now"); - return; - } - - int32_t ret = audioDeviceLock_.OnServiceConnected(serviceIndex); - if (ret == SUCCESS) { -#ifdef USB_ENABLE - AudioUsbManager::GetInstance().Init(this); -#endif - audioEffectService_.SetMasterSinkAvailable(); - } - // RegisterBluetoothListener() will be called when bluetooth_host is online - // load hdi-effect-model - LoadHdiEffectModel(); - AudioServerProxy::GetInstance().NotifyAudioPolicyReady(); + AUDIO_INFO_LOG("Not support, use AudioCoreService"); } void AudioPolicyService::OnServiceDisconnected(AudioServiceIndex serviceIndex) @@ -1300,10 +1254,6 @@ std::vector> AudioPolicyService::GetVolumeGroupInfos() void AudioPolicyService::RegiestPolicy() { AUDIO_INFO_LOG("Start"); - const sptr gsp = AudioServerProxy::GetInstance().GetAudioServerProxy(); - CHECK_AND_RETURN_LOG(gsp != nullptr, "RegiestPolicy, Audio Server Proxy is null"); - audioPolicyManager_.SetAudioServerProxy(gsp); - sptr wrapper = new(std::nothrow) PolicyProviderWrapper(this); CHECK_AND_RETURN_LOG(wrapper != nullptr, "Get null PolicyProviderWrapper"); sptr object = wrapper->AsObject(); @@ -1457,51 +1407,6 @@ int32_t AudioPolicyService::GetMaxRendererInstances() return audioConfigManager_.GetMaxRendererInstances(); } -#ifdef BLUETOOTH_ENABLE -const sptr RegisterBluetoothDeathCallback() -{ - lock_guard lock(g_btProxyMutex); - if (g_btProxy == nullptr) { - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - CHECK_AND_RETURN_RET_LOG(samgr != nullptr, nullptr, - "get sa manager failed"); - sptr object = samgr->GetSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID); - CHECK_AND_RETURN_RET_LOG(object != nullptr, nullptr, - "get audio service remote object failed"); - g_btProxy = iface_cast(object); - CHECK_AND_RETURN_RET_LOG(g_btProxy != nullptr, nullptr, - "get audio service proxy failed"); - - // register death recipent - sptr asDeathRecipient = - new(std::nothrow) AudioServerDeathRecipient(getpid(), getuid()); - if (asDeathRecipient != nullptr) { - asDeathRecipient->SetNotifyCb([] (pid_t pid, pid_t uid) { - AudioPolicyService::BluetoothServiceCrashedCallback(pid, uid); - }); - bool result = object->AddDeathRecipient(asDeathRecipient); - if (!result) { - AUDIO_ERR_LOG("failed to add deathRecipient"); - } - } - } - sptr gasp = g_btProxy; - return gasp; -} - -void AudioPolicyService::BluetoothServiceCrashedCallback(pid_t pid, pid_t uid) -{ - AUDIO_INFO_LOG("Bluetooth sa crashed, will restore proxy in next call"); - lock_guard lock(g_btProxyMutex); - g_btProxy = nullptr; - isBtListenerRegistered = false; - isBtCrashed = true; - Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSink(); - Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSource(); - Bluetooth::AudioHfpManager::DisconnectBluetoothHfpSink(); -} -#endif - void AudioPolicyService::RegisterBluetoothListener() { #ifdef BLUETOOTH_ENABLE @@ -1519,11 +1424,6 @@ void AudioPolicyService::RegisterBluetoothListener() isBtListenerRegistered = true; isBtCrashed = false; - const sptr gsp = RegisterBluetoothDeathCallback(); - AudioPolicyUtils::GetInstance().SetBtConnecting(true); - Bluetooth::AudioA2dpManager::CheckA2dpDeviceReconnect(); - Bluetooth::AudioHfpManager::CheckHfpDeviceReconnect(); - AudioPolicyUtils::GetInstance().SetBtConnecting(false); #endif } diff --git a/services/audio_policy/server/src/service/concurrency/audio_concurrency_service.cpp b/services/audio_policy/server/src/service/concurrency/audio_concurrency_service.cpp index 1833d74e0179ea1375cf337d6b705e3df211db8a..292e437948bb235c78d278b2c0fc9eff8de292c3 100644 --- a/services/audio_policy/server/src/service/concurrency/audio_concurrency_service.cpp +++ b/services/audio_policy/server/src/service/concurrency/audio_concurrency_service.cpp @@ -190,5 +190,10 @@ int32_t AudioConcurrencyService::ActivateAudioConcurrency(AudioPipeType incoming "Existing call in concede incoming call in"); return SUCCESS; } + +std::map, ConcurrencyAction>& AudioConcurrencyService::GetConcurrencyMap() +{ + return concurrencyCfgMap_; +} } // namespace AudioStandard } // namespace OHOS \ No newline at end of file diff --git a/services/audio_policy/server/src/service/concurrency/audio_concurrency_service.h b/services/audio_policy/server/src/service/concurrency/audio_concurrency_service.h index 899f75f8b5fff14cd8aab4627af849ba9a0930a7..91a06e738885015f832a90e5c18adf8a4fd2c6dd 100644 --- a/services/audio_policy/server/src/service/concurrency/audio_concurrency_service.h +++ b/services/audio_policy/server/src/service/concurrency/audio_concurrency_service.h @@ -46,6 +46,7 @@ public: int32_t ActivateAudioConcurrency(AudioPipeType incomingPipeType, const std::vector> &audioRendererChangeInfos, const std::vector> &audioCapturerChangeInfos); + std::map, ConcurrencyAction>& GetConcurrencyMap(); private: // Inner class for death handler class AudioConcurrencyDeathRecipient : public IRemoteObject::DeathRecipient { diff --git a/services/audio_policy/server/src/service/device/audio_device_descriptor.cpp b/services/audio_policy/server/src/service/device/audio_device_descriptor.cpp index a871a96a74338410d8a290d4b03c556505c9b241..a135979db72b9b707fe33f5b077acf1252aa821b 100644 --- a/services/audio_policy/server/src/service/device/audio_device_descriptor.cpp +++ b/services/audio_policy/server/src/service/device/audio_device_descriptor.cpp @@ -362,6 +362,14 @@ bool AudioDeviceDescriptor::IsSameDeviceDesc(const AudioDeviceDescriptor &device (!IsUsb(deviceType_) || deviceDescriptor.deviceRole_ == deviceRole_); } +bool AudioDeviceDescriptor::IsSameDeviceDescPtr(std::shared_ptr deviceDescriptor) const +{ + return deviceDescriptor->deviceType_ == deviceType_ && + deviceDescriptor->macAddress_ == macAddress_ && + deviceDescriptor->networkId_ == networkId_ && + (!IsUsb(deviceType_) || deviceDescriptor->deviceRole_ == deviceRole_); +} + bool AudioDeviceDescriptor::IsSameDeviceInfo(const AudioDeviceDescriptor &deviceInfo) const { return deviceType_ == deviceInfo.deviceType_ && @@ -379,6 +387,17 @@ bool AudioDeviceDescriptor::IsPairedDeviceDesc(const AudioDeviceDescriptor &devi deviceDescriptor.networkId_ == networkId_; } +void AudioDeviceDescriptor::Dump(std::string &dumpString) +{ + dumpString += "deviceName: " + deviceName_ + " deviceRole: "; + if (deviceRole_ != INPUT_DEVICE && deviceRole_ != OUTPUT_DEVICE) { + dumpString += "INVALID"; + } else { + dumpString += deviceRole_ == INPUT_DEVICE ? "INPUT" : "OUTPUT"; + } + dumpString += " deviceType: " + std::to_string(deviceType_); +} + DeviceType AudioDeviceDescriptor::MapInternalToExternalDeviceType() const { switch (deviceType_) { diff --git a/services/audio_policy/server/src/service/manager/audio_adapter_manager.cpp b/services/audio_policy/server/src/service/manager/audio_adapter_manager.cpp index fbab99e75810cf3fc6c52e248b76ee469788cf3d..fa7fa6e9048b039ec01d20a5587cbac083280143 100644 --- a/services/audio_policy/server/src/service/manager/audio_adapter_manager.cpp +++ b/services/audio_policy/server/src/service/manager/audio_adapter_manager.cpp @@ -972,27 +972,187 @@ AudioRingerMode AudioAdapterManager::GetRingerMode() const return ringerMode_; } +bool AudioAdapterManager::IsPaRoute(uint32_t routeFlag) +{ + if ((routeFlag & AUDIO_OUTPUT_FLAG_DIRECT) || + (routeFlag & AUDIO_OUTPUT_FLAG_FAST) || + (routeFlag & AUDIO_INPUT_FLAG_FAST)) { + return false; + } + return true; +} + // LCOV_EXCL_START -AudioIOHandle AudioAdapterManager::OpenAudioPort(const AudioModuleInfo &audioModuleInfo) +AudioIOHandle AudioAdapterManager::OpenAudioPort(std::shared_ptr pipeInfo, uint32_t &paIndex) { - std::string moduleArgs = GetModuleArgs(audioModuleInfo); + std::string moduleArgs = GetModuleArgs(pipeInfo->moduleInfo_); + AUDIO_INFO_LOG("Adapter load-module %{public}s, route flag: %{public}u", moduleArgs.c_str(), pipeInfo->routeFlag_); + curActiveCount_++; + AudioIOHandle ioHandle = HDI_INVALID_ID; + if (IsPaRoute(pipeInfo->routeFlag_)) { + AUDIO_INFO_LOG("Is pa route"); + return OpenPaAudioPort(pipeInfo, paIndex, moduleArgs); + } + + AUDIO_INFO_LOG("Not pa route"); + return OpenNotPaAudioPort(pipeInfo, paIndex); +} + +AudioIOHandle AudioAdapterManager::OpenPaAudioPort(std::shared_ptr pipeInfo, uint32_t &paIndex, + std::string moduleArgs) +{ + AudioIOHandle ioHandle = HDI_INVALID_ID; + CHECK_AND_RETURN_RET_LOG(audioServerProxy_ != nullptr, ioHandle, "audioServerProxy_ null"); + std::string identity = IPCSkeleton::ResetCallingIdentity(); + if (pipeInfo->pipeRole_ == PIPE_ROLE_OUTPUT) { + std::string idInfo = GetHdiSinkIdInfo(pipeInfo->moduleInfo_); + IAudioSinkAttr attr = GetAudioSinkAttr(pipeInfo->moduleInfo_); + ioHandle = audioServerProxy_->CreateHdiSinkPort(pipeInfo->moduleInfo_.className, idInfo, attr); + } else if (pipeInfo->pipeRole_ == PIPE_ROLE_INPUT) { + std::string idInfo = GetHdiSourceIdInfo(pipeInfo->moduleInfo_); + IAudioSourceAttr attr = GetAudioSourceAttr(pipeInfo->moduleInfo_); + ioHandle = audioServerProxy_->CreateHdiSourcePort(pipeInfo->moduleInfo_.className, idInfo, attr); + } else { + AUDIO_ERR_LOG("Invalid pipe role: %{public}u", pipeInfo->pipeRole_); + } + IPCSkeleton::SetCallingIdentity(identity); + paIndex = audioServiceAdapter_->OpenAudioPort(pipeInfo->moduleInfo_.lib, moduleArgs.c_str()); + AUDIO_INFO_LOG("Open %{public}u port, paIndex: %{public}u end.", ioHandle, paIndex); + return ioHandle; +} + +AudioIOHandle AudioAdapterManager::OpenNotPaAudioPort(std::shared_ptr pipeInfo, uint32_t &paIndex) +{ + AudioIOHandle ioHandle = HDI_INVALID_ID; + CHECK_AND_RETURN_RET_LOG(audioServerProxy_ != nullptr, ioHandle, "audioServerProxy_ null"); + if (pipeInfo->pipeRole_ == PIPE_ROLE_OUTPUT) { + std::string idInfo = HDI_ID_INFO_DEFAULT; + HdiIdType idType = HDI_ID_TYPE_PRIMARY; + GetSinkIdInfoAndIdType(pipeInfo, idInfo, idType); + IAudioSinkAttr attr = GetAudioSinkAttr(pipeInfo->moduleInfo_); + if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_FAST) { + if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_VOIP) { + AUDIO_INFO_LOG("Use voip mmap"); + attr.audioStreamFlag = AUDIO_FLAG_VOIP_FAST; + } else { + attr.audioStreamFlag = AUDIO_FLAG_MMAP; + } + } else if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_DIRECT) { + if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_VOIP) { + AUDIO_INFO_LOG("Use voip direct"); + attr.audioStreamFlag = AUDIO_FLAG_VOIP_DIRECT; + } else { + AUDIO_INFO_LOG("Use direct"); + attr.audioStreamFlag = AUDIO_FLAG_DIRECT; + } + } + std::string identity = IPCSkeleton::ResetCallingIdentity(); + ioHandle = audioServerProxy_->CreateSinkPort(HDI_ID_BASE_RENDER, idType, idInfo, attr); + IPCSkeleton::SetCallingIdentity(identity); + } else if (pipeInfo->pipeRole_ == PIPE_ROLE_INPUT) { + std::string idInfo = HDI_ID_INFO_DEFAULT; + HdiIdType idType = HDI_ID_TYPE_PRIMARY; + GetSourceIdInfoAndIdType(pipeInfo, idInfo, idType); + IAudioSourceAttr attr = GetAudioSourceAttr(pipeInfo->moduleInfo_); + if (pipeInfo->routeFlag_ & AUDIO_INPUT_FLAG_FAST) { + if (pipeInfo->routeFlag_ & AUDIO_INPUT_FLAG_VOIP) { + AUDIO_INFO_LOG("Use voip mmap"); + attr.audioStreamFlag = AUDIO_FLAG_VOIP_FAST; + } else { + attr.audioStreamFlag = AUDIO_FLAG_MMAP; + } + } + std::string identity = IPCSkeleton::ResetCallingIdentity(); + ioHandle = audioServerProxy_->CreateSourcePort(HDI_ID_BASE_CAPTURE, idType, idInfo, attr); + IPCSkeleton::SetCallingIdentity(identity); + } else { + AUDIO_ERR_LOG("Invalid pipe role: %{public}u", pipeInfo->pipeRole_); + } + AUDIO_INFO_LOG("Open %{public}u port, paIndex: %{public}u end.", ioHandle, paIndex); + return ioHandle; +} - AUDIO_INFO_LOG("[Adapter load-module] %{public}s %{public}s", - audioModuleInfo.lib.c_str(), audioModuleInfo.className.c_str()); +void AudioAdapterManager::GetSinkIdInfoAndIdType( + std::shared_ptr pipeInfo, std::string &idInfo, HdiIdType &idType) +{ + if (pipeInfo->adapterName_ == "primary") { + if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_FAST) { + idType = HDI_ID_TYPE_FAST; + if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_VOIP) { + idInfo = HDI_ID_INFO_VOIP; + } + } else if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_DIRECT) { + idType = HDI_ID_TYPE_PRIMARY; + if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_VOIP) { + idInfo = HDI_ID_INFO_VOIP; + } + } + } else if (pipeInfo->adapterName_ == "a2dp") { + if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_FAST) { + idType = HDI_ID_TYPE_BLUETOOTH; + idInfo = HDI_ID_INFO_MMAP; + } + } +} + +void AudioAdapterManager::GetSourceIdInfoAndIdType( + std::shared_ptr pipeInfo, std::string &idInfo, HdiIdType &idType) +{ + if (pipeInfo->adapterName_ == "primary") { + if (pipeInfo->routeFlag_ & AUDIO_INPUT_FLAG_FAST) { + idType = HDI_ID_TYPE_FAST; + if (pipeInfo->routeFlag_ & AUDIO_INPUT_FLAG_VOIP) { + idInfo = HDI_ID_INFO_VOIP; + } + } + } +} + +AudioIOHandle AudioAdapterManager::OpenAudioPort(const AudioModuleInfo &audioModuleInfo, uint32_t &paIndex) +{ + std::string moduleArgs = GetModuleArgs(audioModuleInfo); + AUDIO_INFO_LOG("Adapter load-module %{public}s", moduleArgs.c_str()); CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null"); curActiveCount_++; - AudioIOHandle ioHandle = audioServiceAdapter_->OpenAudioPort(audioModuleInfo.lib, moduleArgs.c_str()); - AUDIO_INFO_LOG("Open %{public}d port end.", static_cast(ioHandle)); + AudioIOHandle ioHandle = HDI_INVALID_ID; + CHECK_AND_RETURN_RET_LOG(audioServerProxy_ != nullptr, ioHandle, "audioServerProxy_ null"); + std::string identity = IPCSkeleton::ResetCallingIdentity(); + if (audioModuleInfo.lib == "libmodule-inner-capturer-sink.z.so") { + std::string idInfo = audioModuleInfo.name; + IAudioSinkAttr attr = GetAudioSinkAttr(audioModuleInfo); + ioHandle = audioServerProxy_->CreateSinkPort(HDI_ID_BASE_RENDER, HDI_ID_TYPE_PRIMARY, idInfo, attr); + } else { + if (audioModuleInfo.role == HDI_AUDIO_PORT_SINK_ROLE) { + std::string idInfo = GetHdiSinkIdInfo(audioModuleInfo); + IAudioSinkAttr attr = GetAudioSinkAttr(audioModuleInfo); + ioHandle = audioServerProxy_->CreateHdiSinkPort(audioModuleInfo.className, idInfo, attr); + } else if (audioModuleInfo.role == HDI_AUDIO_PORT_SOURCE_ROLE) { + std::string idInfo = GetHdiSourceIdInfo(audioModuleInfo); + IAudioSourceAttr attr = GetAudioSourceAttr(audioModuleInfo); + ioHandle = audioServerProxy_->CreateHdiSourcePort(audioModuleInfo.className, idInfo, attr); + } + } + IPCSkeleton::SetCallingIdentity(identity); + + paIndex = audioServiceAdapter_->OpenAudioPort(audioModuleInfo.lib, moduleArgs.c_str()); + AUDIO_INFO_LOG("Open %{public}u port, paIndex: %{public}u end.", ioHandle, paIndex); return ioHandle; } -int32_t AudioAdapterManager::CloseAudioPort(AudioIOHandle ioHandle, bool isSync) +int32_t AudioAdapterManager::CloseAudioPort(AudioIOHandle ioHandle, uint32_t paIndex, bool isSync) { + AUDIO_INFO_LOG("IoHandle: %{public}u, paIndex: %{public}u, curCount: %{public}d", + ioHandle, paIndex, curActiveCount_); CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null"); + CHECK_AND_RETURN_RET_LOG(audioServerProxy_ != nullptr, ERROR, "audioServerProxy_ null"); curActiveCount_--; - int32_t ret = audioServiceAdapter_->CloseAudioPort(ioHandle, isSync); - AUDIO_INFO_LOG("Close %{public}d port end.", static_cast(ioHandle)); + int32_t ret = audioServiceAdapter_->CloseAudioPort(paIndex, isSync); + AudioIOHandle tempHandle = ioHandle; + std::string identity = IPCSkeleton::ResetCallingIdentity(); + audioServerProxy_->DestroyHdiPort(ioHandle); + IPCSkeleton::SetCallingIdentity(identity); + AUDIO_INFO_LOG("Close %{public}u port, paIndex: %{public}u end.", tempHandle, paIndex); return ret; } @@ -1237,6 +1397,127 @@ std::string AudioAdapterManager::GetModuleArgs(const AudioModuleInfo &audioModul return args; } +std::string AudioAdapterManager::GetHdiSinkIdInfo(const AudioModuleInfo &audioModuleInfo) const +{ + if (audioModuleInfo.className == "remote") { + return audioModuleInfo.networkId; + } + return HDI_ID_INFO_DEFAULT; +} + +std::string AudioAdapterManager::GetHdiSourceIdInfo(const AudioModuleInfo &audioModuleInfo) const +{ + if (audioModuleInfo.className == "primary" && audioModuleInfo.sourceType == "SOURCE_TYPE_WAKEUP") { + return audioModuleInfo.name; + } + if (audioModuleInfo.className == "remote") { + return audioModuleInfo.networkId; + } + return HDI_ID_INFO_DEFAULT; +} + +static AudioSampleFormat ParseSinkAudioSampleFormat(const std::string &format) +{ + if (format == "u8") { + return SAMPLE_U8; + } else if (format == "s16le") { + return SAMPLE_S16LE; + } else if (format == "s24le") { + return SAMPLE_S24LE; + } else if (format == "s32le") { + return SAMPLE_S32LE; + } + return INVALID_WIDTH; +} + +static AudioSampleFormat ParseSourceAudioSampleFormat(const std::string &format) +{ + if (format == "u8") { + return SAMPLE_U8; + } else if (format == "s16le" || format == "s16be") { + return SAMPLE_S16LE; + } else if (format == "s24le" || format == "s24be") { + return SAMPLE_S24LE; + } else if (format == "s32le" || format == "s32be") { + return SAMPLE_S32LE; + } + return SAMPLE_S16LE; +} + +static bool IsBigEndian(const std::string &format) +{ + if (format == "s16be" || format == "s24be" || format == "s32be" || format == "f32be") { + return true; + } + return false; +} + +IAudioSinkAttr AudioAdapterManager::GetAudioSinkAttr(const AudioModuleInfo &audioModuleInfo) const +{ + IAudioSinkAttr attr; + attr.adapterName = audioModuleInfo.adapterName.c_str(); + if (!audioModuleInfo.OpenMicSpeaker.empty()) { + attr.openMicSpeaker = static_cast(std::stoul(audioModuleInfo.OpenMicSpeaker)); + } + attr.format = ParseSinkAudioSampleFormat(audioModuleInfo.format); + if (!audioModuleInfo.rate.empty()) { + attr.sampleRate = static_cast(std::stoul(audioModuleInfo.rate)); + } + if (!audioModuleInfo.channels.empty()) { + attr.channel = static_cast(std::stoul(audioModuleInfo.channels)); + } + attr.volume = HDI_MAX_SINK_VOLUME_LEVEL; + attr.filePath = audioModuleInfo.fileName.c_str(); + attr.deviceNetworkId = audioModuleInfo.networkId.c_str(); + if (!audioModuleInfo.deviceType.empty()) { + attr.deviceType = std::stoi(audioModuleInfo.deviceType); + } + if (audioModuleInfo.className == "multichannel") { + attr.channelLayout = HDI_DEFAULT_MULTICHANNEL_CHANNELLAYOUT; + } + return attr; +} + +IAudioSourceAttr AudioAdapterManager::GetAudioSourceAttr(const AudioModuleInfo &audioModuleInfo) const +{ + IAudioSourceAttr attr; + attr.adapterName = audioModuleInfo.adapterName.c_str(); + if (!audioModuleInfo.OpenMicSpeaker.empty()) { + attr.openMicSpeaker = static_cast(std::stoul(audioModuleInfo.OpenMicSpeaker)); + } + attr.format = ParseSourceAudioSampleFormat(audioModuleInfo.format); + if (!audioModuleInfo.OpenMicSpeaker.empty()) { + attr.sampleRate = static_cast(std::stoul(audioModuleInfo.rate)); + } + if (!audioModuleInfo.channels.empty()) { + attr.channel = static_cast(std::stoul(audioModuleInfo.channels)); + } + if (!audioModuleInfo.bufferSize.empty()) { + attr.bufferSize = static_cast(std::stoul(audioModuleInfo.bufferSize)); + } + attr.isBigEndian = IsBigEndian(audioModuleInfo.format); + attr.filePath = audioModuleInfo.fileName.c_str(); + attr.deviceNetworkId = audioModuleInfo.networkId.c_str(); + if (!audioModuleInfo.deviceType.empty()) { + attr.deviceType = std::stoi(audioModuleInfo.deviceType); + } + if (!audioModuleInfo.sourceType.empty()) { + attr.sourceType = std::stoi(audioModuleInfo.sourceType); + } + if ((!audioModuleInfo.ecType.empty()) && static_cast(std::stoul(audioModuleInfo.ecType)) == + HDI_EC_SAME_ADAPTER) { + attr.hasEcConfig = true; + attr.formatEc = ParseSourceAudioSampleFormat(audioModuleInfo.ecFormat); + if (!audioModuleInfo.ecSamplingRate.empty()) { + attr.sampleRateEc = static_cast(std::stoul(audioModuleInfo.ecSamplingRate)); + } + if (!audioModuleInfo.ecChannels.empty()) { + attr.channelEc = static_cast(std::stoul(audioModuleInfo.ecChannels)); + } + } + return attr; +} + std::string AudioAdapterManager::GetVolumeKeyForKvStore(DeviceType deviceType, AudioStreamType streamType) { DeviceGroup type = GetVolumeGroupForDevice(deviceType); diff --git a/services/audio_policy/server/src/service/service/audio_capturer_session.cpp b/services/audio_policy/server/src/service/service/audio_capturer_session.cpp index 543394bafe2215ce74700fda6dfa27a63b983b09..8944e90e45f3484f80014d4c65b51f32a9f9d20e 100644 --- a/services/audio_policy/server/src/service/service/audio_capturer_session.cpp +++ b/services/audio_policy/server/src/service/service/audio_capturer_session.cpp @@ -24,6 +24,7 @@ #include "audio_policy_log.h" #include "audio_policy_utils.h" +#include "audio_core_service.h" namespace OHOS { namespace AudioStandard { @@ -105,6 +106,7 @@ void AudioCapturerSession::UnloadInnerCapturerSink(std::string moduleName) void AudioCapturerSession::HandleRemoteCastDevice(bool isConnected, AudioStreamInfo streamInfo) { #ifdef HAS_FEATURE_INNERCAPTURER + AUDIO_INFO_LOG("Is connected: %{public}d", isConnected); AudioDeviceDescriptor updatedDesc = AudioDeviceDescriptor(DEVICE_TYPE_REMOTE_CAST, AudioPolicyUtils::GetInstance().GetDeviceRole(DEVICE_TYPE_REMOTE_CAST)); std::vector> descForCb = {}; @@ -117,11 +119,12 @@ void AudioCapturerSession::HandleRemoteCastDevice(bool isConnected, AudioStreamI audioPolicyManager_.ResetRemoteCastDeviceVolume(); } else { audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb); - audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::OLD_DEVICE_UNAVALIABLE_EXT); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute( + AudioStreamDeviceChangeReasonExt::ExtEnum::OLD_DEVICE_UNAVALIABLE_EXT); UnloadInnerCapturerSink(REMOTE_CAST_INNER_CAPTURER_SINK_NAME); } - audioDeviceCommon_.FetchDevice(true); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute(); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); // update a2dp offload if (audioA2dpOffloadManager_) { @@ -144,11 +147,10 @@ int32_t AudioCapturerSession::OnCapturerSessionAdded(uint64_t sessionID, Session } if (specialSourceTypeSet_.count(sessionInfo.sourceType) == 0) { // normal source types, dynamic open - StreamPropInfo targetInfo; + PipeStreamPropInfo targetInfo; SourceType targetSource; int32_t res = audioEcManager_.FetchTargetInfoForSessionAdd(sessionInfo, targetInfo, targetSource); - CHECK_AND_RETURN_RET_LOG(res == SUCCESS, res, - "fetch target source info error"); + CHECK_AND_RETURN_RET_LOG(res == SUCCESS, res, "fetch target source info error"); if (audioEcManager_.GetSourceOpened() == SOURCE_TYPE_INVALID) { // normal source is not opened before @@ -233,15 +235,15 @@ bool AudioCapturerSession::ConstructWakeupAudioModuleInfo(const AudioStreamInfo return false; } - AudioAdapterInfo info; - AdaptersType type = static_cast(AudioPolicyUtils::portStrToEnum[std::string(PRIMARY_WAKEUP)]); + std::shared_ptr info; + AudioAdapterType type = static_cast(AudioPolicyUtils::portStrToEnum[std::string(PRIMARY_WAKEUP)]); bool ret = audioConfigManager_.GetAdapterInfoByType(type, info); if (!ret) { AUDIO_ERR_LOG("can not find adapter info"); return false; } - auto pipeInfo = info.GetPipeByName(PIPE_WAKEUP_INPUT); + std::shared_ptr pipeInfo = info->GetPipeInfoByName(PIPE_WAKEUP_INPUT); if (pipeInfo == nullptr) { AUDIO_ERR_LOG("wakeup pipe info is nullptr"); return false; @@ -252,9 +254,9 @@ bool AudioCapturerSession::ConstructWakeupAudioModuleInfo(const AudioStreamInfo return false; } - audioModuleInfo.adapterName = info.adapterName_; - audioModuleInfo.name = pipeInfo->moduleName_; - audioModuleInfo.lib = pipeInfo->lib_; + audioModuleInfo.adapterName = info->adapterName; + audioModuleInfo.name = pipeInfo->paProp_.moduleName_; + audioModuleInfo.lib = pipeInfo->paProp_.lib_; audioModuleInfo.networkId = "LocalDevice"; audioModuleInfo.className = "primary"; audioModuleInfo.fileName = ""; @@ -294,8 +296,8 @@ int32_t AudioCapturerSession::CloseWakeUpAudioCapturer() } // private method -bool AudioCapturerSession::FillWakeupStreamPropInfo(const AudioStreamInfo &streamInfo, PipeInfo *pipeInfo, - AudioModuleInfo &audioModuleInfo) +bool AudioCapturerSession::FillWakeupStreamPropInfo(const AudioStreamInfo &streamInfo, + std::shared_ptr pipeInfo, AudioModuleInfo &audioModuleInfo) { if (pipeInfo == nullptr) { AUDIO_ERR_LOG("wakeup pipe info is nullptr"); @@ -307,16 +309,16 @@ bool AudioCapturerSession::FillWakeupStreamPropInfo(const AudioStreamInfo &strea return false; } - auto targetIt = pipeInfo->streamPropInfos_.begin(); - for (auto it = pipeInfo->streamPropInfos_.begin(); it != pipeInfo->streamPropInfos_.end(); ++it) { - if (it -> channelLayout_ == static_cast(streamInfo.channels)) { + auto targetIt = *pipeInfo->streamPropInfos_.begin(); + for (auto it : pipeInfo->streamPropInfos_) { + if (it -> channels_ == static_cast(streamInfo.channels)) { targetIt = it; break; } } - audioModuleInfo.format = targetIt->format_; - audioModuleInfo.channels = std::to_string(targetIt->channelLayout_); + audioModuleInfo.format = AudioDefinitionPolicyUtils::enumToFormatStr[targetIt->format_]; + audioModuleInfo.channels = std::to_string(targetIt->channels_); audioModuleInfo.rate = std::to_string(targetIt->sampleRate_); audioModuleInfo.bufferSize = std::to_string(targetIt->bufferSize_); diff --git a/services/audio_policy/server/src/service/service/audio_config_manager.cpp b/services/audio_policy/server/src/service/service/audio_config_manager.cpp index 3dd6e21da204dbe20c3a85101417f72032fd8ae8..aed1d21ba25f42c81abd1c34592abb133bf8b0e0 100644 --- a/services/audio_policy/server/src/service/service/audio_config_manager.cpp +++ b/services/audio_policy/server/src/service/service/audio_config_manager.cpp @@ -28,6 +28,7 @@ #include "audio_policy_utils.h" #include "audio_policy_service.h" +#include "audio_core_service.h" namespace OHOS { namespace AudioStandard { @@ -135,8 +136,8 @@ bool AudioConfigManager::GetDefaultAdapterEnable() void AudioConfigManager::OnUpdateAnahsSupport(std::string anahsShowType) { - AUDIO_INFO_LOG("OnUpdateAnahsSupport show type: %{public}s", anahsShowType.c_str()); - AudioPolicyService::GetAudioPolicyService().OnUpdateAnahsSupport(anahsShowType); + AUDIO_INFO_LOG("Show type: %{public}s", anahsShowType.c_str()); + AudioCoreService::GetCoreService()->OnUpdateAnahsSupport(anahsShowType); } void AudioConfigManager::OnVolumeGroupParsed(std::unordered_map& volumeGroupData) @@ -214,6 +215,7 @@ int32_t AudioConfigManager::GetVoipRendererFlag(const std::string &sinkPortName, const AudioSamplingRate &samplingRate) { // VoIP stream has three mode for different products. + AUDIO_INFO_LOG("enableFastVoip_: %{public}d", enableFastVoip_); if (enableFastVoip_ && (sinkPortName == PRIMARY_SPEAKER && networkId == LOCAL_NETWORK_ID)) { if (samplingRate != SAMPLE_RATE_48000 && samplingRate != SAMPLE_RATE_16000) { return AUDIO_FLAG_NORMAL; diff --git a/services/audio_policy/server/src/service/service/audio_device_common.cpp b/services/audio_policy/server/src/service/service/audio_device_common.cpp index e0c39d55d551b707ef72ecbb64f7e8e1e4bc29fc..49661c2963a359a6012a1f8bdcf5cb89b6cc4eb8 100644 --- a/services/audio_policy/server/src/service/service/audio_device_common.cpp +++ b/services/audio_policy/server/src/service/service/audio_device_common.cpp @@ -219,103 +219,15 @@ std::vector> AudioDeviceCommon::GetPrefer int32_t AudioDeviceCommon::GetPreferredOutputStreamTypeInner(StreamUsage streamUsage, DeviceType deviceType, int32_t flags, std::string &networkId, AudioSamplingRate &samplingRate) { - AUDIO_INFO_LOG("Device type: %{public}d, stream usage: %{public}d, flag: %{public}d", - deviceType, streamUsage, flags); - std::string sinkPortName = AudioPolicyUtils::GetInstance().GetSinkPortName(deviceType); - if (streamUsage == STREAM_USAGE_VOICE_COMMUNICATION || streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) { - // Avoid two voip stream existing - if (streamCollector_.HasVoipRendererStream()) { - AUDIO_WARNING_LOG("Voip Change To Normal"); - return AUDIO_FLAG_NORMAL; - } - - // VoIP stream. Need to judge whether it is fast or direct mode. - int32_t flag = audioConfigManager_.GetVoipRendererFlag(sinkPortName, networkId, samplingRate); - if (flag == AUDIO_FLAG_VOIP_FAST || flag == AUDIO_FLAG_VOIP_DIRECT) { - return flag; - } - } - if (!audioConfigManager_.GetAdapterInfoFlag()) { - return AUDIO_FLAG_NORMAL; - } - AudioAdapterInfo adapterInfo; - bool ret = audioConfigManager_.GetAdapterInfoByType(static_cast( - AudioPolicyUtils::portStrToEnum[sinkPortName]), adapterInfo); - if (!ret) { - AUDIO_ERR_LOG("Invalid adapter"); - return AUDIO_FLAG_NORMAL; - } - - AudioPipeDeviceInfo* deviceInfo = adapterInfo.GetDeviceInfoByDeviceType(deviceType); - CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, AUDIO_FLAG_NORMAL, "Device type is not supported"); - for (auto &supportPipe : deviceInfo->supportPipes_) { - PipeInfo* pipeInfo = adapterInfo.GetPipeByName(supportPipe); - if (pipeInfo == nullptr) { - continue; - } - if (flags == AUDIO_FLAG_MMAP && pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) { - return AUDIO_FLAG_MMAP; - } - if (flags == AUDIO_FLAG_VOIP_FAST && pipeInfo->audioUsage_ == AUDIO_USAGE_VOIP && - pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) { - return AUDIO_FLAG_VOIP_FAST; - } - } - return AUDIO_FLAG_NORMAL; + AUDIO_INFO_LOG("Not support, should use AudioPipeSelector"); + return flags; } int32_t AudioDeviceCommon::GetPreferredInputStreamTypeInner(SourceType sourceType, DeviceType deviceType, int32_t flags, const std::string &networkId, const AudioSamplingRate &samplingRate) { - AUDIO_INFO_LOG("Device type: %{public}d, source type: %{public}d, flag: %{public}d", - deviceType, sourceType, flags); - - std::string sourcePortName = AudioPolicyUtils::GetInstance().GetSourcePortName(deviceType); - if (sourceType == SOURCE_TYPE_VOICE_COMMUNICATION && - (sourcePortName == PRIMARY_MIC && networkId == LOCAL_NETWORK_ID)) { - if (audioConfigManager_.GetVoipConfig() && (samplingRate == SAMPLE_RATE_48000 - || samplingRate == SAMPLE_RATE_16000)) { - // Avoid voip stream existing with other - if (streamCollector_.ChangeVoipCapturerStreamToNormal()) { - AUDIO_WARNING_LOG("Voip Change To Normal"); - return AUDIO_FLAG_NORMAL; - } - return AUDIO_FLAG_VOIP_FAST; - } - return AUDIO_FLAG_NORMAL; - } - if (!audioConfigManager_.GetAdapterInfoFlag()) { - return AUDIO_FLAG_NORMAL; - } - AudioAdapterInfo adapterInfo; - bool ret = audioConfigManager_.GetAdapterInfoByType(static_cast( - AudioPolicyUtils::portStrToEnum[sourcePortName]), adapterInfo); - if (!ret) { - AUDIO_ERR_LOG("Invalid adapter"); - return AUDIO_FLAG_NORMAL; - } - - AudioPipeDeviceInfo* deviceInfo = adapterInfo.GetDeviceInfoByDeviceType(deviceType); - CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, AUDIO_FLAG_NORMAL, "Device type is not supported"); - for (auto &supportPipe : deviceInfo->supportPipes_) { - PipeInfo* pipeInfo = adapterInfo.GetPipeByName(supportPipe); - if (pipeInfo == nullptr) { - continue; - } - if (flags == AUDIO_FLAG_MMAP && pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) { - return AUDIO_FLAG_MMAP; - } - if (flags == AUDIO_FLAG_VOIP_FAST && pipeInfo->audioUsage_ == AUDIO_USAGE_VOIP && - pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) { - // Avoid voip stream existing with other - if (streamCollector_.ChangeVoipCapturerStreamToNormal()) { - AUDIO_WARNING_LOG("Voip Change To Normal By DeviceInfo"); - return AUDIO_FLAG_NORMAL; - } - return AUDIO_FLAG_VOIP_FAST; - } - } - return AUDIO_FLAG_NORMAL; + AUDIO_INFO_LOG("Not support, should use AudioPipeSelector"); + return flags; } void AudioDeviceCommon::UpdateDeviceInfo(AudioDeviceDescriptor &deviceInfo, @@ -573,7 +485,7 @@ bool AudioDeviceCommon::IsFastFromA2dpToA2dp(const std::shared_ptrrendererInfo.originalFlag == AUDIO_FLAG_MMAP && rendererChangeInfo->outputDeviceInfo.deviceId_ != desc->deviceId_) { TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, rendererChangeInfo->sessionId, - AUDIO_FLAG_MMAP, reason); + AUDIO_OUTPUT_FLAG_FAST, reason); AUDIO_INFO_LOG("Switch fast stream from a2dp to a2dp"); return true; } @@ -592,7 +504,7 @@ bool AudioDeviceCommon::NotifyRecreateDirectStream(std::shared_ptrcallerPid, rendererChangeInfo->sessionId, - AUDIO_FLAG_DIRECT, reason); + AUDIO_OUTPUT_FLAG_NORMAL, reason); return true; } else if (audioActiveDevice_.IsDirectSupportedDevice() && rendererChangeInfo->rendererInfo.pipeType != PIPE_TYPE_DIRECT_MUSIC) { @@ -601,7 +513,7 @@ bool AudioDeviceCommon::NotifyRecreateDirectStream(std::shared_ptr= SAMPLE_RATE_48000 && info.format >= SAMPLE_S24LE) { AUDIO_DEBUG_LOG("stream change to direct."); TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, rendererChangeInfo->sessionId, - AUDIO_FLAG_DIRECT, reason); + AUDIO_OUTPUT_FLAG_DIRECT, reason); return true; } } @@ -873,38 +785,7 @@ int32_t AudioDeviceCommon::HandleScoOutputDeviceFetched(std::shared_ptr &desc, const std::shared_ptr &rendererChangeInfo, const AudioStreamDeviceChangeReasonExt reason) { - AUDIO_INFO_LOG("New device type: %{public}d, current rendererFlag: %{public}d, origianl flag: %{public}d", - desc->deviceType_, rendererChangeInfo->rendererInfo.rendererFlags, - rendererChangeInfo->rendererInfo.originalFlag); - CHECK_AND_RETURN_RET_LOG((rendererChangeInfo->outputDeviceInfo.deviceType_ != DEVICE_TYPE_INVALID && - desc->deviceType_ != DEVICE_TYPE_INVALID) || desc->deviceType_ == DEVICE_TYPE_REMOTE_CAST, - false, "isUpdateActiveDevice is false"); - CHECK_AND_RETURN_RET_LOG(desc->deviceType_ != DEVICE_TYPE_REMOTE_CAST || - (desc->deviceType_ == DEVICE_TYPE_REMOTE_CAST && - rendererChangeInfo->rendererInfo.rendererFlags != AUDIO_FLAG_NORMAL), - false, "new device is remote cast and current renderer flag is normal"); - // Switch between old and new stream as they have different hals - std::string oldDevicePortName - = AudioPolicyUtils::GetInstance().GetSinkPortName(rendererChangeInfo->outputDeviceInfo.deviceType_); - bool isOldDeviceLocal = rendererChangeInfo->outputDeviceInfo.networkId_ == "" || - rendererChangeInfo->outputDeviceInfo.networkId_ == LOCAL_NETWORK_ID; - bool isNewDeviceLocal = desc->networkId_ == "" || desc->networkId_ == LOCAL_NETWORK_ID; - AudioScene scene = audioSceneManager_.GetAudioScene(true); - if (!(isOldDeviceLocal ^ isNewDeviceLocal) || scene == AUDIO_SCENE_PHONE_CALL) { - CHECK_AND_RETURN_RET_LOG(rendererChangeInfo->rendererInfo.originalFlag != AUDIO_FLAG_NORMAL && - rendererChangeInfo->rendererInfo.originalFlag != AUDIO_FLAG_FORCED_NORMAL, false, - "original flag is normal"); - } - if ((strcmp(oldDevicePortName.c_str(), - AudioPolicyUtils::GetInstance().GetSinkPortName(desc->deviceType_).c_str())) || - (isOldDeviceLocal ^ isNewDeviceLocal)) { - int32_t streamClass = GetPreferredOutputStreamTypeInner(rendererChangeInfo->rendererInfo.streamUsage, - desc->deviceType_, rendererChangeInfo->rendererInfo.originalFlag, desc->networkId_, - rendererChangeInfo->rendererInfo.samplingRate); - TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, - rendererChangeInfo->sessionId, streamClass, reason); - return true; - } + AUDIO_INFO_LOG("Not support, should use AudioPipeSelector"); return false; } @@ -1984,7 +1865,8 @@ int32_t AudioDeviceCommon::LoadA2dpModule(DeviceType deviceType, const AudioStre if (audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name) == false) { // a2dp device connects for the first time GetA2dpModuleInfo(moduleInfo, audioStreamInfo, sourceType); - AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo); + uint32_t temp = 0; + AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, temp); CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED, "OpenAudioPort failed %{public}d", ioHandle); audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle); @@ -2022,7 +1904,8 @@ int32_t AudioDeviceCommon::ReloadA2dpAudioPort(AudioModuleInfo &moduleInfo, Devi // Load a2dp sink or source module again with the configuration of active a2dp device. GetA2dpModuleInfo(moduleInfo, audioStreamInfo, sourceType); - AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo); + uint32_t temp = 0; + AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, temp); CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED, "OpenAudioPort failed %{public}d", ioHandle); audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle); diff --git a/services/audio_policy/server/src/service/service/audio_device_status.cpp b/services/audio_policy/server/src/service/service/audio_device_status.cpp index 7fc56c0f22a6948ca0c69c7dbfb6a851faa192c9..38417ae417fef23ebf199ab001691af0a132d740 100644 --- a/services/audio_policy/server/src/service/service/audio_device_status.cpp +++ b/services/audio_policy/server/src/service/service/audio_device_status.cpp @@ -29,6 +29,7 @@ #include "audio_policy_utils.h" #include "audio_server_proxy.h" +#include "audio_core_service.h" namespace OHOS { namespace AudioStandard { @@ -117,8 +118,8 @@ void AudioDeviceStatus::OnDeviceStatusUpdated(DeviceType devType, bool isConnect int32_t result = HandleSpecialDeviceType(devType, isConnected, macAddress, role); CHECK_AND_RETURN_LOG(result == SUCCESS, "handle special deviceType failed."); - AUDIO_WARNING_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d], address[%{public}s]", - devType, isConnected, GetEncryptStr(macAddress).c_str()); + AUDIO_WARNING_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d], address[%{public}s], " + "role[%{public}d]", devType, isConnected, GetEncryptStr(macAddress).c_str(), role); AudioDeviceDescriptor updatedDesc(devType, role == DEVICE_ROLE_NONE ? AudioPolicyUtils::GetInstance().GetDeviceRole(devType) : role); @@ -159,8 +160,8 @@ void AudioDeviceStatus::OnDeviceStatusUpdated(DeviceType devType, bool isConnect TriggerAvailableDeviceChangedCallback(descForCb, isConnected); // fetch input&output device - audioDeviceCommon_.FetchDevice(true, reason); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute(reason); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); // update a2dp offload audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream(); @@ -372,6 +373,7 @@ int32_t AudioDeviceStatus::HandleLocalDeviceConnected(AudioDeviceDescriptor &upd void AudioDeviceStatus::UpdateActiveA2dpDeviceWhenDisconnecting(const std::string& macAddress) { + AUDIO_INFO_LOG("In"); if (audioA2dpDevice_.DelA2dpDevice(macAddress) == 0) { audioActiveDevice_.SetActiveBtDeviceMac(""); audioIOHandleMap_.ClosePortAndEraseIOHandle(BLUETOOTH_SPEAKER); @@ -556,7 +558,7 @@ void AudioDeviceStatus::ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType, uint32_t bufferSize = streamInfo.samplingRate * AudioPolicyUtils::GetInstance().PcmFormatToBytes(streamInfo.format) * streamInfo.channels / BT_BUFFER_ADJUSTMENT_FACTOR; - AUDIO_DEBUG_LOG("Updated buffer size: %{public}d", bufferSize); + AUDIO_INFO_LOG("Updated buffer size: %{public}d", bufferSize); std::list moduleInfoList; bool ret = audioConfigManager_.GetModuleListByType(ClassType::TYPE_A2DP, moduleInfoList); @@ -583,8 +585,9 @@ void AudioDeviceStatus::ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType, audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle); // Load bt sink module again with new configuration - AUDIO_DEBUG_LOG("Reload a2dp module [%{public}s]", moduleInfo.name.c_str()); - AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo); + AUDIO_INFO_LOG("Reload a2dp module [%{public}s]", moduleInfo.name.c_str()); + uint32_t paIndex; + AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, paIndex); if (ioHandle == OPEN_PORT_FAILURE) { audioPolicyManager_.SuspendAudioDevice(currentActivePort, false); AUDIO_ERR_LOG("OpenAudioPort failed %{public}d", ioHandle); @@ -656,6 +659,7 @@ bool AudioDeviceStatus::IsConfigurationUpdated(DeviceType deviceType, const Audi DeviceType AudioDeviceStatus::GetDeviceTypeFromPin(AudioPin hdiPin) { + AUDIO_INFO_LOG("Pin: %{public}d", hdiPin); switch (hdiPin) { case OHOS::AudioStandard::AUDIO_PIN_NONE: break; @@ -708,9 +712,9 @@ void AudioDeviceStatus::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isSto TriggerDeviceChangedCallback(descForCb, statusInfo.isConnected); TriggerAvailableDeviceChangedCallback(descForCb, statusInfo.isConnected); - audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE); - audioDeviceCommon_.FetchDevice(false); - + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute( + AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin); if (AudioPolicyUtils::GetInstance().GetDeviceRole(devType) == DeviceRole::INPUT_DEVICE) { remoteCapturerSwitch_ = true; @@ -731,7 +735,29 @@ int32_t AudioDeviceStatus::ActivateNewDevice(std::string networkId, DeviceType d AudioPolicyUtils::GetInstance().GetDeviceRole(deviceType), deviceType); std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId, AudioPolicyUtils::GetInstance().GetDeviceRole(deviceType)); - audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleName, moduleInfo); + AUDIO_INFO_LOG("Module name: %{public}s, adapter name: %{public}s", + moduleName.c_str(), moduleInfo.adapterName.c_str()); + uint32_t paIndex = 0; + AudioIOHandle ioHandle = AudioPolicyManagerFactory::GetAudioPolicyManager().OpenAudioPort(moduleInfo, paIndex); + CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_INVALID_HANDLE, + "OpenAudioPort failed: %{public}d", ioHandle); + + std::shared_ptr pipeInfo_ = std::make_shared(); + pipeInfo_->id_ = ioHandle; + pipeInfo_->paIndex_ = paIndex; + if (moduleInfo.role == "sink") { + pipeInfo_->pipeRole_ = PIPE_ROLE_OUTPUT; + pipeInfo_->routeFlag_ = AUDIO_OUTPUT_FLAG_NORMAL; + } else { + pipeInfo_->pipeRole_ = PIPE_ROLE_INPUT; + pipeInfo_->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL; + } + pipeInfo_->adapterName_ = moduleInfo.adapterName; + pipeInfo_->moduleInfo_ = moduleInfo; + pipeInfo_->pipeAction_ = PIPE_ACTION_DEFAULT; + + AudioPipeManager::GetPipeManager()->AddAudioPipeInfo(pipeInfo_); + audioIOHandleMap_.AddIOHandleInfo(moduleName, ioHandle); } return SUCCESS; } @@ -935,7 +961,7 @@ void AudioDeviceStatus::OnForcedDeviceSelected(DeviceType devType, const std::st } else { AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_MEDIA_RENDER, audioDeviceDescriptors[0]); } - audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute(AudioStreamDeviceChangeReason::OVERRODE); audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(), audioActiveDevice_.GetCurrentOutputDevice(), "OnForcedDeviceSelected"); } @@ -970,8 +996,8 @@ void AudioDeviceStatus::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc return; } // fetch input&output device - audioDeviceCommon_.FetchDevice(true, reason); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute(reason); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); // update a2dp offload if (devType == DEVICE_TYPE_BLUETOOTH_A2DP && audioA2dpOffloadManager_) { audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream(); @@ -996,11 +1022,13 @@ void AudioDeviceStatus::UpdateDeviceList(AudioDeviceDescriptor &updatedDesc, bo audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb); reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE; CheckForA2dpSuspend(updatedDesc); - audioDeviceCommon_.FetchDevice(true, reason); // fix pop, fetch device before unload module + // fix pop, fetch device before unload module + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute(reason); int32_t result = HandleLocalDeviceDisconnected(updatedDesc); CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed."); reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE; } + AUDIO_INFO_LOG("Device: %{public}d, isConnected: %{public}d", updatedDesc.deviceType_, isConnected); } #ifdef BLUETOOTH_ENABLE @@ -1047,8 +1075,8 @@ void AudioDeviceStatus::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const D AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN; OnPreferredStateUpdated(desc, command, reason); - audioDeviceCommon_.FetchDevice(true, reason); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute(reason); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); if (audioA2dpOffloadManager_) { audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream(); } @@ -1206,8 +1234,9 @@ void AudioDeviceStatus::HandleOfflineDistributedDevice() TriggerAvailableDeviceChangedCallback(deviceChangeDescriptor, false); AUDIO_INFO_LOG("onDeviceStatusUpdated reson:%{public}d", AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE); - audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute( + AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); } } diff --git a/services/audio_policy/server/src/service/service/audio_ec_manager.cpp b/services/audio_policy/server/src/service/service/audio_ec_manager.cpp index 7c34a39b973bc8aecae2b9ea349bfe226e687cdd..0a5d19b13ebe02a1194dfd1d588fdeadea4a2e19 100644 --- a/services/audio_policy/server/src/service/service/audio_ec_manager.cpp +++ b/services/audio_policy/server/src/service/service/audio_ec_manager.cpp @@ -172,7 +172,7 @@ void AudioEcManager::Init(int32_t ecEnableState, int32_t micRefEnableState) } void AudioEcManager::PrepareAndOpenNormalSource(SessionInfo &sessionInfo, - StreamPropInfo &targetInfo, SourceType targetSource) + PipeStreamPropInfo &targetInfo, SourceType targetSource) { AudioModuleInfo moduleInfo; UpdateEnhanceEffectState(targetSource); @@ -231,16 +231,16 @@ void AudioEcManager::UpdateEnhanceEffectState(SourceType source) isEcFeatureEnable_, isMicRefFeatureEnable_, isMicRefRecordOn_, isMicRefVoipUpOn_); } -void AudioEcManager::UpdateStreamCommonInfo(AudioModuleInfo &moduleInfo, StreamPropInfo &targetInfo, +void AudioEcManager::UpdateStreamCommonInfo(AudioModuleInfo &moduleInfo, PipeStreamPropInfo &targetInfo, SourceType sourceType) { if (!isEcFeatureEnable_) { moduleInfo = primaryMicModuleInfo_; // current layout represents the number of channel. This will need to be modify in the future. - moduleInfo.channels = std::to_string(targetInfo.channelLayout_); + moduleInfo.channels = std::to_string(targetInfo.channels_); moduleInfo.rate = std::to_string(targetInfo.sampleRate_); moduleInfo.bufferSize = std::to_string(targetInfo.bufferSize_); - moduleInfo.format = targetInfo.format_; + moduleInfo.format = AudioDefinitionPolicyUtils::enumToFormatStr[targetInfo.format_]; moduleInfo.sourceType = std::to_string(sourceType); } else { shared_ptr inputDesc = audioRouterCenter_.FetchInputDevice(sourceType, -1); @@ -250,16 +250,16 @@ void AudioEcManager::UpdateStreamCommonInfo(AudioModuleInfo &moduleInfo, StreamP } else { moduleInfo = primaryMicModuleInfo_; // current layout represents the number of channel. This will need to be modify in the future. - moduleInfo.channels = std::to_string(targetInfo.channelLayout_); + moduleInfo.channels = std::to_string(targetInfo.channels_); moduleInfo.rate = std::to_string(targetInfo.sampleRate_); moduleInfo.bufferSize = std::to_string(targetInfo.bufferSize_); - moduleInfo.format = targetInfo.format_; + moduleInfo.format = AudioDefinitionPolicyUtils::enumToFormatStr[targetInfo.format_]; moduleInfo.sourceType = std::to_string(sourceType); moduleInfo.deviceType = std::to_string(static_cast(inputDesc->deviceType_)); // update primary info for ec config to get later - primaryMicModuleInfo_.channels = std::to_string(targetInfo.channelLayout_); + primaryMicModuleInfo_.channels = std::to_string(targetInfo.channels_); primaryMicModuleInfo_.rate = std::to_string(targetInfo.sampleRate_); - primaryMicModuleInfo_.format = targetInfo.format_; + primaryMicModuleInfo_.format = AudioDefinitionPolicyUtils::enumToFormatStr[targetInfo.format_]; } } } @@ -290,58 +290,61 @@ void AudioEcManager::UpdateStreamMicRefInfo(AudioModuleInfo &moduleInfo, SourceT UpdateModuleInfoForMicRef(moduleInfo, sourceType); } -std::string AudioEcManager::GetEcSamplingRate(const std::string &halName, StreamPropInfo &outModuleInfo) +std::string AudioEcManager::GetEcSamplingRate(const std::string &halName, + std::shared_ptr &outModuleInfo) { if (halName == DP_CLASS) { if (!dpSinkModuleInfo_.rate.empty()) { AUDIO_INFO_LOG("use dp cust param"); return dpSinkModuleInfo_.rate; } - return std::to_string(outModuleInfo.sampleRate_); + return std::to_string(outModuleInfo->sampleRate_); } else if (halName == USB_CLASS) { if (!usbSinkModuleInfo_.rate.empty()) { AUDIO_INFO_LOG("use arm usb cust param"); return usbSinkModuleInfo_.rate; } - return std::to_string(outModuleInfo.sampleRate_); + return std::to_string(outModuleInfo->sampleRate_); } else { return primaryMicModuleInfo_.rate; } } -std::string AudioEcManager::GetEcFormat(const std::string &halName, StreamPropInfo &outModuleInfo) +std::string AudioEcManager::GetEcFormat(const std::string &halName, + std::shared_ptr &outModuleInfo) { if (halName == DP_CLASS) { if (!dpSinkModuleInfo_.format.empty()) { AUDIO_INFO_LOG("use dp cust param"); return dpSinkModuleInfo_.format; } - return outModuleInfo.format_; + return AudioDefinitionPolicyUtils::enumToFormatStr[outModuleInfo->format_]; } else if (halName == USB_CLASS) { if (!usbSinkModuleInfo_.format.empty()) { AUDIO_INFO_LOG("use arm usb cust param"); return usbSinkModuleInfo_.format; } - return outModuleInfo.format_; + return AudioDefinitionPolicyUtils::enumToFormatStr[outModuleInfo->format_]; } else { return primaryMicModuleInfo_.format; } } -std::string AudioEcManager::GetEcChannels(const std::string &halName, StreamPropInfo &outModuleInfo) +std::string AudioEcManager::GetEcChannels(const std::string &halName, + std::shared_ptr &outModuleInfo) { if (halName == DP_CLASS) { if (!dpSinkModuleInfo_.channels.empty()) { AUDIO_INFO_LOG("use dp cust param"); return dpSinkModuleInfo_.channels; } - return std::to_string(outModuleInfo.channelLayout_); + return std::to_string(outModuleInfo->channels_); } else if (halName == USB_CLASS) { if (!usbSinkModuleInfo_.channels.empty()) { AUDIO_INFO_LOG("use arm usb cust param"); return usbSinkModuleInfo_.channels; } - return std::to_string(outModuleInfo.channelLayout_); + return std::to_string(outModuleInfo->channels_); } else { return std::to_string(HEADPHONE_CHANNEL_NUM); } @@ -375,7 +378,7 @@ std::string AudioEcManager::GetPipeNameByDeviceForEc(const std::string &role, co } int32_t AudioEcManager::GetPipeInfoByDeviceTypeForEc(const std::string &role, const DeviceType deviceType, - PipeInfo &pipeInfo) + std::shared_ptr pipeInfo) { std::string portName; if (role == ROLE_SOURCE) { @@ -383,8 +386,8 @@ int32_t AudioEcManager::GetPipeInfoByDeviceTypeForEc(const std::string &role, co } else { portName = AudioPolicyUtils::GetInstance().GetSinkPortName(deviceType); } - AudioAdapterInfo info; - bool ret = audioConfigManager_.GetAdapterInfoByType(static_cast( + std::shared_ptr info; + bool ret = audioConfigManager_.GetAdapterInfoByType(static_cast( AudioPolicyUtils::portStrToEnum[portName]), info); if (!ret) { AUDIO_ERR_LOG("no adapter found for deviceType: %{public}d, portName: %{public}s", @@ -392,15 +395,14 @@ int32_t AudioEcManager::GetPipeInfoByDeviceTypeForEc(const std::string &role, co return ERROR; } std::string pipeName = GetPipeNameByDeviceForEc(role, deviceType); - auto pipe = info.GetPipeByName(pipeName); - if (pipe == nullptr) { + pipeInfo = info->GetPipeInfoByName(pipeName); + if (pipeInfo == nullptr) { AUDIO_ERR_LOG("no pipe info found for pipeName: %{public}s, deviceType: %{public}d, portName: %{public}s", pipeName.c_str(), deviceType, portName.c_str()); return ERROR; } - pipeInfo = *pipe; AUDIO_INFO_LOG("pipe name: %{public}s, moduleName: %{public}s found for device: %{public}d", - pipeInfo.name_.c_str(), pipeInfo.moduleName_.c_str(), deviceType); + pipeInfo->name_.c_str(), pipeInfo->paProp_.moduleName_.c_str(), deviceType); return SUCCESS; } @@ -433,13 +435,12 @@ void AudioEcManager::UpdateAudioEcInfo(const AudioDeviceDescriptor &inputDevice, audioEcInfo_.ecType = GetEcType(inputDevice.deviceType_, outputDevice.deviceType_); audioEcInfo_.ecInputAdapter = GetHalNameForDevice(ROLE_SOURCE, inputDevice.deviceType_); audioEcInfo_.ecOutputAdapter = GetHalNameForDevice(ROLE_SINK, outputDevice.deviceType_); - PipeInfo pipeInfo; + std::shared_ptr pipeInfo; int32_t result = GetPipeInfoByDeviceTypeForEc(ROLE_SINK, outputDevice.deviceType_, pipeInfo); CHECK_AND_RETURN_LOG(result == SUCCESS, "Ec stream not update for no pipe found"); - audioEcInfo_.pipeInfo = pipeInfo; - audioEcInfo_.samplingRate = GetEcSamplingRate(audioEcInfo_.ecOutputAdapter, pipeInfo.streamPropInfos_.front()); - audioEcInfo_.format = GetEcFormat(audioEcInfo_.ecOutputAdapter, pipeInfo.streamPropInfos_.front()); - audioEcInfo_.channels = GetEcChannels(audioEcInfo_.ecOutputAdapter, pipeInfo.streamPropInfos_.front()); + audioEcInfo_.samplingRate = GetEcSamplingRate(audioEcInfo_.ecOutputAdapter, pipeInfo->streamPropInfos_.front()); + audioEcInfo_.format = GetEcFormat(audioEcInfo_.ecOutputAdapter, pipeInfo->streamPropInfos_.front()); + audioEcInfo_.channels = GetEcChannels(audioEcInfo_.ecOutputAdapter, pipeInfo->streamPropInfos_.front()); AUDIO_INFO_LOG("inputDevice: %{public}d, outputDevice: %{public}d, ecType: %{public}d, ecInputAdapter: %{public}s" "ecOutputAdapter: %{public}s, samplingRate: %{public}s, format: %{public}s, channels: %{public}s", audioEcInfo_.inputDevice.deviceType_, audioEcInfo_.outputDevice.deviceType_, audioEcInfo_.ecType, @@ -622,7 +623,7 @@ void AudioEcManager::ReloadSourceForSession(SessionInfo sessionInfo) { AUDIO_INFO_LOG("reload source for session"); - StreamPropInfo targetInfo; + PipeStreamPropInfo targetInfo; SourceType targetSource = sessionInfo.sourceType; int32_t res = FetchTargetInfoForSessionAdd(sessionInfo, targetInfo, targetSource); CHECK_AND_RETURN_LOG(res == SUCCESS, "fetch target source info error"); @@ -634,14 +635,14 @@ void AudioEcManager::ReloadSourceForSession(SessionInfo sessionInfo) DeviceFlag::INPUT_DEVICES_FLAG); } -int32_t AudioEcManager::FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo, StreamPropInfo &targetInfo, +int32_t AudioEcManager::FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo, PipeStreamPropInfo &targetInfo, SourceType &targetSourceType) { - const PipeInfo *pipeInfoPtr = nullptr; - AudioAdapterInfo adapterInfo; - bool ret = audioConfigManager_.GetAdapterInfoByType(AdaptersType::TYPE_PRIMARY, adapterInfo); + std::shared_ptr pipeInfoPtr = nullptr; + std::shared_ptr adapterInfo = nullptr; + bool ret = audioConfigManager_.GetAdapterInfoByType(AudioAdapterType::TYPE_PRIMARY, adapterInfo); if (ret) { - pipeInfoPtr = adapterInfo.GetPipeByName(PIPE_PRIMARY_INPUT); + pipeInfoPtr = adapterInfo->GetPipeInfoByName(PIPE_PRIMARY_INPUT); } CHECK_AND_RETURN_RET_LOG(pipeInfoPtr != nullptr, ERROR, "pipeInfoPtr is null"); @@ -653,37 +654,37 @@ int32_t AudioEcManager::FetchTargetInfoForSessionAdd(const SessionInfo sessionIn } // use first profile as default - StreamPropInfo targetStreamPropInfo = *streamPropInfoList.begin(); + std::shared_ptr targetStreamPropInfo = *streamPropInfoList.begin(); bool useMatchingPropInfo = false; GetTargetSourceTypeAndMatchingFlag(sessionInfo.sourceType, targetSourceType, useMatchingPropInfo); if (useMatchingPropInfo) { for (const auto &streamPropInfo : streamPropInfoList) { - if (sessionInfo.channels == streamPropInfo.channelLayout_ - && sessionInfo.rate == streamPropInfo.sampleRate_) { + if (sessionInfo.channels == streamPropInfo->channels_ && + sessionInfo.rate == streamPropInfo->sampleRate_) { targetStreamPropInfo = streamPropInfo; break; } } } - targetInfo = targetStreamPropInfo; + targetInfo = *targetStreamPropInfo; if (isEcFeatureEnable_) { std::shared_ptr inputDesc = audioRouterCenter_.FetchInputDevice(targetSourceType, -1); if (inputDesc != nullptr && inputDesc->deviceType_ != DEVICE_TYPE_MIC && targetInfo.channelLayout_ == PC_MIC_CHANNEL_NUM) { // only built-in mic can use 4 channel, update later by using xml to describe - targetInfo.channelLayout_ = HEADPHONE_CHANNEL_NUM; + targetInfo.channels_ = static_cast(HEADPHONE_CHANNEL_NUM); + targetInfo.channelLayout_ = CH_LAYOUT_STEREO; } } #ifndef IS_EMULATOR // need change to use profile for all devices later if (primaryMicModuleInfo_.OpenMicSpeaker == "1") { - uint32_t sampleFormatBits = AudioPolicyUtils::GetInstance().PcmFormatToBytes( - static_cast(formatFromParserStrToEnum[targetInfo.format_])); + uint32_t sampleFormatBits = AudioPolicyUtils::GetInstance().PcmFormatToBytes(targetInfo.format_); targetInfo.bufferSize_ = BUFFER_CALC_20MS * targetInfo.sampleRate_ / static_cast(MS_PER_S) - * targetInfo.channelLayout_ * sampleFormatBits; + * targetInfo.channels_ * sampleFormatBits; } #endif @@ -730,11 +731,11 @@ std::string AudioEcManager::GetHalNameForDevice(const std::string &role, const D } else { portName = AudioPolicyUtils::GetInstance().GetSinkPortName(deviceType); } - AudioAdapterInfo info; - bool ret = audioConfigManager_.GetAdapterInfoByType(static_cast( + std::shared_ptr info; + bool ret = audioConfigManager_.GetAdapterInfoByType(static_cast( AudioPolicyUtils::portStrToEnum[portName]), info); if (ret) { - halName = info.adapterName_; + halName = info->adapterName; } AUDIO_INFO_LOG("role: %{public}s, device: %{public}d, halName: %{public}s", role.c_str(), deviceType, halName.c_str()); diff --git a/services/audio_policy/server/src/service/service/audio_iohandle_map.cpp b/services/audio_policy/server/src/service/service/audio_iohandle_map.cpp index 532a4ccbfd76aa7cfd53b38c6746b884534213c0..031bb6aa6f4326ea7e8e5d24681dddc004541d25 100644 --- a/services/audio_policy/server/src/service/service/audio_iohandle_map.cpp +++ b/services/audio_policy/server/src/service/service/audio_iohandle_map.cpp @@ -23,6 +23,7 @@ #include "audio_server_proxy.h" #include "audio_policy_async_action_handler.h" +#include "audio_pipe_manager.h" namespace OHOS { namespace AudioStandard { @@ -175,10 +176,28 @@ AudioIOHandle AudioIOHandleMap::GetSourceIOHandle(DeviceType deviceType) int32_t AudioIOHandleMap::OpenPortAndInsertIOHandle(const std::string &moduleName, const AudioModuleInfo &moduleInfo) { - AudioIOHandle ioHandle = AudioPolicyManagerFactory::GetAudioPolicyManager().OpenAudioPort(moduleInfo); + AUDIO_INFO_LOG("In, name: %{public}s", moduleName.c_str()); + uint32_t paIndex = 0; + AudioIOHandle ioHandle = AudioPolicyManagerFactory::GetAudioPolicyManager().OpenAudioPort(moduleInfo, paIndex); CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_INVALID_HANDLE, "OpenAudioPort failed %{public}d", ioHandle); + std::shared_ptr pipeInfo_ = std::make_shared(); + pipeInfo_->id_ = ioHandle; + pipeInfo_->paIndex_ = paIndex; + if (moduleInfo.role == "sink") { + pipeInfo_->pipeRole_ = PIPE_ROLE_OUTPUT; + pipeInfo_->routeFlag_ = AUDIO_OUTPUT_FLAG_NORMAL; + } else { + pipeInfo_->pipeRole_ = PIPE_ROLE_INPUT; + pipeInfo_->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL; + } + pipeInfo_->adapterName_ = moduleInfo.adapterName; + pipeInfo_->moduleInfo_ = moduleInfo; + pipeInfo_->pipeAction_ = PIPE_ACTION_DEFAULT; + + AudioPipeManager::GetPipeManager()->AddAudioPipeInfo(pipeInfo_); + AddIOHandleInfo(moduleName, ioHandle); return SUCCESS; } @@ -190,8 +209,13 @@ int32_t AudioIOHandleMap::ClosePortAndEraseIOHandle(const std::string &moduleNam "can not find %{public}s in io map", moduleName.c_str()); DelIOHandleInfo(moduleName); - AUDIO_INFO_LOG("[close-module] %{public}s,id:%{public}d", moduleName.c_str(), ioHandle); - int32_t result = AudioPolicyManagerFactory::GetAudioPolicyManager().CloseAudioPort(ioHandle, isSync); + std::shared_ptr pipeManager = AudioPipeManager::GetPipeManager(); + uint32_t paIndex = pipeManager->GetPaIndexByIoHandle(ioHandle); + pipeManager->RemoveAudioPipeInfo(ioHandle); + + AUDIO_INFO_LOG("[close-module] %{public}s, id:%{public}d, paIndex: %{public}u", + moduleName.c_str(), ioHandle, paIndex); + int32_t result = AudioPolicyManagerFactory::GetAudioPolicyManager().CloseAudioPort(ioHandle, paIndex, isSync); CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "CloseAudioPort failed %{public}d", result); return SUCCESS; } diff --git a/services/audio_policy/server/src/service/service/audio_offload_stream.cpp b/services/audio_policy/server/src/service/service/audio_offload_stream.cpp index 1f783b55b84143d2256d81bfc1be3be6405cf242..ff5bb912cd8cbf01afa237d48ff2d31f30164a76 100644 --- a/services/audio_policy/server/src/service/service/audio_offload_stream.cpp +++ b/services/audio_policy/server/src/service/service/audio_offload_stream.cpp @@ -66,13 +66,7 @@ void AudioOffloadStream::HandlePowerStateChanged(PowerMgr::PowerState state) void AudioOffloadStream::SetOffloadAvailableFromXML(AudioModuleInfo &moduleInfo) { - if (moduleInfo.name == "Speaker") { - for (const auto &portInfo : moduleInfo.ports) { - if ((portInfo.adapterName == "primary") && (portInfo.offloadEnable == "1")) { - isOffloadAvailable_ = true; - } - } - } + isOffloadAvailable_ = true; } bool AudioOffloadStream::GetOffloadAvailableFromXml() const @@ -104,15 +98,7 @@ void AudioOffloadStream::OffloadStreamSetCheck(uint32_t sessionId) std::string curOutputNetworkId = audioActiveDevice_.GetCurrentOutputDeviceNetworkId(); std::string curOutputMacAddr = audioActiveDevice_.GetCurrentOutputDeviceMacAddr(); DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType(); - ret = streamCollector_.GetRendererDeviceInfo(sessionId, deviceInfo); - if (ret != SUCCESS || curOutputNetworkId != LOCAL_NETWORK_ID || - curOutputDeviceType == DEVICE_TYPE_REMOTE_CAST || - deviceInfo.deviceType_ != curOutputDeviceType || - deviceInfo.networkId_ != curOutputNetworkId || - deviceInfo.macAddress_ != curOutputMacAddr) { - AUDIO_INFO_LOG("sessionId[%{public}d] not fetch device, Offload Skipped", sessionId); - return; - } + streamCollector_.GetRendererDeviceInfo(sessionId, deviceInfo); AudioStreamType streamType = streamCollector_.GetStreamType(sessionId); if (!CheckStreamOffloadMode(sessionId, streamType)) { @@ -161,11 +147,6 @@ bool AudioOffloadStream::CheckStreamOffloadMode(int64_t activateSessionId, Audio return false; } - if (!streamCollector_.IsOffloadAllowed(activateSessionId)) { - AUDIO_PRERELEASE_LOGI("Offload is not allowed, Skipped"); - return false; - } - if ((streamType != STREAM_MUSIC) && (streamType != STREAM_SPEECH)) { AUDIO_DEBUG_LOG("StreamType not allowed get offload mode, Skipped"); return false; @@ -306,15 +287,7 @@ int32_t AudioOffloadStream::MoveToNewPipeInner(uint32_t sessionId, AudioPipeType void AudioOffloadStream::ResetOffloadMode(int32_t sessionId) { - AUDIO_DEBUG_LOG("Doing reset offload mode!"); - - if (!audioActiveDevice_.CheckActiveOutputDeviceSupportOffload()) { - AUDIO_DEBUG_LOG("Resetting offload not available on this output device! Release."); - OffloadStreamReleaseCheck(*offloadSessionID_); - return; - } - - OffloadStreamSetCheck(sessionId); + AUDIO_INFO_LOG("No need to reset offload mode! SKIPPED"); } void AudioOffloadStream::OffloadStreamReleaseCheck(uint32_t sessionId) diff --git a/services/audio_policy/server/src/service/service/audio_policy_dump.cpp b/services/audio_policy/server/src/service/service/audio_policy_dump.cpp index 7d4474d89c6b3a3877ef6da8f050b1c52e67ad21..475c18783d531e3767be9bfbe864ba39b83d8e86 100644 --- a/services/audio_policy/server/src/service/service/audio_policy_dump.cpp +++ b/services/audio_policy/server/src/service/service/audio_policy_dump.cpp @@ -340,32 +340,60 @@ void AudioPolicyDump::GetGroupInfoDump(std::string &dumpString) dumpString += "\n"; } -void AudioPolicyDump::AudioPolicyParserDumpInner(std::string &dumpString, - const std::unordered_map& adapterInfoMap, - const std::unordered_map& volumeGroupData, - std::unordered_map& interruptGroupData, - GlobalConfigs globalConfigs) +void AudioPolicyDump::AudioPolicyParserDumpAdapterInfo(std::string &dumpString, + std::unordered_map>& adapterInfoMap) { for (auto &[adapterType, adapterInfo] : adapterInfoMap) { - AppendFormat(dumpString, " - adapter : %s -- adapterType:%u\n", adapterInfo.adapterName_.c_str(), adapterType); - for (auto &deviceInfo : adapterInfo.deviceInfos_) { - AppendFormat(dumpString, " - device -- name:%s, pin:%s, type:%s, role:%s\n", deviceInfo.name_.c_str(), - deviceInfo.pin_.c_str(), deviceInfo.type_.c_str(), deviceInfo.role_.c_str()); + AppendFormat(dumpString, " - adapter : %s -- adapterType=%u, supportSelectScene=%s\n", + adapterInfo->adapterName.c_str(), adapterType, adapterInfo->adapterSupportScene.c_str()); + AudioPolicyParserDumpPipeInfo(dumpString, adapterInfo); + + for (auto &deviceInfo : adapterInfo->deviceInfos) { + AppendFormat(dumpString, " - device : %s -- type=%u, pin=%u, role=%u\n", + deviceInfo->name_.c_str(), deviceInfo->type_, deviceInfo->pin_, deviceInfo->role_); + AppendFormat(dumpString, " - support pipe | "); + for (auto pipeIt : deviceInfo->supportPipeMap_) { + AppendFormat(dumpString, "%s,", pipeIt.second->name_.c_str()); + } + AppendFormat(dumpString, "\n"); } - for (auto &pipeInfo : adapterInfo.pipeInfos_) { - AppendFormat(dumpString, " - module : -- name:%s, pipeRole:%s, pipeFlags:%s, lib:%s, paPropRole:%s, " - "fixedLatency:%s, renderInIdleState:%s\n", pipeInfo.name_.c_str(), - pipeInfo.pipeRole_.c_str(), pipeInfo.pipeFlags_.c_str(), pipeInfo.lib_.c_str(), - pipeInfo.paPropRole_.c_str(), pipeInfo.fixedLatency_.c_str(), pipeInfo.renderInIdleState_.c_str()); - - for (auto &configInfo : pipeInfo.configInfos_) { - AppendFormat(dumpString, " - config : -- name:%s, value:%s\n", configInfo.name_.c_str(), - configInfo.value_.c_str()); + } +} + +void AudioPolicyDump::AudioPolicyParserDumpPipeInfo(std::string &dumpString, + std::shared_ptr &adapterInfo) +{ + for (auto &pipeInfo : adapterInfo->pipeInfos) { + AppendFormat(dumpString, " -pipeInfo : %s -- role=%u, supportFlags=0x%x, lib=%s, " + "paPropRole=%s, fixedLatency=%s, renderInIdleState=%s\n", pipeInfo->name_.c_str(), + pipeInfo->role_, pipeInfo->supportFlags_, pipeInfo->paProp_.lib_.c_str(), + pipeInfo->paProp_.role_.c_str(), pipeInfo->paProp_.fixedLatency_.c_str(), + pipeInfo->paProp_.renderInIdleState_.c_str()); + + for (auto &streamProp : pipeInfo->streamPropInfos_) { + AppendFormat(dumpString, " - streamProp : -- format=%zu, sampleRates=%zu, channelLayout=%zu," + " channels=%zu, bufferSize=%zu\n", streamProp->format_, streamProp->sampleRate_, + streamProp->channelLayout_, streamProp->channels_, streamProp->bufferSize_); + AppendFormat(dumpString, " - support device | "); + for (auto deviceIt : streamProp->supportDeviceMap_) { + AppendFormat(dumpString, "%s,", deviceIt.second->name_.c_str()); } + AppendFormat(dumpString, "\n"); + } + + for (auto &attributeInfo : pipeInfo->attributeInfos_) { + AppendFormat(dumpString, " - attribute : -- name=%s, value=%s\n", attributeInfo->name_.c_str(), + attributeInfo->value_.c_str()); } } +} + +void AudioPolicyDump::AudioPolicyParserDumpInner(std::string &dumpString, + const std::unordered_map& volumeGroupData, + std::unordered_map& interruptGroupData, PolicyGlobalConfigs globalConfigs) +{ for (auto& volume : volumeGroupData) { - AppendFormat(dumpString, " - volumeGroupMap_ first:%s, second:%s\n\n", volume.first.c_str(), + AppendFormat(dumpString, " - volumeGroupMap_ first:%s, second:%s\n", volume.first.c_str(), volume.second.c_str()); } for (auto& interrupt : interruptGroupData) { @@ -378,13 +406,9 @@ void AudioPolicyDump::AudioPolicyParserDumpInner(std::string &dumpString, globalConfigs.updateRouteSupport_, globalConfigs.globalPaConfigs_.audioLatency_.c_str(), globalConfigs.globalPaConfigs_.sinkLatency_.c_str()); - for (auto &outputConfig : globalConfigs.outputConfigInfos_) { - AppendFormat(dumpString, " - output config name:%s, type:%s, value:%s\n", outputConfig.name_.c_str(), - outputConfig.type_.c_str(), outputConfig.value_.c_str()); - } - for (auto &inputConfig : globalConfigs.inputConfigInfos_) { - AppendFormat(dumpString, " - input config name:%s, type_%s, value:%s\n\n", inputConfig.name_.c_str(), - inputConfig.type_.c_str(), inputConfig.value_.c_str()); + for (auto &commonConfig : globalConfigs.commonConfigs_) { + AppendFormat(dumpString, " - common config name:%s, type:%s, value:%s\n", commonConfig.name_.c_str(), + commonConfig.type_.c_str(), commonConfig.value_.c_str()); } AppendFormat(dumpString, " - module curActiveCount:%d\n\n", audioPolicyManager_.GetCurActivateCount()); } @@ -392,17 +416,18 @@ void AudioPolicyDump::AudioPolicyParserDumpInner(std::string &dumpString, void AudioPolicyDump::AudioPolicyParserDump(std::string &dumpString) { dumpString += "\nAudioPolicyParser:\n"; - std::unordered_map adapterInfoMap; + std::unordered_map> adapterInfoMap; std::unordered_map volumeGroupData; std::unordered_map interruptGroupData; - GlobalConfigs globalConfigs; + PolicyGlobalConfigs globalConfigs; audioConfigManager_.GetAudioAdapterInfos(adapterInfoMap); audioConfigManager_.GetVolumeGroupData(volumeGroupData); audioConfigManager_.GetInterruptGroupData(interruptGroupData); audioConfigManager_.GetGlobalConfigs(globalConfigs); - AudioPolicyParserDumpInner(dumpString, adapterInfoMap, volumeGroupData, interruptGroupData, globalConfigs); + AudioPolicyParserDumpAdapterInfo(dumpString, adapterInfoMap); + AudioPolicyParserDumpInner(dumpString, volumeGroupData, interruptGroupData, globalConfigs); } void AudioPolicyDump::AudioStreamDump(std::string &dumpString) @@ -525,7 +550,7 @@ void AudioPolicyDump::EffectManagerInfoDump(string &dumpString) int32_t count = 0; GetEffectManagerInfo(); - std::unordered_map adapterInfoMap; + std::unordered_map> adapterInfoMap; audioConfigManager_.GetAudioAdapterInfos(adapterInfoMap); dumpString += "==== Audio Effect Manager INFO ====\n"; diff --git a/services/audio_policy/server/src/service/service/audio_policy_utils.cpp b/services/audio_policy/server/src/service/service/audio_policy_utils.cpp index da61436da537188896119760709a8b9a55709d79..614e3864e23bad597e2029e3ef75dd32ac4208e6 100644 --- a/services/audio_policy/server/src/service/service/audio_policy_utils.cpp +++ b/services/audio_policy/server/src/service/service/audio_policy_utils.cpp @@ -293,6 +293,17 @@ std::string AudioPolicyUtils::GetSinkName(const AudioDeviceDescriptor &desc, int } } +std::string AudioPolicyUtils::GetSinkName(std::shared_ptr desc, int32_t sessionId) +{ + if (desc->networkId_ == LOCAL_NETWORK_ID) { + AudioPipeType pipeType = PIPE_TYPE_UNKNOWN; + streamCollector_.GetPipeType(sessionId, pipeType); + return GetSinkPortName(desc->deviceType_, pipeType); + } else { + return GetRemoteModuleName(desc->networkId_, desc->deviceRole_); + } +} + std::string AudioPolicyUtils::GetSourcePortName(DeviceType deviceType) { std::string portName = PORT_NONE; @@ -496,9 +507,11 @@ AudioModuleInfo AudioPolicyUtils::ConstructRemoteAudioModuleInfo(std::string net audioModuleInfo.format = "s16le"; // 16bit little endian audioModuleInfo.fixedLatency = "1"; // here we need to set latency fixed for a fixed buffer size. audioModuleInfo.renderInIdleState = "1"; + audioModuleInfo.role = "sink"; } else if (deviceRole == DeviceRole::INPUT_DEVICE) { audioModuleInfo.lib = "libmodule-hdi-source.z.so"; audioModuleInfo.format = "s16le"; // we assume it is bigger endian + audioModuleInfo.role = "source"; } else { AUDIO_WARNING_LOG("Invalid flag provided %{public}d", static_cast(deviceType)); } diff --git a/services/audio_policy/server/src/service/service/audio_recovery_device.cpp b/services/audio_policy/server/src/service/service/audio_recovery_device.cpp index 7a3db25e6f7066bfa03065959ddfb74bcc99d6e8..f0092fe1da8761aedf36ad8990d0c766beba8706 100644 --- a/services/audio_policy/server/src/service/service/audio_recovery_device.cpp +++ b/services/audio_policy/server/src/service/service/audio_recovery_device.cpp @@ -23,6 +23,7 @@ #include "audio_server_proxy.h" #include "audio_policy_utils.h" +#include "audio_core_service.h" namespace OHOS { namespace AudioStandard { @@ -223,8 +224,8 @@ int32_t AudioRecoveryDevice::SelectOutputDevice(sptr audioR void AudioRecoveryDevice::HandleFetchDeviceChange(const AudioStreamDeviceChangeReason &reason, const std::string &caller) { - audioDeviceCommon_.FetchDevice(true, reason); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute(reason); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); auto currentInputDevice = audioActiveDevice_.GetCurrentInputDevice(); auto currentOutputDevice = audioActiveDevice_.GetCurrentOutputDevice(); audioCapturerSession_.ReloadSourceForDeviceChange( @@ -247,7 +248,7 @@ int32_t AudioRecoveryDevice::SelectOutputDeviceForFastInner(sptrFetchOutputDeviceAndRoute(AudioStreamDeviceChangeReason::OVERRODE); return true; } @@ -383,7 +384,7 @@ int32_t AudioRecoveryDevice::SelectInputDevice(sptr audioCa "AddFastRouteMapInfo failed! fastRouteMap is too large!"); AUDIO_INFO_LOG("Success for uid[%{public}d] device[%{public}s]", audioCapturerFilter->uid, GetEncryptStr(selectedDesc[0]->networkId_).c_str()); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); audioCapturerSession_.ReloadSourceForDeviceChange( audioActiveDevice_.GetCurrentInputDevice(), audioActiveDevice_.GetCurrentOutputDevice(), "SelectInputDevice fast"); @@ -398,7 +399,7 @@ int32_t AudioRecoveryDevice::SelectInputDevice(sptr audioCa AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_RECORD_CAPTURE, selectedDesc[0]); } audioActiveDevice_.DisconnectScoWhenUserSelectInput(selectedDesc[0]); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); audioDeviceCommon_.OnPreferredInputDeviceUpdated(audioActiveDevice_.GetCurrentInputDeviceType(), audioActiveDevice_.GetCurrentInputDevice().networkId_); @@ -442,8 +443,8 @@ int32_t AudioRecoveryDevice::ExcludeOutputDevices(AudioDeviceUsage audioDevUsage WriteExcludeOutputSysEvents(audioDevUsage, desc); } - audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute(AudioStreamDeviceChangeReason::OVERRODE); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); AudioDeviceDescriptor currentOutputDevice = audioActiveDevice_.GetCurrentOutputDevice(); AudioDeviceDescriptor currentInputDevice = audioActiveDevice_.GetCurrentInputDevice(); audioCapturerSession_.ReloadSourceForDeviceChange( @@ -469,8 +470,8 @@ int32_t AudioRecoveryDevice::UnexcludeOutputDevices(AudioDeviceUsage audioDevUsa int32_t ret = UnexcludeOutputDevicesInner(audioDevUsage, audioDeviceDescriptors); CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Unexclude devices failed"); - audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE); - audioDeviceCommon_.FetchDevice(false); + AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute(AudioStreamDeviceChangeReason::OVERRODE); + AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute(); AudioDeviceDescriptor currentOutputDevice = audioActiveDevice_.GetCurrentOutputDevice(); AudioDeviceDescriptor currentInputDevice = audioActiveDevice_.GetCurrentInputDevice(); audioCapturerSession_.ReloadSourceForDeviceChange( diff --git a/services/audio_policy/server/src/service/service/audio_server_proxy.cpp b/services/audio_policy/server/src/service/service/audio_server_proxy.cpp index 5703272f1968f524ed717c38e22e4b548dce6358..e2e23b0e890c5d47f9352e7e25d4dd6db8dc8b7d 100644 --- a/services/audio_policy/server/src/service/service/audio_server_proxy.cpp +++ b/services/audio_policy/server/src/service/service/audio_server_proxy.cpp @@ -391,6 +391,16 @@ int32_t AudioServerProxy::RegiestPolicyProviderProxy(const sptr & return ret; } +int32_t AudioServerProxy::RegistCoreServiceProviderProxy(const sptr &object) +{ + const sptr gsp = GetAudioServerProxy(); + CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_INVALID_HANDLE, "Service proxy unavailable"); + std::string identity = IPCSkeleton::ResetCallingIdentity(); + int32_t ret = gsp->RegistCoreServiceProvider(object); + IPCSkeleton::SetCallingIdentity(identity); + return ret; +} + void AudioServerProxy::SetParameterCallbackProxy(const sptr& object) { const sptr gsp = GetAudioServerProxy(); @@ -517,6 +527,37 @@ void AudioServerProxy::UnloadHdiAdapterProxy(uint32_t devMgrType, const std::str IPCSkeleton::SetCallingIdentity(identity); } +uint32_t AudioServerProxy::CreateHdiSinkPortProxy(const std::string &deviceClass, const std::string &idInfo, + const IAudioSinkAttr &attr) +{ + const sptr gsp = GetAudioServerProxy(); + CHECK_AND_RETURN_RET_LOG(gsp != nullptr, HDI_INVALID_ID, "Service proxy unavailable"); + std::string identity = IPCSkeleton::ResetCallingIdentity(); + uint32_t res = gsp->CreateHdiSinkPort(deviceClass, idInfo, attr); + IPCSkeleton::SetCallingIdentity(identity); + return res; +} + +uint32_t AudioServerProxy::CreateHdiSourcePortProxy(const std::string &deviceClass, const std::string &idInfo, + const IAudioSourceAttr &attr) +{ + const sptr gsp = GetAudioServerProxy(); + CHECK_AND_RETURN_RET_LOG(gsp != nullptr, HDI_INVALID_ID, "Service proxy unavailable"); + std::string identity = IPCSkeleton::ResetCallingIdentity(); + uint32_t res = gsp->CreateHdiSourcePort(deviceClass, idInfo, attr); + IPCSkeleton::SetCallingIdentity(identity); + return res; +} + +void AudioServerProxy::DestroyHdiPortProxy(uint32_t id) +{ + const sptr gsp = GetAudioServerProxy(); + CHECK_AND_RETURN_LOG(gsp != nullptr, "Service proxy unavailable"); + std::string identity = IPCSkeleton::ResetCallingIdentity(); + gsp->DestroyHdiPort(id); + IPCSkeleton::SetCallingIdentity(identity); +} + void AudioServerProxy::SetDeviceConnectedFlag(bool flag) { const sptr gsp = GetAudioServerProxy(); diff --git a/services/audio_policy/services/core/config/src/audio_policy_config_manager.cpp b/services/audio_policy/services/core/config/src/audio_policy_config_manager.cpp index dc9c10bbdf125cf318e170824cb64e5dfbe61a39..53e5604b8f692e666e09b4bc4ce23df8ec90afc6 100644 --- a/services/audio_policy/services/core/config/src/audio_policy_config_manager.cpp +++ b/services/audio_policy/services/core/config/src/audio_policy_config_manager.cpp @@ -48,7 +48,7 @@ bool AudioPolicyConfigManager::Init() void AudioPolicyConfigManager::OnAudioPolicyConfigXmlParsingCompleted() { - AUDIO_INFO_LOG("AdapterInfo num [%{public}zu]", audioPolicyCOnfig_.adapterInfoMap.size()); + AUDIO_INFO_LOG("AdapterInfo num [%{public}zu]", audioPolicyConfig_.adapterInfoMap.size()); CHECK_AND_RETURN_LOG(!audioPolicyConfig_.adapterInfoMap.empty(), "Parse audio policy xml failed, received data is empty"); @@ -331,9 +331,9 @@ void AudioPolicyConfigManager::GetStreamPropInfo(std::shared_ptr &info) { auto newDeviceDesc = desc->newDeviceDescs_.front(); - std::shared_ptr deviceInfo = audioPolicyConfig_.GetDeviceInfo( + std::shared_ptr deviceInfo = audioPolicyConfig_.GetAdapterDeviceInfo( newDeviceDesc->deviceType_, newDeviceDesc->deviceRole_, newDeviceDesc->networkId_, desc->audioFlag_); - CHECK_AND_RETURN_LOG(deviceInfo != nullptr, flag, "Find device failed;none streamProp"); + CHECK_AND_RETURN_LOG(deviceInfo != nullptr, "Find device failed, none streamProp"); auto pipeIt = deviceInfo->supportPipeMap_.find(desc->routeFlag_); CHECK_AND_RETURN_LOG(pipeIt != deviceInfo->supportPipeMap_.end(), "Find pipeInfo failed;none streamProp"); @@ -345,12 +345,9 @@ void AudioPolicyConfigManager::GetStreamPropInfo(std::shared_ptrsecond, desc->streamInfo_.format, - desc->streamInfo_.sampleRate, tempChannel); + desc->streamInfo_.samplingRate, tempChannel); if (streamProp != nullptr) { info = streamProp; - AUDIO_INFO_LOG("format:%{public}u, sampleRate:%{public}u, channelLayout:%{public}u, channels:%{public}u," - " desc channels:%{public}u", info->format_, info->sampleRate_, info->channelLayout_, info->channels_, - tempChannel); return; } @@ -365,12 +362,9 @@ void AudioPolicyConfigManager::GetStreamPropInfo(std::shared_ptrrouteFlag_ = desc->audioMode_ == AUDIO_MODE_PLAYBACK ? AUDIO_OUTPUT_FLAG_NORMAL : AUDIO_INPUT_FLAG_NORMAL; auto streamProp = GetStreamPropInfoFromPipe(pipeIt->second, desc->streamInfo_.format, - desc->streamInfo_.sampleRate, desc->streamInfo_.channels); + desc->streamInfo_.samplingRate, desc->streamInfo_.channels); if (streamProp != nullptr) { info = streamProp; - AUDIO_INFO_LOG("format:%{public}u, sampleRate:%{public}u, channelLayout:%{public}u, " - "channels:%{public}u, desc channels:%{public}u", info->format_, info->sampleRate_, - info->channelLayout_, info->channels_, desc->streamInfo_.channels); return; } } @@ -379,8 +373,6 @@ void AudioPolicyConfigManager::GetStreamPropInfo(std::shared_ptrsecond->streamPropInfos_.empty()) { info = pipeIt->second->streamPropInfos_.front(); } // if not match, choose first? - AUDIO_INFO_LOG("format:%{public}u, sampleRate:%{public}u, channelLayout:%{public}lu, channels:%{public}u", - info->format_, info->sampleRate_, info->channelLayout_, info->channels_, desc->streamInfo_.channels); } std::shared_ptr AudioPolicyConfigManager::GetStreamPropInfoFromPipe( @@ -406,8 +398,7 @@ bool AudioPolicyConfigManager::SupportImplicitConversion(uint32_t routeFlag) (routeFlag & AUDIO_INPUT_FLAG_WAKEUP)) { return true; } - return false + return false; } - } } diff --git a/services/audio_policy/services/core/include/audio_core_service.h b/services/audio_policy/services/core/include/audio_core_service.h new file mode 100644 index 0000000000000000000000000000000000000000..5be5337db2904ad5f3c4433bdd5df0b337aba4d3 --- /dev/null +++ b/services/audio_policy/services/core/include/audio_core_service.h @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef AUDIO_CORE_SERVICE_H +#define AUDIO_CORE_SERVICE_H +#include + +#include "audio_policy_server_handler.h" +#include "i_core_service_provider.h" +#include "idevice_status_observer.h" +#include "audio_stream_descriptor.h" +#include "audio_device_descriptor.h" +#include "audio_info.h" +#include "microphone_descriptor.h" +#include "audio_stream_change_info.h" +#include "audio_active_device.h" +#include "audio_scene_manager.h" +#include "audio_volume_manager.h" +#include "audio_capturer_session.h" +#include "audio_device_manager.h" +#include "audio_connected_device.h" +#include "audio_device_status.h" +#include "audio_effect_service.h" +#include "audio_microphone_descriptor.h" +#include "audio_recovery_device.h" +#include "device_status_listener.h" +#include "core_service_provider_stub.h" +#include "audio_pipe_info.h" +#include "audio_service_enum.h" +#include "audio_pipe_manager.h" +#include "audio_pipe_selector.h" +#include "audio_policy_config_manager.h" +namespace OHOS { +namespace AudioStandard { +class AudioA2dpOffloadManager; +class AudioCoreService : public enable_shared_from_this { +public: + class EventEntry : public ICoreServiceProvider, public IDeviceStatusObserver { + public: + EventEntry(std::shared_ptr coreService); + void RegistCoreService(); + + // Stream operations + int32_t CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId); + int32_t CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId); + + // ICoreServiceProvider + int32_t UpdateSessionOperation(uint32_t sessionId, SessionOperation operation) override; + int32_t SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionId, + const StreamUsage streamUsage, bool isRunning) override; + std::string GetAdapterNameBySessionId(uint32_t sessionId) override; + int32_t GetProcessDeviceInfoBySessionId(uint32_t sessionId, AudioDeviceDescriptor &deviceInfo) override; + uint32_t GenerateSessionId() override; + + // IDeviceStatusObserver + void OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command) override; + void OnDeviceStatusUpdated(DeviceType devType, bool isConnected, + const std::string &macAddress, const std::string &deviceName, + const AudioStreamInfo &streamInfo, DeviceRole role = DEVICE_ROLE_NONE, bool hasPair = false) override; + void OnDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected) override; + void OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop = false) override; + void OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status) override; + void OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected) override; + void OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress, + const std::string &deviceName, const AudioStreamInfo &streamInfo) override; + void OnServiceConnected(AudioServiceIndex serviceIndex) override; + void OnServiceDisconnected(AudioServiceIndex serviceIndex) override; + void OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress) override; + + // Functions related to assignment operations - device related + int32_t SetAudioScene(AudioScene audioScene); + std::vector> GetDevices(DeviceFlag deviceFlag); + int32_t SetDeviceActive(InternalDeviceType deviceType, bool active, const int32_t pid); + int32_t SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address); + int32_t RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, + const sptr &object, const int32_t apiVersion); + int32_t UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo); + void RegisteredTrackerClientDied(pid_t uid); + bool ConnectServiceAdapter(); + void OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName); + int32_t SelectOutputDevice(sptr audioRendererFilter, + std::vector> selectedDesc); + int32_t SelectInputDevice(sptr audioCapturerFilter, + std::vector> selectedDesc); + void NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value); + int32_t OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo, AudioStreamInfo streamInfo); + void OnCapturerSessionRemoved(uint64_t sessionID); + void SetDisplayName(const std::string &deviceName, bool isLocalDevice); + int32_t TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason); + void FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo, + const AudioStreamDeviceChangeReasonExt reason); + void FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo); + int32_t ExcludeOutputDevices(AudioDeviceUsage audioDevUsage, + std::vector> &audioDeviceDescriptors); + int32_t UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage, + std::vector> &audioDeviceDescriptors); + + // Functions related to get operations - device related + bool IsArmUsbDevice(const AudioDeviceDescriptor &deviceDesc); + std::vector> GetPreferredOutputDeviceDescriptors( + AudioRendererInfo &rendererInfo, std::string networkId = LOCAL_NETWORK_ID); + std::vector> GetPreferredInputDeviceDescriptors( + AudioCapturerInfo &captureInfo, std::string networkId = LOCAL_NETWORK_ID); + std::shared_ptr GetActiveBluetoothDevice(); + std::vector> GetAvailableDevices(AudioDeviceUsage usage); + std::vector> GetAvailableMicrophones(); + std::vector> GetAudioCapturerMicrophoneDescriptors(int32_t sessionId); + int32_t GetCurrentRendererChangeInfos(vector> + &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission); + int32_t GetCurrentCapturerChangeInfos(vector> &audioCapturerChangeInfos, + bool hasBTPermission, bool hasSystemPermission); + std::vector> GetExcludedDevices(AudioDeviceUsage audioDevUsage); + int32_t GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo, const std::string &bundleName); + int32_t GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo); + std::vector> GetVolumeGroupInfos(); +private: + std::shared_ptr coreService_; + std::shared_mutex eventMutex_; + }; + + // Ctor & dtor + AudioCoreService(); + ~AudioCoreService(); + + // Called by AudioPolicyServer + static std::shared_ptr GetCoreService(); + void Init(); + void DeInit(); + void SetCallbackHandler(std::shared_ptr handler); + std::shared_ptr GetEventEntry(); + + // Called by EventEntry - with lock + // Stream operations + int32_t CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &audioFlag, uint32_t &sessionId); + int32_t CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &audioFlag, uint32_t &sessionId); + int32_t StartClient(uint32_t sessionId); + int32_t PauseClient(uint32_t sessionId); + int32_t StopClient(uint32_t sessionId); + int32_t ReleaseClient(uint32_t sessionId); + + // ICoreServiceProvider from EventEntry + int32_t SetDefaultOutputDevice( + const DeviceType deviceType, const uint32_t sessionID, const StreamUsage streamUsage, bool isRunning); + std::string GetAdapterNameBySessionId(uint32_t sessionId); + int32_t GetProcessDeviceInfoBySessionId(uint32_t sessionId, AudioDeviceDescriptor &deviceInfo); + uint32_t GenerateSessionId(); + + // IDeviceStatusObserver from EventEntry + void OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command); + void OnDeviceStatusUpdated(DeviceType devType, bool isConnected, + const std::string &macAddress, const std::string &deviceName, + const AudioStreamInfo &streamInfo, DeviceRole role = DEVICE_ROLE_NONE, bool hasPair = false); + void OnDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected); + void OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop = false); + void OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status); + void OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected); + void OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress, + const std::string &deviceName, const AudioStreamInfo &streamInfo); + int32_t OnServiceConnected(AudioServiceIndex serviceIndex); + void OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress); + + // Functions related to assignment operations - device related + int32_t SetAudioScene(AudioScene audioScene); + bool IsArmUsbDevice(const AudioDeviceDescriptor &deviceDesc); + int32_t SetDeviceActive(InternalDeviceType deviceType, bool active, const int32_t pid); + int32_t SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address); + int32_t RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, + const sptr &object, const int32_t apiVersion); + int32_t UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo); + void RegisteredTrackerClientDied(pid_t uid); + bool ConnectServiceAdapter(); + void OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName); + int32_t SelectOutputDevice(sptr audioRendererFilter, + std::vector> selectedDesc); + int32_t SelectInputDevice(sptr audioCapturerFilter, + std::vector> selectedDesc); + void NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value); + int32_t OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo, AudioStreamInfo streamInfo); + void OnCapturerSessionRemoved(uint64_t sessionID); + void SetDisplayName(const std::string &deviceName, bool isLocalDevice); + int32_t TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason); + void FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo, + const AudioStreamDeviceChangeReasonExt reason); + void FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo); + int32_t ExcludeOutputDevices(AudioDeviceUsage audioDevUsage, + std::vector> &audioDeviceDescriptors); + int32_t UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage, + std::vector> &audioDeviceDescriptors); + + // Functions related to get operations - device related + std::vector> GetDevices(DeviceFlag deviceFlag); + std::vector> GetPreferredOutputDeviceDescInner( + AudioRendererInfo &rendererInfo, std::string networkId); + std::vector> GetPreferredInputDeviceDescInner( + AudioCapturerInfo &captureInfo, std::string networkId); + std::shared_ptr GetActiveBluetoothDevice(); + std::vector> GetAvailableDevices(AudioDeviceUsage usage); + std::vector> GetAvailableMicrophones(); + std::vector> GetAudioCapturerMicrophoneDescriptors(int32_t sessionId); + int32_t GetCurrentRendererChangeInfos(vector> + &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission); + int32_t GetCurrentCapturerChangeInfos(vector> &audioCapturerChangeInfos, + bool hasBTPermission, bool hasSystemPermission); + std::vector> GetExcludedDevices(AudioDeviceUsage audioDevUsage); + int32_t GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo, const std::string &bundleName); + int32_t GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo); + bool GetVolumeGroupInfos(std::vector> &infos); + + // Called by Others - without lock + int32_t SetAudioDeviceAnahsCallback(const sptr &object); + int32_t UnsetAudioDeviceAnahsCallback(); + void OnUpdateAnahsSupport(std::string anahsShowType); + void RegisterBluetoothListener(); + void UnregisterBluetoothListener(); + void ConfigDistributedRoutingRole(const std::shared_ptr descriptor, CastType type); + int32_t SetRingerMode(AudioRingerMode ringMode); + int32_t FetchOutputDeviceAndRoute( + const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN); + int32_t FetchInputDeviceAndRoute(); + void SetAudioServerProxy(); + +private: + static std::string GetEncryptAddr(const std::string &addr); + int32_t FetchRendererPipesAndExecute(std::vector> &streamDescs, + const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN); + int32_t FetchCapturerPipesAndExecute(std::vector> &streamDescs); + int32_t HandleScoInputDeviceFetched(std::shared_ptr streamDesc); + int32_t ScoInputDeviceFetchedForRecongnition( + bool handleFlag, const std::string &address, ConnectState connectState); + void BluetoothScoFetch(std::shared_ptr streamDesc); + void CheckModemScene(const AudioStreamDeviceChangeReasonExt reason); + void HandleAudioCaptureState(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo); + void UpdateDefaultOutputDeviceWhenStopping(int32_t uid); + int32_t BluetoothDeviceFetchOutputHandle(shared_ptr desc, + const AudioStreamDeviceChangeReasonExt reason, std::string encryptMacAddr); + int32_t ActivateA2dpDeviceWhenDescEnabled(shared_ptr desc, + const AudioStreamDeviceChangeReasonExt reason); + int32_t ActivateA2dpDevice(std::shared_ptr desc, + const AudioStreamDeviceChangeReasonExt reason); + int32_t SwitchActiveA2dpDevice(std::shared_ptr deviceDescriptor); + int32_t LoadA2dpModule(DeviceType deviceType, const AudioStreamInfo &audioStreamInfo, + std::string networkId, std::string sinkName, SourceType sourceType); + int32_t ReloadA2dpAudioPort(AudioModuleInfo &moduleInfo, DeviceType deviceType, + const AudioStreamInfo& audioStreamInfo, std::string networkId, std::string sinkName, + SourceType sourceType); + void GetA2dpModuleInfo(AudioModuleInfo &moduleInfo, const AudioStreamInfo& audioStreamInfo, + SourceType sourceType); + bool IsSameDevice(shared_ptr &desc, AudioDeviceDescriptor &deviceInfo); +#ifdef BLUETOOTH_ENABLE + const sptr RegisterBluetoothDeathCallback(); + static void BluetoothServiceCrashedCallback(pid_t pid, pid_t uid); +#endif + int32_t FetchDeviceAndRoute( + const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN); + int32_t FetchRendererPipeAndExecute(std::shared_ptr streamDesc, + uint32_t &sessionId, uint32_t &audioFlag, + const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN); + void ProcessOutputPipeNew(std::shared_ptr pipeInfo, uint32_t &flag); + void ProcessOutputPipeUpdate(std::shared_ptr pipeInfo, uint32_t &flag); + int32_t FetchCapturerPipeAndExecute( + std::shared_ptr streamDesc, uint32_t &audioFlag, uint32_t &sessionId); + void ProcessInputPipeNew(std::shared_ptr pipeInfo, uint32_t &flag); + void ProcessInputPipeUpdate(std::shared_ptr pipeInfo, uint32_t &flag); + void RemoveUnusedPipe(); + void MoveToNewOutputDevice(std::shared_ptr streamDesc, + const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN); + int32_t MoveToRemoteOutputDevice( + std::vector sinkInputIds, std::shared_ptr remoteDeviceDescriptor); + void MoveToNewInputDevice(std::shared_ptr streamDesc); + int32_t MoveToLocalInputDevice( + std::vector sourceOutputs, std::shared_ptr localDeviceDescriptor); + int32_t MoveToRemoteInputDevice( + std::vector sourceInputs, std::shared_ptr remoteDeviceDescriptor); + int32_t OpenRemoteAudioDevice(std::string networkId, DeviceRole deviceRole, DeviceType deviceType, + std::shared_ptr remoteDeviceDescriptor); + bool SelectRingerOrAlarmDevices(std::shared_ptr streamDesc); + void UpdateDualToneState(const bool &enable, const int32_t &sessionId); + int32_t MoveToLocalOutputDevice( + std::vector sinkInputIds, std::shared_ptr localDeviceDescriptor); + void UpdateDeviceInfo(std::shared_ptr oldDeviceDesc, + const std::shared_ptr newDeviceDesc, bool hasBTPermission, bool hasSystemPermission); + bool HasLowLatencyCapability(DeviceType deviceType, bool isRemote); + void TriggerRecreateRendererStreamCallback(int32_t callerPid, int32_t sessionId, uint32_t routeFlag, + const AudioStreamDeviceChangeReasonExt::ExtEnum reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN); + void TriggerRecreateCapturerStreamCallback(int32_t callerPid, int32_t sessionId, uint32_t routeFlag); + uint32_t OpenNewAudioPortAndRoute(std::shared_ptr pipeInfo, uint32_t &paIndex); + static int32_t GetRealUid(std::shared_ptr streamDesc); + static void UpdateRendererInfoWhenNoPermission(const shared_ptr &audioRendererChangeInfos, + bool hasSystemPermission); + static void UpdateCapturerInfoWhenNoPermission(const shared_ptr &audioCapturerChangeInfos, + bool hasSystemPermission); + void SendA2dpConnectedWhileRunning(const RendererState &rendererState, const uint32_t &sessionId); + void UpdateSessionConnectionState(const int32_t &sessionID, const int32_t &state); + void UpdateTrackerDeviceChange(const vector> &desc); + void SetPlaybackStreamFlag(std::shared_ptr streamDesc); + AudioFlag CheckIsSpecialStream(std::shared_ptr &streamDesc); + void SetRecordStreamFlag(std::shared_ptr streamDesc); + std::vector FilterSourceOutputs(int32_t sessionId); + std::vector GetSourceOutputs(); + void UpdateOutputRoute(std::shared_ptr streamDesc); + void OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor &deviceDescriptor); + void OnPreferredInputDeviceUpdated(DeviceType deviceType, std::string networkId); + bool IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType &deviceType); + bool GetFastControlParam(); + void StoreDistributedRoutingRoleInfo(const std::shared_ptr descriptor, CastType type); + int32_t GetSystemVolumeLevel(AudioStreamType streamType); + float GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel, DeviceType deviceType) const; + bool IsStreamSupportLowpower(std::shared_ptr streamDesc); + bool IsStreamSupportDirect(std::shared_ptr streamDesc); + bool IsStreamSupportMultiChannel(std::shared_ptr streamDesc); + + bool IsPaRoute(uint32_t routeFlag); + int32_t HandleScoOutputDeviceFetched( + shared_ptr &desc, const AudioStreamDeviceChangeReasonExt reason); +private: + std::shared_ptr eventEntry_; + std::shared_ptr audioPolicyServerHandler_ = nullptr; + AudioActiveDevice& audioActiveDevice_; + AudioSceneManager& audioSceneManager_; + AudioVolumeManager& audioVolumeManager_; + AudioCapturerSession& audioCapturerSession_; + AudioDeviceManager &audioDeviceManager_; + AudioConnectedDevice& audioConnectedDevice_; + AudioDeviceStatus& audioDeviceStatus_; + AudioEffectService& audioEffectService_; + AudioMicrophoneDescriptor& audioMicrophoneDescriptor_; + AudioRecoveryDevice& audioRecoveryDevice_; + AudioRouterCenter& audioRouterCenter_; + AudioStreamCollector& streamCollector_; + AudioStateManager &audioStateManager_; + AudioDeviceCommon& audioDeviceCommon_; + AudioOffloadStream& audioOffloadStream_; + AudioA2dpOffloadFlag& audioA2dpOffloadFlag_; + IAudioPolicyInterface& audioPolicyManager_; + AudioRouteMap& audioRouteMap_; + AudioIOHandleMap& audioIOHandleMap_; + AudioA2dpDevice& audioA2dpDevice_; + AudioEcManager& audioEcManager_; + AudioPolicyConfigManager& policyConfigMananger_; + std::shared_ptr audioPipeSelector_; + + std::shared_ptr audioA2dpOffloadManager_ = nullptr; + std::shared_ptr deviceStatusListener_; + std::shared_ptr pipeManager_ = nullptr; + + std::unordered_map spatialDeviceMap_; + static bool isBtListenerRegistered; + static constexpr int32_t MIN_SERVICE_COUNT = 2; + std::bitset serviceFlag_; + bool isCurrentRemoteRenderer_ = false; + bool isOpenRemoteDevice = false; + int32_t enableDualHalToneSessionId_ = -1; + bool enableDualHalToneState_ = false; + int32_t shouldUpdateDeviceDueToDualTone_ = false; + bool isFastControlled_ = true; + std::mutex serviceFlagMutex_; + DistributedRoutingInfo distributedRoutingInfo_ = { + .descriptor = nullptr, + .type = CAST_TYPE_NULL + }; +}; +} +} +#endif // AUDIO_CORE_SERVICE_H diff --git a/services/audio_policy/services/core/src/audio_core_service.cpp b/services/audio_policy/services/core/src/audio_core_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5489a41b81bf0c885b8c7b684eeb7448e4355407 --- /dev/null +++ b/services/audio_policy/services/core/src/audio_core_service.cpp @@ -0,0 +1,1096 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef LOG_TAG +#define LOG_TAG "AudioCoreService" +#endif + +#include "audio_core_service.h" +#include "system_ability.h" +#include "audio_server_proxy.h" +#include "audio_policy_utils.h" +#include "iservice_registry.h" +#include "hdi_adapter_info.h" +#include "audio_usb_manager.h" +#include "data_share_observer_callback.h" +#include "audio_spatialization_service.h" + + +namespace OHOS { +namespace AudioStandard { +namespace { +const uint32_t FIRST_SESSIONID = 100000; +static const char* CHECK_FAST_BLOCK_PREFIX = "Is_Fast_Blocked_For_AppName#"; +static const int32_t BLUETOOTH_FETCH_RESULT_CONTINUE = 1; +static const int32_t BLUETOOTH_FETCH_RESULT_ERROR = 2; +} + +static const char* CONFIG_AUDIO_BALANACE_KEY = "master_balance"; +bool AudioCoreService::isBtListenerRegistered = false; +#ifdef BLUETOOTH_ENABLE +static sptr g_btProxy = nullptr; +mutex g_btProxyMutex; +#endif + +AudioCoreService::AudioCoreService() + : audioPolicyServerHandler_(DelayedSingleton::GetInstance()), + audioActiveDevice_(AudioActiveDevice::GetInstance()), + audioSceneManager_(AudioSceneManager::GetInstance()), + audioVolumeManager_(AudioVolumeManager::GetInstance()), + audioCapturerSession_(AudioCapturerSession::GetInstance()), + audioDeviceManager_(AudioDeviceManager::GetAudioDeviceManager()), + audioConnectedDevice_(AudioConnectedDevice::GetInstance()), + audioDeviceStatus_(AudioDeviceStatus::GetInstance()), + audioEffectService_(AudioEffectService::GetAudioEffectService()), + audioMicrophoneDescriptor_(AudioMicrophoneDescriptor::GetInstance()), + audioRecoveryDevice_(AudioRecoveryDevice::GetInstance()), + audioRouterCenter_(AudioRouterCenter::GetAudioRouterCenter()), + streamCollector_(AudioStreamCollector::GetAudioStreamCollector()), + audioStateManager_(AudioStateManager::GetAudioStateManager()), + audioDeviceCommon_(AudioDeviceCommon::GetInstance()), + audioOffloadStream_(AudioOffloadStream::GetInstance()), + audioA2dpOffloadFlag_(AudioA2dpOffloadFlag::GetInstance()), + audioPolicyManager_(AudioPolicyManagerFactory::GetAudioPolicyManager()), + audioRouteMap_(AudioRouteMap::GetInstance()), + audioIOHandleMap_(AudioIOHandleMap::GetInstance()), + audioA2dpDevice_(AudioA2dpDevice::GetInstance()), + audioEcManager_(AudioEcManager::GetInstance()), + policyConfigMananger_(AudioPolicyConfigManager::GetInstance()), + audioPipeSelector_(AudioPipeSelector::GetPipeSelector()), + pipeManager_(AudioPipeManager::GetPipeManager()) +{ + AUDIO_INFO_LOG("Ctor"); +} + +AudioCoreService::~AudioCoreService() +{ + AUDIO_INFO_LOG("Dtor"); +} + +std::shared_ptr AudioCoreService::GetCoreService() +{ + static std::shared_ptr instance = std::make_shared(); + return instance; +} + +void AudioCoreService::Init() +{ + serviceFlag_.reset(); + eventEntry_ = std::make_shared(shared_from_this()); + + audioA2dpOffloadManager_ = std::make_shared(); + if (audioA2dpOffloadManager_ != nullptr) { + audioA2dpOffloadManager_->Init(); + } + audioVolumeManager_.Init(audioPolicyServerHandler_); + audioDeviceCommon_.Init(audioPolicyServerHandler_); + audioRecoveryDevice_.Init(audioA2dpOffloadManager_); + + audioDeviceStatus_.Init(audioA2dpOffloadManager_, audioPolicyServerHandler_); + audioCapturerSession_.Init(audioA2dpOffloadManager_); + + deviceStatusListener_ = std::make_shared(*eventEntry_); // shared_ptr.get() -> * + isFastControlled_ = GetFastControlParam(); + // Register device status listener + int32_t status = deviceStatusListener_->RegisterDeviceStatusListener(); + if (status != SUCCESS) { + AudioPolicyUtils::GetInstance().WriteServiceStartupError("Register for device status events failed"); + AUDIO_ERR_LOG("Register for device status events failed"); + } + + policyConfigMananger_.Init(); +} + +void AudioCoreService::DeInit() +{ + // Remove device status listener + deviceStatusListener_->UnRegisterDeviceStatusListener(); + if (isBtListenerRegistered) { + UnregisterBluetoothListener(); + } +} + +void AudioCoreService::SetCallbackHandler(std::shared_ptr handler) +{ + audioPolicyServerHandler_ = handler; +} + +std::shared_ptr AudioCoreService::GetEventEntry() +{ + return eventEntry_; +} + +int32_t AudioCoreService::CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &audioFlag, uint32_t &sessionId) +{ + if (streamDesc->rendererInfo_.streamUsage == STREAM_USAGE_VOICE_MODEM_COMMUNICATION) { + audioFlag = AUDIO_FLAG_NORMAL; + sessionId = GenerateSessionId(); + AUDIO_INFO_LOG("Modem communication, sessionId %{public}u", sessionId); + pipeManager_->SetModemCommunicationId(sessionId); + return SUCCESS; + } + streamDesc->oldDeviceDescs_ = streamDesc->newDeviceDescs_; + // Select device + int32_t ret = SUCCESS; + streamDesc->newDeviceDescs_ = + audioRouterCenter_.FetchOutputDevices(streamDesc->rendererInfo_.streamUsage, GetRealUid(streamDesc)); + for (auto device : streamDesc->newDeviceDescs_) { + AUDIO_INFO_LOG("Device type %{public}d", device->deviceType_); + } + { + // handle a2dp + std::string encryptMacAddr = + GetEncryptAddr(streamDesc->newDeviceDescs_.front()->macAddress_); + int32_t bluetoothFetchResult = BluetoothDeviceFetchOutputHandle(streamDesc->newDeviceDescs_.front(), + AudioStreamDeviceChangeReason::UNKNOWN, encryptMacAddr); + if (bluetoothFetchResult == BLUETOOTH_FETCH_RESULT_CONTINUE || + bluetoothFetchResult == BLUETOOTH_FETCH_RESULT_ERROR) { + return ERROR; + } + } + SetPlaybackStreamFlag(streamDesc); + AUDIO_INFO_LOG("Will use audio flag: %{public}u", streamDesc->audioFlag_); + + // Fetch pipe + ret = FetchRendererPipeAndExecute(streamDesc, sessionId, audioFlag); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "FetchPipeAndExecute failed"); + + return SUCCESS; +} + +int32_t AudioCoreService::CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &audioFlag, uint32_t &sessionId) +{ + streamDesc->oldDeviceDescs_ = streamDesc->newDeviceDescs_; + // Select device + int32_t ret = SUCCESS; + std::shared_ptr inputDeviceDesc = + audioRouterCenter_.FetchInputDevice(streamDesc->capturerInfo_.sourceType, GetRealUid(streamDesc)); + streamDesc->newDeviceDescs_.clear(); + streamDesc->newDeviceDescs_.push_back(inputDeviceDesc); + AUDIO_INFO_LOG("New stream device type %{public}d", inputDeviceDesc->deviceType_); + + { + // handle a2dp + if (streamDesc->newDeviceDescs_[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { + BluetoothScoFetch(streamDesc); + } + } + + SetRecordStreamFlag(streamDesc); + AUDIO_INFO_LOG("Will use audio flag: %{public}u", streamDesc->audioFlag_); + + // Fetch pipe + ret = FetchCapturerPipeAndExecute(streamDesc, audioFlag, sessionId); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "FetchPipeAndExecute failed"); + + return SUCCESS; +} + +bool AudioCoreService::IsStreamSupportMultiChannel(std::shared_ptr streamDesc) +{ + Trace trace("IsStreamSupportMultiChannel"); + AUDIO_INFO_LOG("In"); + + if (streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_SPEAKER && + streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_BLUETOOTH_A2DP) { + AUDIO_INFO_LOG("normal stream, deviceType: %{public}d", streamDesc->newDeviceDescs_[0]->deviceType_); + return false; + } + if (streamDesc->streamInfo_.channels <= STEREO) { + AUDIO_INFO_LOG("normal stream beacuse channels."); + return false; + } + // The multi-channel algorithm needs to be supported in the dsp + return AudioServerProxy::GetInstance().GetEffectOffloadEnabledProxy(); +} + +bool AudioCoreService::IsStreamSupportDirect(std::shared_ptr streamDesc) +{ + Trace trace("IsStreamSupportDirect"); + if (streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_WIRED_HEADSET && + streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_USB_HEADSET) { + AUDIO_INFO_LOG("normal stream, deviceType: %{public}d", + streamDesc->newDeviceDescs_[0]->deviceType_); + return false; + } + if (streamDesc->rendererInfo_.streamUsage != STREAM_USAGE_MUSIC || + streamDesc->streamInfo_.samplingRate < SAMPLE_RATE_48000 || + streamDesc->streamInfo_.format < SAMPLE_S24LE || + streamDesc->rendererInfo_.pipeType != PIPE_TYPE_DIRECT_MUSIC) { + AUDIO_INFO_LOG("normal stream because stream info"); + return false; + } + if (streamDesc->streamInfo_.samplingRate > SAMPLE_RATE_192000) { + AUDIO_INFO_LOG("sample rate over 192k"); + return false; + } + return true; +} + +void AudioCoreService::SetPlaybackStreamFlag(std::shared_ptr streamDesc) +{ + AUDIO_INFO_LOG("deviceType: %{public}d", streamDesc->newDeviceDescs_.front()->deviceType_); + // fast/normal has done in audioRendererPrivate + if (streamDesc->rendererInfo_.originalFlag == AUDIO_FLAG_FORCED_NORMAL) { + streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_NORMAL; + AUDIO_INFO_LOG("Forced normal"); + return; + } + + if (streamDesc->newDeviceDescs_.back()->deviceType_ == DEVICE_TYPE_REMOTE_CAST || + streamDesc->newDeviceDescs_.back()->networkId_ == "REMOTE_NETWORK_ID") { + streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_NORMAL; // remote cast/remote device select normal + AUDIO_INFO_LOG("remote device/cast set normal"); + return; + } + + if (streamDesc->rendererInfo_.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION || + streamDesc->rendererInfo_.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) { + std::string sinkPortName = + AudioPolicyUtils::GetInstance().GetSinkPortName(streamDesc->newDeviceDescs_.front()->deviceType_); + AUDIO_INFO_LOG("sinkPortName %{public}s", sinkPortName.c_str()); + // in plan: if has two voip, return normal + streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_VOIP; + AUDIO_INFO_LOG("sinkPortName: %{public}s, audioFlag_ %{public}d", sinkPortName.c_str(), streamDesc->audioFlag_); + return; + } + AUDIO_INFO_LOG("rendererFlag: %{public}d", streamDesc->rendererInfo_.rendererFlags); + switch (streamDesc->rendererInfo_.originalFlag) { + case AUDIO_FLAG_MMAP: + streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_FAST; + return; + case AUDIO_FLAG_VOIP_FAST: + streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_VOIP; + return; + case AUDIO_FLAG_VOIP_DIRECT: + streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_VOIP; + return; + default: + break; + } + streamDesc->audioFlag_ = CheckIsSpecialStream(streamDesc); +} + +AudioFlag AudioCoreService::CheckIsSpecialStream(std::shared_ptr &streamDesc) +{ + if (IsStreamSupportDirect(streamDesc)) { + return AUDIO_OUTPUT_FLAG_HD; + } + if (IsStreamSupportLowpower(streamDesc)) { + return AUDIO_OUTPUT_FLAG_LOWPOWER; + } + if (IsStreamSupportMultiChannel(streamDesc)) { + return AUDIO_OUTPUT_FLAG_MULTICHANNEL; + } + AUDIO_INFO_LOG("StreamDesc flag use default - NORMAL"); + return AUDIO_OUTPUT_FLAG_NORMAL; +} + +void AudioCoreService::SetRecordStreamFlag(std::shared_ptr streamDesc) +{ + // fast/normal has done in audioCapturerPrivate + if (streamDesc->capturerInfo_.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) { + // in plan: if has two voip, return normal + streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_VOIP; + AUDIO_INFO_LOG("streamDesc->audioFlag_ %{public}d", streamDesc->audioFlag_); + return; + } + if (streamDesc->capturerInfo_.sourceType == SOURCE_TYPE_REMOTE_CAST) { + streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_NORMAL; + AUDIO_WARNING_LOG("record normal stream due to remotecast"); + return; + } + + if (streamDesc->capturerInfo_.sourceType == SOURCE_TYPE_WAKEUP) { + streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_WAKEUP; + } + switch (streamDesc->capturerInfo_.capturerFlags) { + case AUDIO_FLAG_MMAP: + streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_FAST; + return; + case AUDIO_FLAG_VOIP_FAST: + streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_VOIP_FAST; + return; + default: + break; + } + // In plan: streamDesc to audioFlag; + streamDesc->audioFlag_ = AUDIO_FLAG_NONE; +} + + +int32_t AudioCoreService::StartClient(uint32_t sessionId) +{ + AUDIO_INFO_LOG("In, session %{public}u", sessionId); + std::shared_ptr streamDesc = pipeManager_->GetStreamDescById(sessionId); + if (streamDesc == nullptr) { + AUDIO_ERR_LOG("Cannot find session %{public}u", sessionId); + return ERROR; + } + + if (streamDesc->audioMode_ == AUDIO_MODE_PLAYBACK) { + std::vector> activeDevices; + if (streamDesc->newDeviceDescs_.size() == 2) { // 2 for dual use + std::string firstSinkName = + AudioPolicyUtils::GetInstance().GetSinkName(streamDesc->newDeviceDescs_[0], streamDesc->sessionId_); + std::string secondSinkName = + AudioPolicyUtils::GetInstance().GetSinkName(streamDesc->newDeviceDescs_[1], streamDesc->sessionId_); + AUDIO_INFO_LOG("firstSinkName %{public}s, secondSinkName %{public}s", + firstSinkName.c_str(), secondSinkName.c_str()); + if (firstSinkName == secondSinkName) { + activeDevices.push_back( + make_pair(streamDesc->newDeviceDescs_[0]->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG)); + activeDevices.push_back( + make_pair(streamDesc->newDeviceDescs_[1]->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG)); + } + } else { + std::string firstSinkName = + AudioPolicyUtils::GetInstance().GetSinkName(streamDesc->newDeviceDescs_[0], streamDesc->sessionId_); + AUDIO_INFO_LOG("firstSinkName %{public}s", firstSinkName.c_str()); + if (firstSinkName == "primary") { + activeDevices.push_back( + make_pair(streamDesc->newDeviceDescs_[0]->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG)); + } + } + if (activeDevices.size() != 0) { + audioActiveDevice_.UpdateActiveDevicesRoute(activeDevices); + } + } else { + audioActiveDevice_.UpdateActiveDeviceRoute( + streamDesc->newDeviceDescs_[0]->deviceType_, DeviceFlag::INPUT_DEVICES_FLAG); + } + + pipeManager_->StartClient(sessionId); + return SUCCESS; +} + +int32_t AudioCoreService::PauseClient(uint32_t sessionId) +{ + std::shared_ptr streamDesc = pipeManager_->GetStreamDescById(sessionId); + if (streamDesc->audioMode_ == AUDIO_MODE_PLAYBACK) { + audioActiveDevice_.UpdateActiveDeviceRoute( + streamDesc->newDeviceDescs_[0]->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG); + } else { + audioActiveDevice_.UpdateActiveDeviceRoute( + streamDesc->newDeviceDescs_[0]->deviceType_, DeviceFlag::INPUT_DEVICES_FLAG); + } + audioActiveDevice_.UpdateActiveDeviceRoute(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG); + + pipeManager_->PauseClient(sessionId); + return SUCCESS; +} + +int32_t AudioCoreService::StopClient(uint32_t sessionId) +{ + std::shared_ptr streamDesc = pipeManager_->GetStreamDescById(sessionId); + if (streamDesc->audioMode_ == AUDIO_MODE_PLAYBACK) { + audioActiveDevice_.UpdateActiveDeviceRoute( + streamDesc->newDeviceDescs_[0]->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG); + } else { + audioActiveDevice_.UpdateActiveDeviceRoute( + streamDesc->newDeviceDescs_[0]->deviceType_, DeviceFlag::INPUT_DEVICES_FLAG); + } + audioActiveDevice_.UpdateActiveDeviceRoute(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG); + + pipeManager_->StopClient(sessionId); + return SUCCESS; +} + +int32_t AudioCoreService::ReleaseClient(uint32_t sessionId) +{ + AUDIO_INFO_LOG("Release session %{public}u", sessionId); + if (sessionId == pipeManager_->GetModemCommunicationId()) { + AUDIO_INFO_LOG("Modem communication, sessionId %{public}u", sessionId); + pipeManager_->ResetModemCommunicationId(); + return SUCCESS; + } + pipeManager_->RemoveClient(sessionId); + RemoveUnusedPipe(); + + return SUCCESS; +} + +int32_t AudioCoreService::SetAudioScene(AudioScene audioScene) +{ + audioSceneManager_.SetAudioScenePre(audioScene); + + FetchDeviceAndRoute(AudioStreamDeviceChangeReasonExt::ExtEnum::SET_AUDIO_SCENE); + + int32_t result = audioSceneManager_.SetAudioSceneAfter(audioScene, audioA2dpOffloadFlag_.GetA2dpOffloadFlag()); + CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "failed [%{public}d]", result); + + if (audioScene == AUDIO_SCENE_PHONE_CALL) { + // Make sure the STREAM_VOICE_CALL volume is set before the calling starts. + audioVolumeManager_.SetVoiceCallVolume(audioVolumeManager_.GetSystemVolumeLevel(STREAM_VOICE_CALL)); + } else { + audioVolumeManager_.SetVoiceRingtoneMute(false); + } + audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(), + audioActiveDevice_.GetCurrentOutputDevice(), "SetAudioScene"); + return SUCCESS; +} + +bool AudioCoreService::IsArmUsbDevice(const AudioDeviceDescriptor &deviceDesc) +{ + return audioDeviceManager_.IsArmUsbDevice(deviceDesc); +} + +std::vector> AudioCoreService::GetDevices(DeviceFlag deviceFlag) +{ + return audioConnectedDevice_.GetDevicesInner(deviceFlag); +} + +int32_t AudioCoreService::SetDeviceActive(InternalDeviceType deviceType, bool active, const int32_t pid) +{ + int32_t ret = audioActiveDevice_.SetDeviceActive(deviceType, active, pid); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetDeviceActive failed"); + + FetchDeviceAndRoute(AudioStreamDeviceChangeReasonExt::ExtEnum::OVERRODE); + + audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(), + audioActiveDevice_.GetCurrentOutputDevice(), "SetDevcieActive"); + return SUCCESS; +} + +std::vector> AudioCoreService::GetPreferredOutputDeviceDescInner( + AudioRendererInfo &rendererInfo, std::string networkId) +{ + std::vector> deviceList = {}; + if (rendererInfo.streamUsage <= STREAM_USAGE_UNKNOWN || + rendererInfo.streamUsage > STREAM_USAGE_MAX) { + AUDIO_WARNING_LOG("Invalid usage[%{public}d], return current device.", rendererInfo.streamUsage); + std::shared_ptr devDesc = + std::make_shared(audioActiveDevice_.GetCurrentOutputDevice()); + deviceList.push_back(devDesc); + return deviceList; + } + if (networkId == LOCAL_NETWORK_ID) { + vector> descs = + audioRouterCenter_.FetchOutputDevices(rendererInfo.streamUsage, -1); + for (size_t i = 0; i < descs.size(); i++) { + std::shared_ptr devDesc = std::make_shared(*descs[i]); + deviceList.push_back(devDesc); + } + } else { + vector> descs = audioDeviceManager_.GetRemoteRenderDevices(); + for (const auto &desc : descs) { + std::shared_ptr devDesc = std::make_shared(*desc); + deviceList.push_back(devDesc); + } + } + + return deviceList; +} + +std::vector> AudioCoreService::GetPreferredInputDeviceDescInner( + AudioCapturerInfo &captureInfo, std::string networkId) +{ + std::vector> deviceList = {}; + if (captureInfo.sourceType <= SOURCE_TYPE_INVALID || + captureInfo.sourceType > SOURCE_TYPE_MAX) { + std::shared_ptr devDesc = + std::make_shared(audioActiveDevice_.GetCurrentInputDevice()); + deviceList.push_back(devDesc); + return deviceList; + } + + if (captureInfo.sourceType == SOURCE_TYPE_WAKEUP) { + std::shared_ptr devDesc = + std::make_shared(DEVICE_TYPE_MIC, INPUT_DEVICE); + devDesc->networkId_ = LOCAL_NETWORK_ID; + deviceList.push_back(devDesc); + return deviceList; + } + + if (networkId == LOCAL_NETWORK_ID) { + std::shared_ptr desc = audioRouterCenter_.FetchInputDevice(captureInfo.sourceType, -1); + if (desc->deviceType_ == DEVICE_TYPE_NONE && (captureInfo.sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE || + captureInfo.sourceType == SOURCE_TYPE_REMOTE_CAST)) { + desc->deviceType_ = DEVICE_TYPE_INVALID; + desc->deviceRole_ = INPUT_DEVICE; + } + std::shared_ptr devDesc = std::make_shared(*desc); + deviceList.push_back(devDesc); + } else { + vector> descs = audioDeviceManager_.GetRemoteCaptureDevices(); + for (const auto &desc : descs) { + std::shared_ptr devDesc = std::make_shared(*desc); + deviceList.push_back(devDesc); + } + } + + return deviceList; +} + +int32_t AudioCoreService::GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo, + const std::string &bundleName) +{ + // Use GetPreferredOutputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream + std::vector> preferredDeviceList = + GetPreferredOutputDeviceDescInner(rendererInfo, LOCAL_NETWORK_ID); + if (preferredDeviceList.size() == 0) { + return AUDIO_FLAG_NORMAL; + } + + int32_t flag = AUDIO_FLAG_NORMAL; + if (isFastControlled_ && (rendererInfo.playerType != PLAYER_TYPE_SOUND_POOL) && + (flag == AUDIO_FLAG_MMAP || flag == AUDIO_FLAG_VOIP_FAST)) { + std::string bundleNamePre = CHECK_FAST_BLOCK_PREFIX + bundleName; + std::string result = AudioServerProxy::GetInstance().GetAudioParameterProxy(bundleNamePre); + if (result == "true") { + AUDIO_INFO_LOG("%{public}s not in fast list", bundleName.c_str()); + return AUDIO_FLAG_NORMAL; + } + } + if (flag == AUDIO_FLAG_VOIP_FAST && audioSceneManager_.GetAudioScene() == AUDIO_SCENE_PHONE_CALL) { + AUDIO_INFO_LOG("Current scene is phone call, concede incoming voip fast output stream"); + flag = AUDIO_FLAG_NORMAL; + } + return flag; +} + +int32_t AudioCoreService::GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo) +{ + // Use GetPreferredInputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream + std::vector> preferredDeviceList = + GetPreferredInputDeviceDescInner(capturerInfo, LOCAL_NETWORK_ID); + if (preferredDeviceList.size() == 0) { + return AUDIO_FLAG_NORMAL; + } + int32_t flag = audioDeviceCommon_.GetPreferredInputStreamTypeInner(capturerInfo.sourceType, + preferredDeviceList[0]->deviceType_, + capturerInfo.originalFlag, preferredDeviceList[0]->networkId_, capturerInfo.samplingRate); + if (flag == AUDIO_FLAG_VOIP_FAST && audioSceneManager_.GetAudioScene() == AUDIO_SCENE_PHONE_CALL) { + AUDIO_INFO_LOG("Current scene is phone call, concede incoming voip fast input stream"); + flag = AUDIO_FLAG_NORMAL; + } + return flag; +} + +bool AudioCoreService::GetVolumeGroupInfos(std::vector> &infos) +{ + return audioVolumeManager_.GetVolumeGroupInfosNotWait(infos); +} + +std::shared_ptr AudioCoreService::GetActiveBluetoothDevice() +{ + std::shared_ptr preferredDesc = audioStateManager_.GetPreferredCallRenderDevice(); + if (preferredDesc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { + return preferredDesc; + } + + std::vector> audioPrivacyDeviceDescriptors = + audioDeviceManager_.GetCommRenderPrivacyDevices(); + std::vector> activeDeviceDescriptors; + + for (const auto &desc : audioPrivacyDeviceDescriptors) { + if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && desc->isEnable_) { + activeDeviceDescriptors.push_back(make_shared(*desc)); + } + } + + uint32_t btDeviceSize = activeDeviceDescriptors.size(); + if (btDeviceSize == 0) { + activeDeviceDescriptors = audioDeviceManager_.GetCommRenderBTCarDevices(); + } + btDeviceSize = activeDeviceDescriptors.size(); + if (btDeviceSize == 0) { + return make_shared(); + } else if (btDeviceSize == 1) { + shared_ptr res = std::move(activeDeviceDescriptors[0]); + return res; + } + + uint32_t index = 0; + for (uint32_t i = 1; i < btDeviceSize; ++i) { + if (activeDeviceDescriptors[i]->connectTimeStamp_ > + activeDeviceDescriptors[index]->connectTimeStamp_) { + index = i; + } + } + shared_ptr res = std::move(activeDeviceDescriptors[index]); + return res; +} + +void AudioCoreService::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command) +{ + audioDeviceStatus_.OnDeviceInfoUpdated(desc, command); +} + +int32_t AudioCoreService::SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address) +{ + AUDIO_WARNING_LOG("Device type[%{public}d] flag[%{public}d] address[%{public}s]", + deviceType, active, GetEncryptAddr(address).c_str()); + CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device"); + + int32_t ret = audioActiveDevice_.SetCallDeviceActive(deviceType, active, address); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetCallDeviceActive failed"); + ret = FetchDeviceAndRoute(AudioStreamDeviceChangeReason::OVERRODE); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "FetchDeviceAndRoute failed"); + + return SUCCESS; +} + +std::vector> AudioCoreService::GetAvailableDevices(AudioDeviceUsage usage) +{ + std::vector> audioDeviceDescriptors; + audioDeviceDescriptors = audioDeviceManager_.GetAvailableDevicesByUsage(usage); + return audioDeviceDescriptors; +} + +std::vector> AudioCoreService::GetAvailableMicrophones() +{ + return audioMicrophoneDescriptor_.GetAvailableMicrophones(); +} + +std::vector> AudioCoreService::GetAudioCapturerMicrophoneDescriptors(int32_t sessionId) +{ + return audioMicrophoneDescriptor_.GetAudioCapturerMicrophoneDescriptors(sessionId); +} + +int32_t AudioCoreService::GetCurrentRendererChangeInfos(vector> + &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission) +{ + int32_t status = streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos); + CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status, + "AudioPolicyServer:: Get renderer change info failed"); + + std::vector> outputDevices = + audioConnectedDevice_.GetDevicesInner(OUTPUT_DEVICES_FLAG); + DeviceType activeDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType(); + DeviceRole activeDeviceRole = OUTPUT_DEVICE; + std::string activeDeviceMac = audioActiveDevice_.GetCurrentOutputDeviceMacAddr(); + + const auto& itr = std::find_if(outputDevices.begin(), outputDevices.end(), + [&activeDeviceType, &activeDeviceRole, &activeDeviceMac](const std::shared_ptr &desc) { + if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) { + // This A2DP device is not the active A2DP device. Skip it. + return activeDeviceType != DEVICE_TYPE_BLUETOOTH_A2DP || desc->macAddress_ == activeDeviceMac; + } + return false; + }); + + if (itr != outputDevices.end()) { + size_t rendererInfosSize = audioRendererChangeInfos.size(); + for (size_t i = 0; i < rendererInfosSize; i++) { + UpdateRendererInfoWhenNoPermission(audioRendererChangeInfos[i], hasSystemPermission); + audioDeviceCommon_.UpdateDeviceInfo(audioRendererChangeInfos[i]->outputDeviceInfo, *itr, + hasBTPermission, hasSystemPermission); + } + } + return status; +} + +int32_t AudioCoreService::GetCurrentCapturerChangeInfos( + vector> &audioCapturerChangeInfos, + bool hasBTPermission, bool hasSystemPermission) +{ + int status = streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos); + CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status, + "AudioPolicyServer:: Get capturer change info failed"); + + std::vector> inputDevices = GetDevices(INPUT_DEVICES_FLAG); + DeviceType activeDeviceType = audioActiveDevice_.GetCurrentInputDeviceType(); + DeviceRole activeDeviceRole = INPUT_DEVICE; + for (std::shared_ptr desc : inputDevices) { + if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) { + size_t capturerInfosSize = audioCapturerChangeInfos.size(); + for (size_t i = 0; i < capturerInfosSize; i++) { + UpdateCapturerInfoWhenNoPermission(audioCapturerChangeInfos[i], hasSystemPermission); + audioDeviceCommon_.UpdateDeviceInfo(audioCapturerChangeInfos[i]->inputDeviceInfo, desc, + hasBTPermission, hasSystemPermission); + } + break; + } + } + return status; +} + +std::vector> AudioCoreService::GetExcludedDevices( + AudioDeviceUsage audioDevUsage) +{ + return audioStateManager_.GetExcludedDevices(audioDevUsage); +} + +void AudioCoreService::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo, + const AudioStreamDeviceChangeReasonExt reason) +{ + AUDIO_WARNING_LOG("Not Supported"); +} + +void AudioCoreService::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo) +{ + AUDIO_WARNING_LOG("Not Supported"); +} + +int32_t AudioCoreService::ExcludeOutputDevices(AudioDeviceUsage audioDevUsage, + std::vector> &audioDeviceDescriptors) +{ + return audioRecoveryDevice_.ExcludeOutputDevices(audioDevUsage, audioDeviceDescriptors); +} + +int32_t AudioCoreService::UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage, + std::vector> &audioDeviceDescriptors) +{ + return audioRecoveryDevice_.UnexcludeOutputDevices(audioDevUsage, audioDeviceDescriptors); +} + +int32_t AudioCoreService::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, + const sptr &object, const int32_t apiVersion) +{ + if (mode == AUDIO_MODE_RECORD) { + audioMicrophoneDescriptor_.AddAudioCapturerMicrophoneDescriptor( + streamChangeInfo.audioCapturerChangeInfo.sessionId, DEVICE_TYPE_NONE); + if (apiVersion > 0 && apiVersion < API_11) { + audioDeviceCommon_.UpdateDeviceInfo(streamChangeInfo.audioCapturerChangeInfo.inputDeviceInfo, + std::make_shared(audioActiveDevice_.GetCurrentInputDevice()), false, false); + } + } else if (apiVersion > 0 && apiVersion < API_11) { + audioDeviceCommon_.UpdateDeviceInfo(streamChangeInfo.audioRendererChangeInfo.outputDeviceInfo, + std::make_shared(audioActiveDevice_.GetCurrentOutputDevice()), false, false); + } + return streamCollector_.RegisterTracker(mode, streamChangeInfo, object); +} + +int32_t AudioCoreService::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo) +{ + HandleAudioCaptureState(mode, streamChangeInfo); + + int32_t ret = streamCollector_.UpdateTracker(mode, streamChangeInfo); + + const auto &rendererState = streamChangeInfo.audioRendererChangeInfo.rendererState; + if (rendererState == RENDERER_PREPARED || rendererState == RENDERER_NEW || rendererState == RENDERER_INVALID) { + return ret; // only update tracker in new and prepared + } + + audioDeviceCommon_.UpdateTracker(mode, streamChangeInfo, rendererState); + + if (audioA2dpOffloadManager_) { + audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream(audioActiveDevice_.GetCurrentOutputDeviceType()); + } + + SendA2dpConnectedWhileRunning(rendererState, streamChangeInfo.audioRendererChangeInfo.sessionId); + return ret; +} + +void AudioCoreService::RegisteredTrackerClientDied(pid_t uid) +{ + UpdateDefaultOutputDeviceWhenStopping(static_cast(uid)); + + audioMicrophoneDescriptor_.RemoveAudioCapturerMicrophoneDescriptor(static_cast(uid)); + streamCollector_.RegisteredTrackerClientDied(static_cast(uid)); + + audioDeviceCommon_.ClientDiedDisconnectScoNormal(); + audioDeviceCommon_.ClientDiedDisconnectScoRecognition(); + + if (!streamCollector_.ExistStreamForPipe(PIPE_TYPE_OFFLOAD)) { + audioOffloadStream_.DynamicUnloadOffloadModule(); + } + + if (!streamCollector_.ExistStreamForPipe(PIPE_TYPE_MULTICHANNEL)) { + audioOffloadStream_.UnloadMchModule(); + } +} + +bool AudioCoreService::ConnectServiceAdapter() +{ + return audioPolicyManager_.ConnectServiceAdapter(); +} + +void AudioCoreService::OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName) +{ + audioDeviceManager_.OnReceiveBluetoothEvent(macAddress, deviceName); + audioConnectedDevice_.SetDisplayName(macAddress, deviceName); +} + +int32_t AudioCoreService::SelectOutputDevice(sptr audioRendererFilter, + std::vector> selectedDesc) +{ + return audioRecoveryDevice_.SelectOutputDevice(audioRendererFilter, selectedDesc); +} + +int32_t AudioCoreService::SelectInputDevice(sptr audioCapturerFilter, + std::vector> selectedDesc) +{ + return audioRecoveryDevice_.SelectInputDevice(audioCapturerFilter, selectedDesc); +} + +void AudioCoreService::NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value) +{ + AUDIO_INFO_LOG("device<%{public}s> condition:%{public}s value:%{public}s", + GetEncryptStr(networkId).c_str(), condition.c_str(), value.c_str()); + + vector sinkInputs; + audioPolicyManager_.GetAllSinkInputs(sinkInputs); + vector targetSinkInputs = {}; + for (auto sinkInput : sinkInputs) { + if (sinkInput.sinkName == networkId) { + targetSinkInputs.push_back(sinkInput); + } + } + AUDIO_DEBUG_LOG("move [%{public}zu] of all [%{public}zu]sink-inputs to local.", + targetSinkInputs.size(), sinkInputs.size()); + std::shared_ptr localDevice = std::make_shared(); + CHECK_AND_RETURN_LOG(localDevice != nullptr, "Device error: null device."); + localDevice->networkId_ = LOCAL_NETWORK_ID; + localDevice->deviceRole_ = DeviceRole::OUTPUT_DEVICE; + localDevice->deviceType_ = DeviceType::DEVICE_TYPE_SPEAKER; + + int32_t ret; + AudioDeviceDescriptor curOutputDeviceDesc = audioActiveDevice_.GetCurrentOutputDevice(); + if (localDevice->deviceType_ != curOutputDeviceDesc.deviceType_) { + AUDIO_WARNING_LOG("device[%{public}d] not active, use device[%{public}d] instead.", + static_cast(localDevice->deviceType_), static_cast(curOutputDeviceDesc.deviceType_)); + ret = audioDeviceCommon_.MoveToLocalOutputDevice(targetSinkInputs, + std::make_shared(curOutputDeviceDesc)); + } else { + ret = audioDeviceCommon_.MoveToLocalOutputDevice(targetSinkInputs, localDevice); + } + CHECK_AND_RETURN_LOG((ret == SUCCESS), "MoveToLocalOutputDevice failed!"); + + // Suspend device, notify audio stream manager that device has been changed. + ret = audioPolicyManager_.SuspendAudioDevice(networkId, true); + CHECK_AND_RETURN_LOG((ret == SUCCESS), "SuspendAudioDevice failed!"); + + std::vector> desc = {}; + desc.push_back(localDevice); + UpdateTrackerDeviceChange(desc); + audioDeviceCommon_.OnPreferredOutputDeviceUpdated(curOutputDeviceDesc); + AUDIO_DEBUG_LOG("Success"); +} + +int32_t AudioCoreService::OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo, + AudioStreamInfo streamInfo) +{ + return audioCapturerSession_.OnCapturerSessionAdded(sessionID, sessionInfo, streamInfo); +} + +void AudioCoreService::OnCapturerSessionRemoved(uint64_t sessionID) +{ + audioCapturerSession_.OnCapturerSessionRemoved(sessionID); +} + +void AudioCoreService::SetDisplayName(const std::string &deviceName, bool isLocalDevice) +{ + audioConnectedDevice_.SetDisplayName(deviceName, isLocalDevice); +} + +int32_t AudioCoreService::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason) +{ + FetchOutputDeviceAndRoute(reason); + FetchInputDeviceAndRoute(); + + // update a2dp offload + audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream(); + return SUCCESS; +} + +// No lock +int32_t AudioCoreService::SetAudioDeviceAnahsCallback(const sptr &object) +{ + return deviceStatusListener_->SetAudioDeviceAnahsCallback(object); +} + +int32_t AudioCoreService::UnsetAudioDeviceAnahsCallback() +{ + return deviceStatusListener_->UnsetAudioDeviceAnahsCallback(); +} + +void AudioCoreService::OnUpdateAnahsSupport(std::string anahsShowType) +{ + AUDIO_INFO_LOG("OnUpdateAnahsSupport show type: %{public}s", anahsShowType.c_str()); + deviceStatusListener_->UpdateAnahsPlatformType(anahsShowType); +} + +void AudioCoreService::RegisterBluetoothListener() +{ +#ifdef BLUETOOTH_ENABLE + AUDIO_INFO_LOG("Enter"); + Bluetooth::RegisterDeviceObserver(deviceStatusListener_->deviceObserver_); + if (isBtListenerRegistered) { + AUDIO_INFO_LOG("audio policy service already register bt listerer, return"); + return; + } + Bluetooth::AudioA2dpManager::RegisterBluetoothA2dpListener(); + Bluetooth::AudioHfpManager::RegisterBluetoothScoListener(); + isBtListenerRegistered = true; + const sptr gsp = RegisterBluetoothDeathCallback(); + AudioPolicyUtils::GetInstance().SetBtConnecting(true); + Bluetooth::AudioA2dpManager::CheckA2dpDeviceReconnect(); + Bluetooth::AudioHfpManager::CheckHfpDeviceReconnect(); + AudioPolicyUtils::GetInstance().SetBtConnecting(false); +#endif +} + +void AudioCoreService::UnregisterBluetoothListener() +{ +#ifdef BLUETOOTH_ENABLE + AUDIO_INFO_LOG("Enter"); + Bluetooth::UnregisterDeviceObserver(); + Bluetooth::AudioA2dpManager::UnregisterBluetoothA2dpListener(); + Bluetooth::AudioHfpManager::UnregisterBluetoothScoListener(); + isBtListenerRegistered = false; +#endif +} + +void AudioCoreService::ConfigDistributedRoutingRole( + const std::shared_ptr descriptor, CastType type) +{ + StoreDistributedRoutingRoleInfo(descriptor, type); + FetchDeviceAndRoute(AudioStreamDeviceChangeReason::OVERRODE); +} + +int32_t AudioCoreService::SetRingerMode(AudioRingerMode ringMode) +{ + int32_t result = audioPolicyManager_.SetRingerMode(ringMode); + if (result == SUCCESS) { + if (Util::IsRingerAudioScene(audioSceneManager_.GetAudioScene(true))) { + AUDIO_INFO_LOG("fetch output device after switch new ringmode."); + FetchOutputDeviceAndRoute(); + } + Volume vol = {false, 1.0f, 0}; + DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType(); + vol.isMute = (ringMode == RINGER_MODE_NORMAL) ? false : true; + vol.volumeInt = static_cast(GetSystemVolumeLevel(STREAM_RING)); + vol.volumeFloat = GetSystemVolumeInDb(STREAM_RING, vol.volumeInt, curOutputDeviceType); + audioVolumeManager_.SetSharedVolume(STREAM_RING, curOutputDeviceType, vol); + } + return result; +} + +int32_t AudioCoreService::FetchOutputDeviceAndRoute(const AudioStreamDeviceChangeReasonExt reason) +{ + std::vector> outputStreamDescs = pipeManager_->GetAllOutputStreamDescs(); + AUDIO_INFO_LOG("Output stream size: %{public}zu", outputStreamDescs.size()); + + CheckModemScene(reason); + + if (outputStreamDescs.empty()) { + AUDIO_PRERELEASE_LOGI("when no stream in"); + vector> descs = + audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_MEDIA, -1); + CHECK_AND_RETURN_RET_LOG(!descs.empty(), ERROR, "descs is empty"); + AudioDeviceDescriptor tmpOutputDeviceDesc = audioActiveDevice_.GetCurrentOutputDevice(); + if (descs.front()->deviceType_ == DEVICE_TYPE_NONE || IsSameDevice(descs.front(), tmpOutputDeviceDesc)) { + AUDIO_DEBUG_LOG("output device is not change"); + return SUCCESS; + } + audioActiveDevice_.SetCurrentOutputDevice(*descs.front()); + AUDIO_DEBUG_LOG("currentActiveDevice %{public}d", audioActiveDevice_.GetCurrentOutputDeviceType()); + audioVolumeManager_.SetVolumeForSwitchDevice(descs.front()->deviceType_); + if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { + SwitchActiveA2dpDevice(std::make_shared(*descs.front())); + } + OnPreferredOutputDeviceUpdated(audioActiveDevice_.GetCurrentOutputDevice()); + } + + for (auto streamDesc : outputStreamDescs) { + streamDesc->oldDeviceDescs_ = streamDesc->newDeviceDescs_; + streamDesc->newDeviceDescs_ = + audioRouterCenter_.FetchOutputDevices(streamDesc->rendererInfo_.streamUsage, GetRealUid(streamDesc)); + AUDIO_INFO_LOG("DeviceType %{public}d", streamDesc->newDeviceDescs_[0]->deviceType_); + + // handle a2dp + std::string encryptMacAddr = + GetEncryptAddr(streamDesc->newDeviceDescs_.front()->macAddress_); + int32_t bluetoothFetchResult = + BluetoothDeviceFetchOutputHandle(streamDesc->newDeviceDescs_.front(), reason, encryptMacAddr); + if (bluetoothFetchResult == BLUETOOTH_FETCH_RESULT_CONTINUE || + bluetoothFetchResult == BLUETOOTH_FETCH_RESULT_ERROR) { + continue; + } + if (streamDesc->newDeviceDescs_.front()->deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) { + audioEcManager_.ActivateArmDevice( + streamDesc->newDeviceDescs_.front()->macAddress_, streamDesc->newDeviceDescs_.front()->deviceRole_); + } + SetPlaybackStreamFlag(streamDesc); + AUDIO_INFO_LOG("Will use audio flag: %{public}u", streamDesc->audioFlag_); + } + + int32_t ret = FetchRendererPipesAndExecute(outputStreamDescs, reason); + return ret; +} + +int32_t AudioCoreService::FetchInputDeviceAndRoute() +{ + std::vector> inputStreamDescs = pipeManager_->GetAllInputStreamDescs(); + for (auto streamDesc : inputStreamDescs) { + streamDesc->oldDeviceDescs_ = streamDesc->newDeviceDescs_; + streamDesc->newDeviceDescs_.clear(); + std::shared_ptr inputDeviceDesc = + audioRouterCenter_.FetchInputDevice(streamDesc->capturerInfo_.sourceType, GetRealUid(streamDesc)); + streamDesc->newDeviceDescs_.push_back(inputDeviceDesc); + AUDIO_INFO_LOG("device type: %{public}d", inputDeviceDesc->deviceType_); + SetRecordStreamFlag(streamDesc); + } + + int32_t ret = FetchCapturerPipesAndExecute(inputStreamDescs); + return ret; +} + +void AudioCoreService::SetAudioServerProxy() +{ + AUDIO_INFO_LOG("SetAudioServerProxy Start"); + const sptr gsp = AudioServerProxy::GetInstance().GetAudioServerProxy(); + CHECK_AND_RETURN_LOG(gsp != nullptr, "SetAudioServerProxy, Audio Server Proxy is null"); + audioPolicyManager_.SetAudioServerProxy(gsp); +} + +#ifdef BLUETOOTH_ENABLE +const sptr AudioCoreService::RegisterBluetoothDeathCallback() +{ + lock_guard lock(g_btProxyMutex); + if (g_btProxy == nullptr) { + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + CHECK_AND_RETURN_RET_LOG(samgr != nullptr, nullptr, + "get sa manager failed"); + sptr object = samgr->GetSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID); + CHECK_AND_RETURN_RET_LOG(object != nullptr, nullptr, + "get audio service remote object failed"); + g_btProxy = iface_cast(object); + CHECK_AND_RETURN_RET_LOG(g_btProxy != nullptr, nullptr, + "get audio service proxy failed"); + + // register death recipent + sptr asDeathRecipient = + new(std::nothrow) AudioServerDeathRecipient(getpid(), getuid()); + if (asDeathRecipient != nullptr) { + asDeathRecipient->SetNotifyCb([] (pid_t pid, pid_t uid) { + AudioCoreService::BluetoothServiceCrashedCallback(pid, uid); + }); + bool result = object->AddDeathRecipient(asDeathRecipient); + if (!result) { + AUDIO_ERR_LOG("failed to add deathRecipient"); + } + } + } + sptr gasp = g_btProxy; + return gasp; +} + +void AudioCoreService::BluetoothServiceCrashedCallback(pid_t pid, pid_t uid) +{ + AUDIO_INFO_LOG("Bluetooth sa crashed, will restore proxy in next call"); + lock_guard lock(g_btProxyMutex); + g_btProxy = nullptr; + isBtListenerRegistered = false; + Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSink(); + Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSource(); + Bluetooth::AudioHfpManager::DisconnectBluetoothHfpSink(); +} +#endif +} // namespace AudioStandard +} // namespace OHOS diff --git a/services/audio_policy/services/core/src/audio_core_service_entry.cpp b/services/audio_policy/services/core/src/audio_core_service_entry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fdb625c3f875a689c312839e2433038af26f5a22 --- /dev/null +++ b/services/audio_policy/services/core/src/audio_core_service_entry.cpp @@ -0,0 +1,423 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef LOG_TAG +#define LOG_TAG "AudioCoreServiceEntry" +#endif + +#include "audio_core_service.h" +#include "audio_server_proxy.h" +#include "audio_usb_manager.h" + +namespace OHOS { +namespace AudioStandard { +namespace { +static constexpr int64_t WAIT_LOAD_DEFAULT_DEVICE_TIME_MS = 200; // 200ms +static constexpr int32_t RETRY_TIMES = 25; +} +AudioCoreService::EventEntry::EventEntry(std::shared_ptr coreService) : coreService_(coreService) +{ + AUDIO_INFO_LOG("Ctor"); +} + +void AudioCoreService::EventEntry::RegistCoreService() +{ + AUDIO_INFO_LOG("In"); + coreService_->SetAudioServerProxy(); + sptr wrapper = new(std::nothrow) CoreServiceProviderWrapper(this); + CHECK_AND_RETURN_LOG(wrapper != nullptr, "Get null CoreServiceProviderWrapper"); + sptr object = wrapper->AsObject(); + CHECK_AND_RETURN_LOG(object != nullptr, "AsObject is nullptr"); + + int32_t ret = AudioServerProxy::GetInstance().RegistCoreServiceProviderProxy(object); + AUDIO_INFO_LOG("Result:%{public}d", ret); +} + +int32_t AudioCoreService::EventEntry::CreateRendererClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) +{ + std::lock_guard lock(eventMutex_); + coreService_->CreateRendererClient(streamDesc, flag, sessionId); + return SUCCESS; +} + +int32_t AudioCoreService::EventEntry::CreateCapturerClient( + std::shared_ptr streamDesc, uint32_t &flag, uint32_t &sessionId) +{ + std::lock_guard lock(eventMutex_); + coreService_->CreateCapturerClient(streamDesc, flag, sessionId); + return SUCCESS; +} + +int32_t AudioCoreService::EventEntry::UpdateSessionOperation(uint32_t sessionId, SessionOperation operation) +{ + std::lock_guard lock(eventMutex_); + switch (operation) { + case SESSION_OPERATION_START: + return coreService_->StartClient(sessionId); + case SESSION_OPERATION_PAUSE: + return coreService_->PauseClient(sessionId); + case SESSION_OPERATION_STOP: + return coreService_->StopClient(sessionId); + case SESSION_OPERATION_RELEASE: + return coreService_->ReleaseClient(sessionId); + default: + return SUCCESS; + } +} + +std::string AudioCoreService::EventEntry::GetAdapterNameBySessionId(uint32_t sessionId) +{ + std::lock_guard lock(eventMutex_); + return coreService_->GetAdapterNameBySessionId(sessionId); +} + +int32_t AudioCoreService::EventEntry::GetProcessDeviceInfoBySessionId( + uint32_t sessionId, AudioDeviceDescriptor &deviceInfo) +{ + std::lock_guard lock(eventMutex_); + return coreService_->GetProcessDeviceInfoBySessionId(sessionId, deviceInfo); +} + +uint32_t AudioCoreService::EventEntry::GenerateSessionId() +{ + return coreService_->GenerateSessionId(); +} + +int32_t AudioCoreService::EventEntry::SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionID, + const StreamUsage streamUsage, bool isRunning) +{ + int32_t ret = coreService_->SetDefaultOutputDevice(deviceType, sessionID, streamUsage, isRunning); + return ret; +} + +// device status listener +void AudioCoreService::EventEntry::OnDeviceStatusUpdated( + DeviceType devType, bool isConnected, const std::string& macAddress, + const std::string& deviceName, const AudioStreamInfo& streamInfo, DeviceRole role, bool hasPair) +{ + std::lock_guard lock(eventMutex_); + coreService_->OnDeviceStatusUpdated(devType, isConnected, macAddress, deviceName, streamInfo, role, hasPair); +} + +void AudioCoreService::EventEntry::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, bool isConnected) +{ + std::lock_guard lock(eventMutex_); + coreService_->OnDeviceStatusUpdated(updatedDesc, isConnected); +} + +void AudioCoreService::EventEntry::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop) +{ + std::lock_guard lock(eventMutex_); + coreService_->OnDeviceStatusUpdated(statusInfo, isStop); +} + +void AudioCoreService::EventEntry::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status) +{ + CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type"); + std::lock_guard lock(eventMutex_); + coreService_->OnMicrophoneBlockedUpdate(devType, status); +} + +void AudioCoreService::EventEntry::OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected) +{ + std::lock_guard lock(eventMutex_); + coreService_->OnPnpDeviceStatusUpdated(desc, isConnected); +} + +void AudioCoreService::EventEntry::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress, + const std::string &deviceName, const AudioStreamInfo &streamInfo) +{ + coreService_->OnDeviceConfigurationChanged(deviceType, macAddress, deviceName, streamInfo); +} + +void AudioCoreService::EventEntry::OnServiceConnected(AudioServiceIndex serviceIndex) +{ + AUDIO_INFO_LOG("[module_load]::OnServiceConnected for [%{public}d]", serviceIndex); + CHECK_AND_RETURN_LOG(serviceIndex >= HDI_SERVICE_INDEX && serviceIndex <= AUDIO_SERVICE_INDEX, "invalid index"); + + // If audio service or hdi service is not ready, donot load default modules + std::lock_guard lock(coreService_->serviceFlagMutex_); + coreService_->serviceFlag_.set(serviceIndex, true); + if (coreService_->serviceFlag_.count() != MIN_SERVICE_COUNT) { + AUDIO_INFO_LOG("[module_load]::hdi service or audio service not up. Cannot load default module now"); + return; + } + + std::unique_lock serviceLock(eventMutex_); + int32_t ret = coreService_->OnServiceConnected(serviceIndex); + serviceLock.unlock(); + if (ret == SUCCESS) { +#ifdef USB_ENABLE + AudioUsbManager::GetInstance().Init(this); +#endif + coreService_->audioEffectService_.SetMasterSinkAvailable(); + } + // RegisterBluetoothListener() will be called when bluetooth_host is online + // load hdi-effect-model + AudioServerProxy::GetInstance().LoadHdiEffectModelProxy(); + AudioServerProxy::GetInstance().NotifyAudioPolicyReady(); +} + +void AudioCoreService::EventEntry::OnServiceDisconnected(AudioServiceIndex serviceIndex) +{ + AUDIO_WARNING_LOG("Service index [%{public}d]", serviceIndex); +} + +void AudioCoreService::EventEntry::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress) +{ + std::lock_guard lock(eventMutex_); + coreService_->OnForcedDeviceSelected(devType, macAddress); +} + +int32_t AudioCoreService::EventEntry::SetAudioScene(AudioScene audioScene) +{ + std::lock_guard lock(eventMutex_); + coreService_->SetAudioScene(audioScene); + return SUCCESS; +} + +bool AudioCoreService::EventEntry::IsArmUsbDevice(const AudioDeviceDescriptor &deviceDesc) +{ + std::shared_lock lock(eventMutex_); + return coreService_->IsArmUsbDevice(deviceDesc); +} + +std::vector> AudioCoreService::EventEntry::GetDevices(DeviceFlag deviceFlag) +{ + std::shared_lock lock(eventMutex_); + return coreService_->GetDevices(deviceFlag); +} + +int32_t AudioCoreService::EventEntry::SetDeviceActive(InternalDeviceType deviceType, bool active, const int32_t pid) +{ + std::lock_guard lock(eventMutex_); + return coreService_->SetDeviceActive(deviceType, active, pid); +} + +std::vector> AudioCoreService::EventEntry::GetPreferredOutputDeviceDescriptors( + AudioRendererInfo &rendererInfo, std::string networkId) +{ + std::lock_guard lock(eventMutex_); + return coreService_->GetPreferredOutputDeviceDescInner(rendererInfo, networkId); +} + +std::vector> AudioCoreService::EventEntry::GetPreferredInputDeviceDescriptors( + AudioCapturerInfo &captureInfo, std::string networkId) +{ + std::shared_lock lock(eventMutex_); + return coreService_->GetPreferredInputDeviceDescInner(captureInfo, networkId); +} + +std::shared_ptr AudioCoreService::EventEntry::GetActiveBluetoothDevice() +{ + std::shared_lock lock(eventMutex_); + return coreService_->GetActiveBluetoothDevice(); +} + +void AudioCoreService::EventEntry::OnDeviceInfoUpdated( + AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command) +{ + std::lock_guard lock(eventMutex_); + coreService_->OnDeviceInfoUpdated(desc, command); +} + +int32_t AudioCoreService::EventEntry::SetCallDeviceActive( + InternalDeviceType deviceType, bool active, std::string address) +{ + std::lock_guard lock(eventMutex_); + coreService_->SetCallDeviceActive(deviceType, active, address); + return SUCCESS; +} + +std::vector> AudioCoreService::EventEntry::GetAvailableDevices(AudioDeviceUsage usage) +{ + std::shared_lock lock(eventMutex_); + return coreService_->GetAvailableDevices(usage); +} + +int32_t AudioCoreService::EventEntry::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, + const sptr &object, const int32_t apiVersion) +{ + std::lock_guard lock(eventMutex_); + return coreService_->RegisterTracker(mode, streamChangeInfo, object, apiVersion); +} + +int32_t AudioCoreService::EventEntry::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo) +{ + std::lock_guard lock(eventMutex_); + return coreService_->UpdateTracker(mode, streamChangeInfo); +} + +void AudioCoreService::EventEntry::RegisteredTrackerClientDied(pid_t uid) +{ + std::lock_guard lock(eventMutex_); + coreService_->RegisteredTrackerClientDied(uid); +} + +bool AudioCoreService::EventEntry::ConnectServiceAdapter() +{ + bool ret = coreService_->ConnectServiceAdapter(); + CHECK_AND_RETURN_RET_LOG(ret, false, "Error in connecting to audio service adapter"); + + OnServiceConnected(AudioServiceIndex::AUDIO_SERVICE_INDEX); + + return true; +} + +vector> AudioCoreService::EventEntry::GetAvailableMicrophones() +{ + std::lock_guard lock(eventMutex_); + return coreService_->GetAvailableMicrophones(); +} + +vector> AudioCoreService::EventEntry::GetAudioCapturerMicrophoneDescriptors( + int32_t sessionId) +{ + std::shared_lock lock(eventMutex_); + return coreService_->GetAudioCapturerMicrophoneDescriptors(sessionId); +} + +void AudioCoreService::EventEntry::OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName) +{ + std::lock_guard lock(eventMutex_); + coreService_->OnReceiveBluetoothEvent(macAddress, deviceName); +} + +int32_t AudioCoreService::EventEntry::SelectOutputDevice(sptr audioRendererFilter, + std::vector> selectedDesc) +{ + Trace trace("AudioCoreService::SelectOutputDevice"); + std::lock_guard lock(eventMutex_); + return coreService_->SelectOutputDevice(audioRendererFilter, selectedDesc); +} + +int32_t AudioCoreService::EventEntry::SelectInputDevice(sptr audioCapturerFilter, + std::vector> selectedDesc) +{ + Trace trace("AudioCoreService::SelectInputDevice"); + std::lock_guard lock(eventMutex_); + return coreService_->SelectInputDevice(audioCapturerFilter, selectedDesc); +} + +int32_t AudioCoreService::EventEntry::GetCurrentRendererChangeInfos(vector> + &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission) +{ + std::shared_lock lock(eventMutex_); + return coreService_->GetCurrentRendererChangeInfos(audioRendererChangeInfos, hasBTPermission, + hasSystemPermission); +} + +int32_t AudioCoreService::EventEntry::GetCurrentCapturerChangeInfos(vector> + &audioCapturerChangeInfos, bool hasBTPermission, bool hasSystemPermission) +{ + return coreService_->GetCurrentCapturerChangeInfos(audioCapturerChangeInfos, hasBTPermission, + hasSystemPermission); +} + +void AudioCoreService::EventEntry::NotifyRemoteRenderState( + std::string networkId, std::string condition, std::string value) +{ + std::lock_guard lock(eventMutex_); + coreService_->NotifyRemoteRenderState(networkId, condition, value); +} + +int32_t AudioCoreService::EventEntry::OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo, + AudioStreamInfo streamInfo) +{ + std::lock_guard lock(eventMutex_); + return coreService_->OnCapturerSessionAdded(sessionID, sessionInfo, streamInfo); +} + +void AudioCoreService::EventEntry::OnCapturerSessionRemoved(uint64_t sessionID) +{ + std::lock_guard lock(eventMutex_); + coreService_->OnCapturerSessionRemoved(sessionID); +} + +void AudioCoreService::EventEntry::SetDisplayName(const std::string &deviceName, bool isLocalDevice) +{ + std::lock_guard lock(eventMutex_); + coreService_->SetDisplayName(deviceName, isLocalDevice); +} + +int32_t AudioCoreService::EventEntry::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason) +{ + std::lock_guard lock(eventMutex_); + return coreService_->TriggerFetchDevice(reason); +} + +std::vector> AudioCoreService::EventEntry::GetVolumeGroupInfos() +{ + std::vector> infos = {}; + for (int32_t i = 0; i < RETRY_TIMES; i++) { + std::shared_lock lock(eventMutex_); + if (coreService_->GetVolumeGroupInfos(infos)) { + return infos; + } else { + lock.unlock(); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_LOAD_DEFAULT_DEVICE_TIME_MS)); + } + } + AUDIO_ERR_LOG("timeout"); + return infos; +} + +void AudioCoreService::EventEntry::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo, + const AudioStreamDeviceChangeReasonExt reason) +{ + AUDIO_INFO_LOG("Not support"); +} + +void AudioCoreService::EventEntry::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo) +{ + AUDIO_INFO_LOG("Not support"); +} + +int32_t AudioCoreService::EventEntry::ExcludeOutputDevices(AudioDeviceUsage audioDevUsage, + std::vector> &audioDeviceDescriptors) +{ + Trace trace("AudioCoreService::EventEntry::ExcludeOutputDevices"); + std::lock_guard lock(eventMutex_); + return coreService_->ExcludeOutputDevices(audioDevUsage, audioDeviceDescriptors); +} + +int32_t AudioCoreService::EventEntry::UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage, + std::vector> &audioDeviceDescriptors) +{ + std::lock_guard lock(eventMutex_); + return coreService_->UnexcludeOutputDevices(audioDevUsage, audioDeviceDescriptors); +} + +std::vector> AudioCoreService::EventEntry::GetExcludedDevices( + AudioDeviceUsage audioDevUsage) +{ + std::lock_guard lock(eventMutex_); + return coreService_->GetExcludedDevices(audioDevUsage); +} + +int32_t AudioCoreService::EventEntry::GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo, + const std::string &bundleName) +{ + std::lock_guard lock(eventMutex_); + return coreService_->GetPreferredOutputStreamType(rendererInfo, bundleName); +} + +int32_t AudioCoreService::EventEntry::GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo) +{ + std::lock_guard lock(eventMutex_); + return coreService_->GetPreferredInputStreamType(capturerInfo); +} +} +} diff --git a/services/audio_policy/services/core/src/audio_core_service_private.cpp b/services/audio_policy/services/core/src/audio_core_service_private.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ebef2eef2dcd9df8bf84cd04d61beafebfeff49 --- /dev/null +++ b/services/audio_policy/services/core/src/audio_core_service_private.cpp @@ -0,0 +1,1443 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef LOG_TAG +#define LOG_TAG "AudioCoreServicePrivate" +#endif + +#include "audio_core_service.h" +#include "system_ability.h" +#include "audio_server_proxy.h" +#include "audio_policy_utils.h" +#include "iservice_registry.h" +#include "hdi_adapter_info.h" +#include "audio_usb_manager.h" +#include "data_share_observer_callback.h" +#include "audio_spatialization_service.h" + +namespace OHOS { +namespace AudioStandard { +namespace { +static const int32_t MEDIA_SERVICE_UID = 1013; +const int32_t DATA_LINK_CONNECTED = 11; +const uint32_t FIRST_SESSIONID = 100000; +constexpr uint32_t MAX_VALID_SESSIONID = UINT32_MAX - FIRST_SESSIONID; +static const int VOLUME_LEVEL_DEFAULT_SIZE = 3; +static const int32_t BLUETOOTH_FETCH_RESULT_DEFAULT = 0; +static const int32_t BLUETOOTH_FETCH_RESULT_CONTINUE = 1; +static const int32_t BLUETOOTH_FETCH_RESULT_ERROR = 2; +static const uint32_t BT_BUFFER_ADJUSTMENT_FACTOR = 50; +} + +static const std::vector SourceNames = { + std::string(PRIMARY_MIC), + std::string(BLUETOOTH_MIC), + std::string(USB_MIC), + std::string(PRIMARY_WAKEUP), + std::string(FILE_SOURCE) +}; + +std::string AudioCoreService::GetEncryptAddr(const std::string &addr) +{ + const int32_t START_POS = 6; + const int32_t END_POS = 13; + const int32_t ADDRESS_STR_LEN = 17; + if (addr.empty() || addr.length() != ADDRESS_STR_LEN) { + return std::string(""); + } + std::string tmp = "**:**:**:**:**:**"; + std::string out = addr; + for (int i = START_POS; i <= END_POS; i++) { + out[i] = tmp[i]; + } + return out; +} + +int32_t AudioCoreService::FetchRendererPipesAndExecute( + std::vector> &streamDescs, const AudioStreamDeviceChangeReasonExt reason) +{ + std::vector> pipeInfos = audioPipeSelector_->FetchPipesAndExecute(streamDescs); + uint32_t audioFlag; + for (auto pipeInfo : pipeInfos) { + AUDIO_INFO_LOG("Pipe name: %{public}s, device class: %{public}s, action: %{public}d", + pipeInfo->moduleInfo_.adapterName.c_str(), pipeInfo->moduleInfo_.className.c_str(), pipeInfo->pipeAction_); + if (pipeInfo->pipeAction_ == PIPE_ACTION_UPDATE) { + ProcessOutputPipeUpdate(pipeInfo, audioFlag); + } else if (pipeInfo->pipeAction_ == PIPE_ACTION_NEW) { + ProcessOutputPipeNew(pipeInfo, audioFlag); + } else if (pipeInfo->pipeAction_ == PIPE_ACTION_DEFAULT) { + // Do nothing + } + } + pipeManager_->UpdateRendererPipeInfos(pipeInfos); + RemoveUnusedPipe(); + return SUCCESS; +} + +int32_t AudioCoreService::FetchCapturerPipesAndExecute(std::vector> &streamDescs) +{ + uint32_t audioFlag; + std::vector> pipeInfos = audioPipeSelector_->FetchPipesAndExecute(streamDescs); + for (auto pipeInfo : pipeInfos) { + AUDIO_INFO_LOG("Pipe name: %{public}s, class: %{public}s, route: %{public}u, action: %{public}d", + pipeInfo->moduleInfo_.adapterName.c_str(), pipeInfo->moduleInfo_.className.c_str(), + pipeInfo->routeFlag_, pipeInfo->pipeAction_); + if (pipeInfo->pipeAction_ == PIPE_ACTION_UPDATE) { + ProcessInputPipeUpdate(pipeInfo, audioFlag); + } else if (pipeInfo->pipeAction_ == PIPE_ACTION_NEW) { // new + ProcessInputPipeNew(pipeInfo, audioFlag); + } else if (pipeInfo->pipeAction_ == PIPE_ACTION_DEFAULT) { // DEFAULT + // Do nothing + } + } + pipeManager_->UpdateCapturerPipeInfos(pipeInfos); + RemoveUnusedPipe(); + return SUCCESS; +} + +int32_t AudioCoreService::HandleScoInputDeviceFetched(std::shared_ptr streamDesc) +{ +#ifdef BLUETOOTH_ENABLE + AUDIO_INFO_LOG("In"); + shared_ptr desc = streamDesc->newDeviceDescs_[0]; + int32_t ret = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_); + if (ret != SUCCESS) { + AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch input device"); + desc->exceptionFlag_ = true; + audioDeviceManager_.UpdateDevicesListInfo( + std::make_shared(*desc), EXCEPTION_FLAG_UPDATE); + FetchInputDeviceAndRoute(); + return ERROR; + } + AUDIO_INFO_LOG("desc->connectState_ %{public}d", desc->connectState_); + if (desc->connectState_ == DEACTIVE_CONNECTED || !audioSceneManager_.IsSameAudioScene()) { + AUDIO_INFO_LOG("In2"); + Bluetooth::AudioHfpManager::ConnectScoWithAudioScene(audioSceneManager_.GetAudioScene(true)); + return SUCCESS; + } +#endif + return SUCCESS; +} + +int32_t AudioCoreService::ScoInputDeviceFetchedForRecongnition(bool handleFlag, const std::string &address, + ConnectState connectState) +{ + AUDIO_INFO_LOG("handleflag %{public}d, address %{public}s, connectState %{public}d", + handleFlag, address.c_str(), connectState); + if (handleFlag && connectState != DEACTIVE_CONNECTED) { + return SUCCESS; + } + Bluetooth::BluetoothRemoteDevice device = Bluetooth::BluetoothRemoteDevice(address); + return Bluetooth::AudioHfpManager::HandleScoWithRecongnition(handleFlag, device); +} + +void AudioCoreService::BluetoothScoFetch(std::shared_ptr streamDesc) +{ + Trace trace("AudioCoreService::BluetoothScoFetch"); + shared_ptr desc = streamDesc->newDeviceDescs_[0]; + int32_t ret; + if (Util::IsScoSupportSource(streamDesc->capturerInfo_.sourceType)) { + int32_t activeRet = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_); + if (activeRet != SUCCESS) { + AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch input device"); + desc->exceptionFlag_ = true; + audioDeviceManager_.UpdateDevicesListInfo( + std::make_shared(*desc), EXCEPTION_FLAG_UPDATE); + FetchInputDeviceAndRoute(); + } + ret = ScoInputDeviceFetchedForRecongnition(true, desc->macAddress_, desc->connectState_); + } else { + ret = HandleScoInputDeviceFetched(streamDesc); + } + if (ret != SUCCESS) { + AUDIO_ERR_LOG("sco [%{public}s] is not connected yet", + GetEncryptAddr(desc->macAddress_).c_str()); + } +} + +void AudioCoreService::CheckModemScene(const AudioStreamDeviceChangeReasonExt reason) +{ + if (pipeManager_->GetModemCommunicationId() != 0) { + AUDIO_INFO_LOG("Modem communication id %{public}u", pipeManager_->GetModemCommunicationId()); + vector> descs = + audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_VOICE_MODEM_COMMUNICATION, -1); + AUDIO_INFO_LOG("Size %{public}zu", descs.size()); + if (descs.size() != 0) { + AUDIO_INFO_LOG("Update route %{public}d", descs.front()->deviceType_); + if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { + int32_t ret = HandleScoOutputDeviceFetched(descs.front(), reason); + AUDIO_INFO_LOG("HandleScoOutputDeviceFetched %{public}d", ret); + } + audioActiveDevice_.UpdateActiveDeviceRoute(descs.front()->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG); + } + } +} + +void AudioCoreService::HandleAudioCaptureState(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo) +{ + if (mode == AUDIO_MODE_RECORD && + (streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_RELEASED || + streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_STOPPED)) { + if (Util::IsScoSupportSource(streamChangeInfo.audioCapturerChangeInfo.capturerInfo.sourceType)) { + audioDeviceCommon_.BluetoothScoDisconectForRecongnition(); + Bluetooth::AudioHfpManager::ClearRecongnitionStatus(); + } + audioMicrophoneDescriptor_.RemoveAudioCapturerMicrophoneDescriptorBySessionID( + streamChangeInfo.audioCapturerChangeInfo.sessionId); + } +} + +void AudioCoreService::UpdateDefaultOutputDeviceWhenStopping(int32_t uid) +{ + std::vector sessionIDSet = streamCollector_.GetAllRendererSessionIDForUID(uid); + for (const auto &sessionID : sessionIDSet) { + audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(sessionID); + audioDeviceManager_.RemoveSelectedDefaultOutputDevice(sessionID); + } + FetchOutputDeviceAndRoute(); +} + +int32_t AudioCoreService::BluetoothDeviceFetchOutputHandle(shared_ptr desc, + const AudioStreamDeviceChangeReasonExt reason, std::string encryptMacAddr) +{ + if (desc == nullptr) { + AUDIO_ERR_LOG("Fetch output device is null"); + return BLUETOOTH_FETCH_RESULT_CONTINUE; + } + if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { + AUDIO_INFO_LOG("A2dp device"); + int32_t ret = ActivateA2dpDeviceWhenDescEnabled(desc, reason); + if (ret != SUCCESS) { + AUDIO_ERR_LOG("Activate a2dp [%{public}s] failed", encryptMacAddr.c_str()); + return BLUETOOTH_FETCH_RESULT_ERROR; + } + } else if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { + int32_t ret = HandleScoOutputDeviceFetched(desc, reason); + if (ret != SUCCESS) { + AUDIO_ERR_LOG("sco [%{public}s] is not connected yet", encryptMacAddr.c_str()); + return BLUETOOTH_FETCH_RESULT_ERROR; + } + } + return BLUETOOTH_FETCH_RESULT_DEFAULT; +} + +int32_t AudioCoreService::ActivateA2dpDeviceWhenDescEnabled(shared_ptr desc, + const AudioStreamDeviceChangeReasonExt reason) +{ + AUDIO_INFO_LOG("Desc isEnabled %{public}d", desc->isEnable_); + if (desc->isEnable_) { + return ActivateA2dpDevice(desc, reason); + } + return SUCCESS; +} + + +int32_t AudioCoreService::ActivateA2dpDevice(std::shared_ptr desc, + const AudioStreamDeviceChangeReasonExt reason) +{ + Trace trace("AudioCoreService::ActiveA2dpDevice"); + int32_t ret = SwitchActiveA2dpDevice(desc); + AUDIO_INFO_LOG("ActivateA2dpDevice ret : %{public}d", ret); + // In plan: re-try when failed + return ret; +} + +int32_t AudioCoreService::SwitchActiveA2dpDevice(std::shared_ptr deviceDescriptor) +{ + CHECK_AND_RETURN_RET_LOG(audioA2dpDevice_.CheckA2dpDeviceExist(deviceDescriptor->macAddress_), + ERR_INVALID_PARAM, "Target A2DP device doesn't exist."); + int32_t result = ERROR; +#ifdef BLUETOOTH_ENABLE + std::string lastActiveA2dpDevice = audioActiveDevice_.GetActiveBtDeviceMac(); + audioActiveDevice_.SetActiveBtDeviceMac(deviceDescriptor->macAddress_); + DeviceType lastDevice = audioPolicyManager_.GetActiveDevice(); + audioPolicyManager_.SetActiveDevice(DEVICE_TYPE_BLUETOOTH_A2DP); + + if (Bluetooth::AudioA2dpManager::GetActiveA2dpDevice() == deviceDescriptor->macAddress_ && + audioIOHandleMap_.CheckIOHandleExist(BLUETOOTH_SPEAKER)) { + AUDIO_WARNING_LOG("A2dp device [%{public}s] is already active", + GetEncryptAddr(deviceDescriptor->macAddress_).c_str()); + return SUCCESS; + } + + result = Bluetooth::AudioA2dpManager::SetActiveA2dpDevice(deviceDescriptor->macAddress_); + if (result != SUCCESS) { + audioActiveDevice_.SetActiveBtDeviceMac(lastActiveA2dpDevice); + audioPolicyManager_.SetActiveDevice(lastDevice); + AUDIO_ERR_LOG("Active [%{public}s] failed, using original [%{public}s] device", + GetEncryptAddr(audioActiveDevice_.GetActiveBtDeviceMac()).c_str(), + GetEncryptAddr(lastActiveA2dpDevice).c_str()); + return result; + } + + AudioStreamInfo audioStreamInfo = {}; + audioActiveDevice_.GetActiveA2dpDeviceStreamInfo(DEVICE_TYPE_BLUETOOTH_A2DP, audioStreamInfo); + std::string networkId = audioActiveDevice_.GetCurrentOutputDeviceNetworkId(); + std::string sinkName = AudioPolicyUtils::GetInstance().GetSinkPortName( + audioActiveDevice_.GetCurrentOutputDeviceType()); + result = LoadA2dpModule(DEVICE_TYPE_BLUETOOTH_A2DP, audioStreamInfo, networkId, sinkName, SOURCE_TYPE_INVALID); + CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "LoadA2dpModule failed %{public}d", result); +#endif + return result; +} + +int32_t AudioCoreService::LoadA2dpModule(DeviceType deviceType, const AudioStreamInfo &audioStreamInfo, + std::string networkId, std::string sinkName, SourceType sourceType) +{ + std::list moduleInfoList; + bool ret = policyConfigMananger_.GetModuleListByType(ClassType::TYPE_A2DP, moduleInfoList); + CHECK_AND_RETURN_RET_LOG(ret, ERR_OPERATION_FAILED, "A2dp module is not exist in the configuration file"); + + // not load bt_a2dp_fast and bt_hdap, maybe need fix + int32_t loadRet = AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_BLUETOOTH, "bt_a2dp"); + if (loadRet) { + AUDIO_ERR_LOG("load adapter failed"); + } + for (auto &moduleInfo : moduleInfoList) { + DeviceRole configRole = moduleInfo.role == "source" ? INPUT_DEVICE : OUTPUT_DEVICE; + DeviceRole deviceRole = deviceType == DEVICE_TYPE_BLUETOOTH_A2DP ? OUTPUT_DEVICE : INPUT_DEVICE; + AUDIO_INFO_LOG("Load a2dp module [%{public}s], load role[%{public}d], config role[%{public}d]", + moduleInfo.name.c_str(), deviceRole, configRole); + if (configRole != deviceRole) {continue;} + if (audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name) == false) { + AUDIO_INFO_LOG("A2dp device connects for the first time"); + // a2dp device connects for the first time + GetA2dpModuleInfo(moduleInfo, audioStreamInfo, sourceType); + uint32_t paIndex = 0; + AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, paIndex); + CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED, + "OpenAudioPort failed %{public}d", ioHandle); + audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle); + + std::shared_ptr pipeInfo_ = std::make_shared(); + pipeInfo_->id_ = ioHandle; + pipeInfo_->paIndex_ = paIndex; + if (moduleInfo.role == "sink") { + pipeInfo_->pipeRole_ = PIPE_ROLE_OUTPUT; + pipeInfo_->routeFlag_ = AUDIO_OUTPUT_FLAG_NORMAL; + } else { + pipeInfo_->pipeRole_ = PIPE_ROLE_INPUT; + pipeInfo_->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL; + } + pipeInfo_->adapterName_ = "a2dp"; + pipeInfo_->moduleInfo_ = moduleInfo; + pipeInfo_->pipeAction_ = PIPE_ACTION_DEFAULT; + pipeManager_->AddAudioPipeInfo(pipeInfo_); + AUDIO_INFO_LOG("Add PipeInfo %{public}u in loada2dp.", pipeInfo_->id_); + } else { + // At least one a2dp device is already connected. A new a2dp device is connecting. + // Need to reload a2dp module when switching to a2dp device. + int32_t result = ReloadA2dpAudioPort(moduleInfo, deviceType, audioStreamInfo, networkId, sinkName, + sourceType); + CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "ReloadA2dpAudioPort failed %{public}d", result); + } + } + + return SUCCESS; +} + +int32_t AudioCoreService::ReloadA2dpAudioPort(AudioModuleInfo &moduleInfo, DeviceType deviceType, + const AudioStreamInfo &audioStreamInfo, std::string networkId, std::string sinkName, + SourceType sourceType) +{ + AUDIO_INFO_LOG("Switch device from a2dp to another a2dp, reload a2dp module"); + if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { + audioIOHandleMap_.MuteDefaultSinkPort(networkId, sinkName); + } + + // Firstly, unload the existing a2dp sink or source. + std::string portName = BLUETOOTH_SPEAKER; + if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP_IN) { + portName = BLUETOOTH_MIC; + } + AudioIOHandle activateDeviceIOHandle; + audioIOHandleMap_.GetModuleIdByKey(portName, activateDeviceIOHandle); + int32_t result = audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle); + CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, + "CloseAudioPort failed %{public}d", result); + + // Load a2dp sink or source module again with the configuration of active a2dp device. + GetA2dpModuleInfo(moduleInfo, audioStreamInfo, sourceType); + uint32_t paIndex = 0; + AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, paIndex); + CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED, + "OpenAudioPort failed %{public}d", ioHandle); + audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle); + + std::shared_ptr pipeInfo_ = std::make_shared(); + pipeInfo_->id_ = ioHandle; + pipeInfo_->paIndex_ = paIndex; + if (moduleInfo.role == "sink") { + pipeInfo_->pipeRole_ = PIPE_ROLE_OUTPUT; + pipeInfo_->routeFlag_ = AUDIO_OUTPUT_FLAG_NORMAL; + } else { + pipeInfo_->pipeRole_ = PIPE_ROLE_INPUT; + pipeInfo_->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL; + } + pipeInfo_->adapterName_ = "a2dp"; + pipeInfo_->moduleInfo_ = moduleInfo; + pipeInfo_->pipeAction_ = PIPE_ACTION_DEFAULT; + pipeManager_->AddAudioPipeInfo(pipeInfo_); + AUDIO_INFO_LOG("Add PipeInfo %{public}u in reloada2dp.", pipeInfo_->id_); + return SUCCESS; +} + +void AudioCoreService::GetA2dpModuleInfo(AudioModuleInfo &moduleInfo, const AudioStreamInfo& audioStreamInfo, + SourceType sourceType) +{ + uint32_t bufferSize = audioStreamInfo.samplingRate * + AudioPolicyUtils::GetInstance().PcmFormatToBytes(audioStreamInfo.format) * + audioStreamInfo.channels / BT_BUFFER_ADJUSTMENT_FACTOR; + AUDIO_INFO_LOG("a2dp rate: %{public}d, format: %{public}d, channel: %{public}d", + audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels); + moduleInfo.channels = to_string(audioStreamInfo.channels); + moduleInfo.rate = to_string(audioStreamInfo.samplingRate); + moduleInfo.format = AudioPolicyUtils::GetInstance().ConvertToHDIAudioFormat(audioStreamInfo.format); + moduleInfo.bufferSize = to_string(bufferSize); + if (moduleInfo.role != "source") { + moduleInfo.renderInIdleState = "1"; + moduleInfo.sinkLatency = "0"; + } +} + +bool AudioCoreService::IsSameDevice(shared_ptr &desc, AudioDeviceDescriptor &deviceInfo) +{ + if (desc->networkId_ == deviceInfo.networkId_ && desc->deviceType_ == deviceInfo.deviceType_ && + desc->macAddress_ == deviceInfo.macAddress_ && desc->connectState_ == deviceInfo.connectState_) { + AUDIO_INFO_LOG("Enter"); + if (deviceInfo.IsAudioDeviceDescriptor()) { + return true; + } + BluetoothOffloadState state = audioA2dpOffloadFlag_.GetA2dpOffloadFlag(); + if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP && + // switch to A2dp + ((deviceInfo.a2dpOffloadFlag_ == A2DP_OFFLOAD && state != A2DP_OFFLOAD) || + // switch to A2dp offload + (deviceInfo.a2dpOffloadFlag_ != A2DP_OFFLOAD && state == A2DP_OFFLOAD))) { + return false; + } + if (IsUsb(desc->deviceType_)) { + return desc->deviceRole_ == deviceInfo.deviceRole_; + } + return true; + } else { + return false; + } +} + +int32_t AudioCoreService::FetchDeviceAndRoute(const AudioStreamDeviceChangeReasonExt reason) +{ + return FetchOutputDeviceAndRoute(reason) && FetchInputDeviceAndRoute(); +} + +int32_t AudioCoreService::FetchRendererPipeAndExecute(std::shared_ptr streamDesc, + uint32_t &sessionId, uint32_t &audioFlag, const AudioStreamDeviceChangeReasonExt reason) +{ + if (sessionId == 0) { + streamDesc->sessionId_ = GenerateSessionId(); + sessionId = streamDesc->sessionId_; + AUDIO_INFO_LOG("New sessionId: %{public}u", sessionId); + } + + std::vector> pipeInfos = audioPipeSelector_->FetchPipeAndExecute(streamDesc); + + uint32_t sinkId = HDI_INVALID_ID; + for (auto pipeInfo : pipeInfos) { + AUDIO_INFO_LOG("Pipe name: %{public}s, class: %{public}s, route: %{public}u, action: %{public}d", + pipeInfo->moduleInfo_.adapterName.c_str(), pipeInfo->moduleInfo_.className.c_str(), + pipeInfo->routeFlag_, pipeInfo->pipeAction_); + if (pipeInfo->pipeAction_ == PIPE_ACTION_UPDATE) { + ProcessOutputPipeUpdate(pipeInfo, audioFlag); + } else if (pipeInfo->pipeAction_ == PIPE_ACTION_NEW) { // new + ProcessOutputPipeNew(pipeInfo, audioFlag); + } else if (pipeInfo->pipeAction_ == PIPE_ACTION_DEFAULT) { // DEFAULT + // Do nothing + } + } + RemoveUnusedPipe(); + return SUCCESS; +} + +void AudioCoreService::ProcessOutputPipeNew(std::shared_ptr pipeInfo, uint32_t &flag) +{ + uint32_t paIndex = 0; + uint32_t id = OpenNewAudioPortAndRoute(pipeInfo, paIndex); + CHECK_AND_RETURN_LOG(id != HDI_INVALID_ID, "Invalid sink"); + pipeInfo->id_ = id; + pipeInfo->paIndex_ = paIndex; + + for (auto desc : pipeInfo->streamDescriptors_) { + AUDIO_INFO_LOG("Stream id: %{public}u, action: %{public}d", desc->sessionId_, desc->streamAction_); + switch (desc->streamAction_) { + case AUDIO_STREAM_ACTION_NEW: + flag = desc->routeFlag_; + break; + case AUDIO_STREAM_ACTION_MOVE: + MoveToNewOutputDevice(desc, AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN); + break; + case AUDIO_STREAM_ACTION_RECREATE: + TriggerRecreateRendererStreamCallback(desc->appInfo_.appPid, + desc->sessionId_, desc->routeFlag_); + break; + default: + break; + } + } + pipeManager_->AddAudioPipeInfo(pipeInfo); +} + +void AudioCoreService::ProcessOutputPipeUpdate(std::shared_ptr pipeInfo, uint32_t &flag) +{ + for (auto desc : pipeInfo->streamDescriptors_) { + AUDIO_INFO_LOG("Stream id: %{public}u, action: %{public}d", desc->sessionId_, desc->streamAction_); + switch (desc->streamAction_) { + case AUDIO_STREAM_ACTION_NEW: + flag = desc->routeFlag_; + break; + case AUDIO_STREAM_ACTION_DEFAULT: + case AUDIO_STREAM_ACTION_MOVE: + MoveToNewOutputDevice(desc); + break; + case AUDIO_STREAM_ACTION_RECREATE: + TriggerRecreateRendererStreamCallback(desc->appInfo_.appPid, + desc->sessionId_, desc->routeFlag_); + break; + default: + break; + } + } + pipeManager_->UpdateAudioPipeInfo(pipeInfo); +} + +int32_t AudioCoreService::FetchCapturerPipeAndExecute(std::shared_ptr streamDesc, + uint32_t &audioFlag, uint32_t &sessionId) +{ + if (sessionId == 0) { + streamDesc->sessionId_ = GenerateSessionId(); + sessionId = streamDesc->sessionId_; + AUDIO_INFO_LOG("New sessionId: %{public}u", sessionId); + } + + if (streamDesc->capturerInfo_.sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE) { + AUDIO_INFO_LOG("Playback capturer, return"); + audioFlag = AUDIO_INPUT_FLAG_NORMAL; + return SUCCESS; + } + std::vector> pipeInfos = audioPipeSelector_->FetchPipeAndExecute(streamDesc); + uint32_t sinkId = HDI_INVALID_ID; + for (auto pipeInfo : pipeInfos) { + AUDIO_INFO_LOG("Pipe name: %{public}s, class: %{public}s, route: %{public}u, action: %{public}d", + pipeInfo->moduleInfo_.adapterName.c_str(), pipeInfo->moduleInfo_.className.c_str(), + pipeInfo->routeFlag_, pipeInfo->pipeAction_); + if (pipeInfo->pipeAction_ == PIPE_ACTION_UPDATE) { + ProcessInputPipeUpdate(pipeInfo, audioFlag); + } else if (pipeInfo->pipeAction_ == PIPE_ACTION_NEW) { // new + ProcessInputPipeNew(pipeInfo, audioFlag); + } else if (pipeInfo->pipeAction_ == PIPE_ACTION_DEFAULT) { // DEFAULT + // Do nothing + } + } + RemoveUnusedPipe(); + return SUCCESS; +} + +void AudioCoreService::ProcessInputPipeNew(std::shared_ptr pipeInfo, uint32_t &flag) +{ + uint32_t paIndex = 0; + uint32_t sourceId = OpenNewAudioPortAndRoute(pipeInfo, paIndex); + CHECK_AND_RETURN_LOG(sourceId != HDI_INVALID_ID, "Invalid sink"); + pipeInfo->id_ = sourceId; + pipeInfo->paIndex_ = paIndex; + + for (auto desc : pipeInfo->streamDescriptors_) { + AUDIO_INFO_LOG("Pipe name: %{public}s, class: %{public}s, route: %{public}u, action: %{public}d", + pipeInfo->moduleInfo_.adapterName.c_str(), pipeInfo->moduleInfo_.className.c_str(), + pipeInfo->routeFlag_, pipeInfo->pipeAction_); + switch (desc->streamAction_) { + case AUDIO_STREAM_ACTION_NEW: + flag = desc->routeFlag_; + break; + case AUDIO_STREAM_ACTION_DEFAULT: + case AUDIO_STREAM_ACTION_MOVE: + MoveToNewInputDevice(desc); + break; + case AUDIO_STREAM_ACTION_RECREATE: + TriggerRecreateCapturerStreamCallback(desc->appInfo_.appPid, + desc->sessionId_, desc->routeFlag_); + break; + default: + break; + } + } + pipeManager_->AddAudioPipeInfo(pipeInfo); +} + +void AudioCoreService::ProcessInputPipeUpdate(std::shared_ptr pipeInfo, uint32_t &flag) +{ + for (auto desc : pipeInfo->streamDescriptors_) { + AUDIO_INFO_LOG("Stream id: %{public}u, action: %{public}d", desc->sessionId_, desc->streamAction_); + switch (desc->streamAction_) { + case AUDIO_STREAM_ACTION_NEW: + flag = desc->routeFlag_; + break; + case AUDIO_STREAM_ACTION_DEFAULT: + case AUDIO_STREAM_ACTION_MOVE: + MoveToNewInputDevice(desc); + break; + case AUDIO_STREAM_ACTION_RECREATE: + TriggerRecreateCapturerStreamCallback(desc->appInfo_.appPid, + desc->sessionId_, desc->routeFlag_); + break; + default: + break; + } + } + pipeManager_->UpdateAudioPipeInfo(pipeInfo); +} + +void AudioCoreService::RemoveUnusedPipe() +{ + std::vector> pipeInfos = pipeManager_->GetUnusedPipe(); + for (auto pipeInfo : pipeInfos) { + AUDIO_INFO_LOG("Close hid port id %{public}u", pipeInfo->id_); + audioPolicyManager_.CloseAudioPort(pipeInfo->id_, pipeInfo->paIndex_); + pipeManager_->RemoveAudioPipeInfo(pipeInfo); + } +} + +std::string AudioCoreService::GetAdapterNameBySessionId(uint32_t sessionId) +{ + AUDIO_INFO_LOG("SessionId %{public}u", sessionId); + std::string adapterName = pipeManager_->GetAdapterNameBySessionId(sessionId); + return adapterName; +} + +int32_t AudioCoreService::GetProcessDeviceInfoBySessionId(uint32_t sessionId, AudioDeviceDescriptor &deviceInfo) +{ + AUDIO_INFO_LOG("SessionId %{public}u", sessionId); + deviceInfo = AudioDeviceDescriptor(pipeManager_->GetProcessDeviceInfoBySessionId(sessionId)); + return SUCCESS; +} + +std::atomic g_sessionId = {FIRST_SESSIONID}; // begin at 100000 + +uint32_t AudioCoreService::GenerateSessionId() +{ + uint32_t sessionId = g_sessionId++; + AUDIO_INFO_LOG("sessionId:%{public}d", sessionId); + if (g_sessionId > MAX_VALID_SESSIONID) { + AUDIO_WARNING_LOG("sessionId is too large, reset it!"); + g_sessionId = FIRST_SESSIONID; + } + return sessionId; +} + +void AudioCoreService::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress, + const std::string& deviceName, const AudioStreamInfo& streamInfo, DeviceRole role, bool hasPair) +{ + // Pnp device status update + audioDeviceStatus_.OnDeviceStatusUpdated(devType, isConnected, macAddress, deviceName, streamInfo, role, hasPair); +} + +void AudioCoreService::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, bool isConnected) +{ + // Bluetooth device status updated + DeviceType devType = updatedDesc.deviceType_; + string macAddress = updatedDesc.macAddress_; + string deviceName = updatedDesc.deviceName_; + bool isActualConnection = (updatedDesc.connectState_ != VIRTUAL_CONNECTED); + AUDIO_INFO_LOG("Device connection is actual connection: %{public}d", isActualConnection); + + AudioStreamInfo streamInfo = {}; +#ifdef BLUETOOTH_ENABLE + if (devType == DEVICE_TYPE_BLUETOOTH_A2DP && isActualConnection && isConnected) { + int32_t ret = Bluetooth::AudioA2dpManager::GetA2dpDeviceStreamInfo(macAddress, streamInfo); + CHECK_AND_RETURN_LOG(ret == SUCCESS, "Get a2dp device stream info failed!"); + } + if (devType == DEVICE_TYPE_BLUETOOTH_A2DP_IN && isActualConnection && isConnected) { + int32_t ret = Bluetooth::AudioA2dpManager::GetA2dpInDeviceStreamInfo(macAddress, streamInfo); + CHECK_AND_RETURN_LOG(ret == SUCCESS, "Get a2dp input device stream info failed!"); + } + if (isConnected && isActualConnection + && devType == DEVICE_TYPE_BLUETOOTH_SCO + && updatedDesc.deviceCategory_ != BT_UNWEAR_HEADPHONE + && !audioDeviceManager_.GetScoState()) { + Bluetooth::AudioHfpManager::SetActiveHfpDevice(macAddress); + } +#endif + audioDeviceStatus_.OnDeviceStatusUpdated(updatedDesc, devType, + macAddress, deviceName, isActualConnection, streamInfo, isConnected); +} + +void AudioCoreService::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop) +{ + // Distributed devices status update + audioDeviceStatus_.OnDeviceStatusUpdated(statusInfo, isStop); +} + +void AudioCoreService::MoveToNewOutputDevice( + std::shared_ptr streamDesc, const AudioStreamDeviceChangeReasonExt reason) +{ + AUDIO_INFO_LOG("session %{public}u", streamDesc->sessionId_); + Trace trace("AudioCoreService::MoveToNewOutputDevice"); + DeviceType oldDeviceType = DEVICE_TYPE_NONE; + bool isNeedTriggerCallback = true; + if (streamDesc->oldDeviceDescs_.size() == 0) { + AUDIO_INFO_LOG("Move session, [][]->[%{public}d][%{public}s], reason %{public}d", + streamDesc->newDeviceDescs_.front()->deviceType_, + GetEncryptAddr(streamDesc->newDeviceDescs_.front()->macAddress_).c_str(), static_cast(reason)); + } else { + oldDeviceType = streamDesc->oldDeviceDescs_.front()->deviceType_; + if (streamDesc->oldDeviceDescs_.front()->IsSameDeviceDesc(streamDesc->newDeviceDescs_.front())) { + isNeedTriggerCallback = false; + } + + AUDIO_INFO_LOG("Move session %{public}u, [%{public}d][%{public}s]->[%{public}d][%{public}s], reason %{public}d", + streamDesc->sessionId_, streamDesc->oldDeviceDescs_.front()->deviceType_, + GetEncryptAddr(streamDesc->oldDeviceDescs_.front()->macAddress_).c_str(), + streamDesc->newDeviceDescs_.front()->deviceType_, + GetEncryptAddr(streamDesc->newDeviceDescs_.front()->macAddress_).c_str(), static_cast(reason)); + } + + std::vector sinkInputs; + audioPolicyManager_.GetAllSinkInputs(sinkInputs); + std::vector targetSinkInputs = audioOffloadStream_.FilterSinkInputs(streamDesc->sessionId_, sinkInputs); + + if (isNeedTriggerCallback && audioPolicyServerHandler_) { + audioPolicyServerHandler_->SendRendererDeviceChangeEvent(streamDesc->appInfo_.appPid, + streamDesc->sessionId_, streamDesc->newDeviceDescs_.front(), reason); + } + + AudioPolicyUtils::GetInstance().UpdateEffectDefaultSink(streamDesc->newDeviceDescs_.front()->deviceType_); + + auto ret = (streamDesc->newDeviceDescs_.front()->networkId_ == LOCAL_NETWORK_ID) + ? MoveToLocalOutputDevice(targetSinkInputs, streamDesc->newDeviceDescs_.front()) + : MoveToRemoteOutputDevice(targetSinkInputs, streamDesc->newDeviceDescs_.front()); + if (ret != SUCCESS) { + AudioPolicyUtils::GetInstance().UpdateEffectDefaultSink(oldDeviceType); + AUDIO_ERR_LOG("Move sink input %{public}d to device %{public}d failed!", + streamDesc->sessionId_, streamDesc->newDeviceDescs_.front()->deviceType_); + return; + } + + if (policyConfigMananger_.GetUpdateRouteSupport() && + streamDesc->newDeviceDescs_.front()->networkId_ == LOCAL_NETWORK_ID && !reason.isSetAudioScene()) { + UpdateOutputRoute(streamDesc); + } + + std::string newSinkName = AudioPolicyUtils::GetInstance().GetSinkName(streamDesc->newDeviceDescs_.front(), + streamDesc->sessionId_); + audioVolumeManager_.SetVolumeForSwitchDevice(streamDesc->newDeviceDescs_.front()->deviceType_, newSinkName); + + streamCollector_.UpdateRendererDeviceInfo(streamDesc->newDeviceDescs_.front()); +} + +void AudioCoreService::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status) +{ + CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type"); + audioDeviceStatus_.OnMicrophoneBlockedUpdate(devType, status); +} + +void AudioCoreService::OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected) +{ + audioDeviceStatus_.OnPnpDeviceStatusUpdated(desc, isConnected); +} + +void AudioCoreService::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress, + const std::string &deviceName, const AudioStreamInfo &streamInfo) +{ + audioDeviceStatus_.OnDeviceConfigurationChanged(deviceType, macAddress, deviceName, streamInfo); +} + +int32_t AudioCoreService::OnServiceConnected(AudioServiceIndex serviceIndex) +{ + return audioDeviceStatus_.OnServiceConnected(serviceIndex); +} + +void AudioCoreService::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress) +{ + audioDeviceStatus_.OnForcedDeviceSelected(devType, macAddress); +} + +int32_t AudioCoreService::MoveToRemoteOutputDevice(std::vector sinkInputIds, + std::shared_ptr remoteDeviceDescriptor) +{ + AUDIO_INFO_LOG("Start for [%{public}zu] sink-inputs", sinkInputIds.size()); + + std::string networkId = remoteDeviceDescriptor->networkId_; + DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_; + DeviceType deviceType = remoteDeviceDescriptor->deviceType_; + + // check: networkid + CHECK_AND_RETURN_RET_LOG(networkId != LOCAL_NETWORK_ID, ERR_INVALID_OPERATION, + "failed: not a remote device."); + + uint32_t sinkId = -1; // invalid sink id, use sink name instead. + std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId, deviceRole); + AUDIO_ERR_LOG("moduleName %{public}s", moduleName.c_str()); + + AudioIOHandle moduleId; + if (audioIOHandleMap_.GetModuleIdByKey(moduleName, moduleId)) { + (void)moduleId; // mIOHandle is module id, not equal to sink id. + } else { + AUDIO_ERR_LOG("no such device."); + if (!isOpenRemoteDevice) { + AUDIO_INFO_LOG("directly return"); + return ERR_INVALID_PARAM; + } else { + return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor); + } + } + int32_t res = AudioServerProxy::GetInstance().CheckRemoteDeviceStateProxy(networkId, deviceRole, true); + CHECK_AND_RETURN_RET_LOG(res == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!"); + + // start move. + for (size_t i = 0; i < sinkInputIds.size(); i++) { + int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, moduleName); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "move [%{public}d] failed", sinkInputIds[i].streamId); + audioRouteMap_.AddRouteMapInfo(sinkInputIds[i].uid, moduleName, sinkInputIds[i].pid); + } + + if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) { + AUDIO_WARNING_LOG("Not defult type[%{public}d] on device:[%{public}s]", + deviceType, GetEncryptStr(networkId).c_str()); + } + isCurrentRemoteRenderer_ = true; + return SUCCESS; +} + +void AudioCoreService::MoveToNewInputDevice(std::shared_ptr streamDesc) +{ + Trace trace("AudioCoreService::MoveToNewInputDevice"); + std::vector targetSourceOutputs = FilterSourceOutputs(streamDesc->sessionId_); + + AUDIO_INFO_LOG("Move session %{public}u, [%{public}d][%{public}s]-->[%{public}d][%{public}s]", + streamDesc->sessionId_, streamDesc->oldDeviceDescs_.front()->deviceType_, + GetEncryptAddr(streamDesc->oldDeviceDescs_.front()->macAddress_).c_str(), + streamDesc->newDeviceDescs_.front()->deviceType_, + GetEncryptAddr(streamDesc->newDeviceDescs_.front()->macAddress_).c_str()); + + // MoveSourceOuputByIndexName + auto ret = (streamDesc->newDeviceDescs_.front()->networkId_ == LOCAL_NETWORK_ID) + ? MoveToLocalInputDevice(targetSourceOutputs, streamDesc->newDeviceDescs_.front()) + : MoveToRemoteInputDevice(targetSourceOutputs, streamDesc->newDeviceDescs_.front()); + CHECK_AND_RETURN_LOG((ret == SUCCESS), "Move source output %{public}d to device %{public}d failed!", + streamDesc->sessionId_, streamDesc->newDeviceDescs_.front()->deviceType_); + + if (policyConfigMananger_.GetUpdateRouteSupport() && + streamDesc->newDeviceDescs_.front()->networkId_ == LOCAL_NETWORK_ID) { + audioActiveDevice_.UpdateActiveDeviceRoute(streamDesc->newDeviceDescs_.front()->deviceType_, + DeviceFlag::INPUT_DEVICES_FLAG, streamDesc->newDeviceDescs_.front()->deviceName_); + streamCollector_.UpdateCapturerDeviceInfo(streamDesc->newDeviceDescs_.front()); + } +} + +int32_t AudioCoreService::MoveToLocalInputDevice(std::vector sourceOutputs, + std::shared_ptr localDeviceDescriptor) +{ + AUDIO_DEBUG_LOG("Start"); + // check + CHECK_AND_RETURN_RET_LOG(LOCAL_NETWORK_ID == localDeviceDescriptor->networkId_, ERR_INVALID_OPERATION, + "failed: not a local device."); + // start move. + uint32_t sourceId = -1; // invalid source id, use source name instead. + std::string sourceName = AudioPolicyUtils::GetInstance().GetSourcePortName(localDeviceDescriptor->deviceType_); + for (size_t i = 0; i < sourceOutputs.size(); i++) { + int32_t ret = audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputs[i].paStreamId, + sourceId, sourceName); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, + "move [%{public}d] to local failed", sourceOutputs[i].paStreamId); + } + + return SUCCESS; +} + +int32_t AudioCoreService::MoveToRemoteInputDevice(std::vector sourceOutputs, + std::shared_ptr remoteDeviceDescriptor) +{ + AUDIO_INFO_LOG("Start"); + + std::string networkId = remoteDeviceDescriptor->networkId_; + DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_; + DeviceType deviceType = remoteDeviceDescriptor->deviceType_; + + // check: networkid + CHECK_AND_RETURN_RET_LOG(networkId != LOCAL_NETWORK_ID, ERR_INVALID_OPERATION, + "failed: not a remote device."); + + uint32_t sourceId = -1; // invalid sink id, use sink name instead. + std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId, deviceRole); + + AudioIOHandle moduleId; + if (audioIOHandleMap_.GetModuleIdByKey(moduleName, moduleId)) { + (void)moduleId; // mIOHandle is module id, not equal to sink id. + } else { + AUDIO_ERR_LOG("no such device."); + if (!isOpenRemoteDevice) { + return ERR_INVALID_PARAM; + } else { + return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor); + } + } + int32_t res = AudioServerProxy::GetInstance().CheckRemoteDeviceStateProxy(networkId, deviceRole, true); + CHECK_AND_RETURN_RET_LOG(res == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!"); + + // start move. + for (size_t i = 0; i < sourceOutputs.size(); i++) { + int32_t ret = audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputs[i].paStreamId, + sourceId, moduleName); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, + "move [%{public}d] failed", sourceOutputs[i].paStreamId); + } + + if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) { + AUDIO_DEBUG_LOG("Not defult type[%{public}d] on device:[%{public}s]", + deviceType, GetEncryptStr(networkId).c_str()); + } + return SUCCESS; +} + +int32_t AudioCoreService::OpenRemoteAudioDevice(std::string networkId, DeviceRole deviceRole, DeviceType deviceType, + std::shared_ptr remoteDeviceDescriptor) +{ + // open the test device. We should open it when device is online. + std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId, deviceRole); + AudioModuleInfo remoteDeviceInfo = AudioPolicyUtils::GetInstance().ConstructRemoteAudioModuleInfo(networkId, + deviceRole, deviceType); + + auto ret = AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_REMOTE, networkId); + if (ret) { + AUDIO_ERR_LOG("load adapter fail"); + } + audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleName, remoteDeviceInfo); + + // If device already in list, remove it else do not modify the list. + audioConnectedDevice_.DelConnectedDevice(networkId, deviceType); + AudioPolicyUtils::GetInstance().UpdateDisplayName(remoteDeviceDescriptor); + audioConnectedDevice_.AddConnectedDevice(remoteDeviceDescriptor); + audioMicrophoneDescriptor_.AddMicrophoneDescriptor(remoteDeviceDescriptor); + return SUCCESS; +} + +inline std::string PrintSourceOutput(SourceOutput sourceOutput) +{ + std::stringstream value; + value << "streamId:[" << sourceOutput.streamId << "] "; + value << "streamType:[" << sourceOutput.streamType << "] "; + value << "uid:[" << sourceOutput.uid << "] "; + value << "pid:[" << sourceOutput.pid << "] "; + value << "statusMark:[" << sourceOutput.statusMark << "] "; + value << "deviceSourceId:[" << sourceOutput.deviceSourceId << "] "; + value << "startTime:[" << sourceOutput.startTime << "]"; + return value.str(); +} + +std::vector AudioCoreService::FilterSourceOutputs(int32_t sessionId) +{ + std::vector targetSourceOutputs = {}; + std::vector sourceOutputs = GetSourceOutputs(); + + for (size_t i = 0; i < sourceOutputs.size(); i++) { + AUDIO_DEBUG_LOG("sourceOutput[%{public}zu]:%{public}s", i, PrintSourceOutput(sourceOutputs[i]).c_str()); + if (sessionId == sourceOutputs[i].streamId) { + targetSourceOutputs.push_back(sourceOutputs[i]); + } + } + return targetSourceOutputs; +} + +std::vector AudioCoreService::GetSourceOutputs() +{ + std::vector sourceOutputs; + { + std::unordered_map mapCopy = AudioIOHandleMap::GetInstance().GetCopy(); + if (std::any_of(mapCopy.cbegin(), mapCopy.cend(), [](const auto &pair) { + return std::find(SourceNames.cbegin(), SourceNames.cend(), pair.first) != SourceNames.cend(); + })) { + sourceOutputs = audioPolicyManager_.GetAllSourceOutputs(); + } + } + return sourceOutputs; +} + +void AudioCoreService::UpdateOutputRoute(std::shared_ptr streamDesc) +{ + StreamUsage streamUsage = streamDesc->rendererInfo_.streamUsage; + InternalDeviceType deviceType = streamDesc->newDeviceDescs_.front()->deviceType_; + AUDIO_INFO_LOG("update route, streamUsage:%{public}d, 1st devicetype:%{public}d", streamUsage, deviceType); + if (Util::IsRingerOrAlarmerStreamUsage(streamUsage) && IsRingerOrAlarmerDualDevicesRange(deviceType) && + !VolumeUtils::IsPCVolumeEnable()) { + if (!SelectRingerOrAlarmDevices(streamDesc)) { + audioActiveDevice_.UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG); + } + + AudioRingerMode ringerMode = audioPolicyManager_.GetRingerMode(); + if (ringerMode != RINGER_MODE_NORMAL && + IsRingerOrAlarmerDualDevicesRange(streamDesc->newDeviceDescs_.front()->getType()) && + streamDesc->newDeviceDescs_.front()->getType() != DEVICE_TYPE_SPEAKER) { + audioPolicyManager_.SetStreamMute(STREAM_RING, false, streamUsage); + audioVolumeManager_.SetRingerModeMute(false); + if (audioPolicyManager_.GetSystemVolumeLevel(STREAM_RING) < + audioPolicyManager_.GetMaxVolumeLevel(STREAM_RING) / VOLUME_LEVEL_DEFAULT_SIZE) { + audioPolicyManager_.SetDoubleRingVolumeDb(STREAM_RING, + audioPolicyManager_.GetMaxVolumeLevel(STREAM_RING) / VOLUME_LEVEL_DEFAULT_SIZE); + } + } else { + audioVolumeManager_.SetRingerModeMute(true); + } + shouldUpdateDeviceDueToDualTone_ = true; + } else { + if (enableDualHalToneState_) { + AUDIO_INFO_LOG("disable dual hal tone for not ringer/alarm."); + UpdateDualToneState(false, enableDualHalToneSessionId_); + } + audioVolumeManager_.SetRingerModeMute(true); + audioActiveDevice_.UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG); + shouldUpdateDeviceDueToDualTone_ = false; + } +} + +void AudioCoreService::OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor& deviceDescriptor) +{ + AUDIO_INFO_LOG("In"); + Trace trace("AudioCoreService::OnPreferredOutputDeviceUpdated:" + std::to_string(deviceDescriptor.deviceType_)); + + if (audioPolicyServerHandler_ != nullptr) { + audioPolicyServerHandler_->SendPreferredOutputDeviceUpdated(); + } + spatialDeviceMap_.insert(make_pair(deviceDescriptor.macAddress_, deviceDescriptor.deviceType_)); + + if (deviceDescriptor.macAddress_ != + AudioSpatializationService::GetAudioSpatializationService().GetCurrentDeviceAddress()) { + AudioServerProxy::GetInstance().UpdateEffectBtOffloadSupportedProxy(false); + } + AudioPolicyUtils::GetInstance().UpdateEffectDefaultSink(deviceDescriptor.deviceType_); + AudioSpatializationService::GetAudioSpatializationService().UpdateCurrentDevice(deviceDescriptor.macAddress_); +} + +void AudioCoreService::OnPreferredInputDeviceUpdated(DeviceType deviceType, std::string networkId) +{ + AUDIO_INFO_LOG("OnPreferredInputDeviceUpdated Start"); + + if (audioPolicyServerHandler_ != nullptr) { + audioPolicyServerHandler_->SendPreferredInputDeviceUpdated(); + } +} + + +bool AudioCoreService::IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType &deviceType) +{ + switch (deviceType) { + case DEVICE_TYPE_SPEAKER: + case DEVICE_TYPE_WIRED_HEADSET: + case DEVICE_TYPE_WIRED_HEADPHONES: + case DEVICE_TYPE_BLUETOOTH_SCO: + case DEVICE_TYPE_BLUETOOTH_A2DP: + case DEVICE_TYPE_USB_HEADSET: + case DEVICE_TYPE_USB_ARM_HEADSET: + return true; + default: + return false; + } +} + +bool AudioCoreService::SelectRingerOrAlarmDevices(std::shared_ptr streamDesc) +{ + CHECK_AND_RETURN_RET_LOG(streamDesc->newDeviceDescs_.size() > 0 && + streamDesc->newDeviceDescs_.size() <= AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT, false, + "audio devices not in range for ringer or alarmer."); + const int32_t sessionId = streamDesc->sessionId_; + const StreamUsage streamUsage = streamDesc->rendererInfo_.streamUsage; + bool allDevicesInDualDevicesRange = true; + std::vector> activeDevices; + for (size_t i = 0; i < streamDesc->newDeviceDescs_.size(); i++) { + if (IsRingerOrAlarmerDualDevicesRange(streamDesc->newDeviceDescs_[i]->deviceType_)) { + activeDevices.push_back(make_pair(streamDesc->newDeviceDescs_[i]->deviceType_, + DeviceFlag::OUTPUT_DEVICES_FLAG)); + AUDIO_INFO_LOG("select ringer/alarm devices devicetype[%{public}zu]:%{public}d", + i, streamDesc->newDeviceDescs_[i]->deviceType_); + } else { + allDevicesInDualDevicesRange = false; + break; + } + } + + AUDIO_INFO_LOG("select ringer/alarm sessionId:%{public}d, streamUsage:%{public}d", sessionId, streamUsage); + if (!streamDesc->newDeviceDescs_.empty() && allDevicesInDualDevicesRange) { + if (streamDesc->newDeviceDescs_.size() == AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT && + AudioPolicyUtils::GetInstance().GetSinkName(*streamDesc->newDeviceDescs_.front(), sessionId) != + AudioPolicyUtils::GetInstance().GetSinkName(*streamDesc->newDeviceDescs_.back(), sessionId)) { + AUDIO_INFO_LOG("set dual hal tone, reset primary sink to default before."); + audioActiveDevice_.UpdateActiveDeviceRoute(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG); + if (enableDualHalToneState_ && enableDualHalToneSessionId_ != sessionId) { + AUDIO_INFO_LOG("sesion changed, disable old dual hal tone."); + UpdateDualToneState(false, enableDualHalToneSessionId_); + } + + if ((audioPolicyManager_.GetRingerMode() != RINGER_MODE_NORMAL && streamUsage != STREAM_USAGE_ALARM) || + (VolumeUtils::IsPCVolumeEnable() && audioVolumeManager_.GetStreamMute(STREAM_MUSIC))) { + AUDIO_INFO_LOG("no normal ringer mode and no alarm, dont dual hal tone."); + return false; + } + UpdateDualToneState(true, sessionId); + } else { + audioActiveDevice_.UpdateActiveDevicesRoute(activeDevices); + } + return true; + } + return false; +} + +void AudioCoreService::UpdateDualToneState(const bool &enable, const int32_t &sessionId) +{ + AUDIO_INFO_LOG("update dual tone state, enable:%{public}d, sessionId:%{public}d", enable, sessionId); + enableDualHalToneState_ = enable; + if (enableDualHalToneState_) { + enableDualHalToneSessionId_ = sessionId; + } + Trace trace("AudioDeviceCommon::UpdateDualToneState sessionId:" + std::to_string(sessionId)); + auto ret = AudioServerProxy::GetInstance().UpdateDualToneStateProxy(enable, sessionId); + CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the dual tone state for sessionId:%{public}d", sessionId); +} + +int32_t AudioCoreService::MoveToLocalOutputDevice(std::vector sinkInputIds, + std::shared_ptr localDeviceDescriptor) +{ + AUDIO_INFO_LOG("Start for [%{public}zu] sink-inputs", sinkInputIds.size()); + // check + CHECK_AND_RETURN_RET_LOG(LOCAL_NETWORK_ID == localDeviceDescriptor->networkId_, + ERR_INVALID_OPERATION, "failed: not a local device."); + + // start move. + uint32_t sinkId = -1; // invalid sink id, use sink name instead. + for (size_t i = 0; i < sinkInputIds.size(); i++) { + AudioPipeType pipeType = PIPE_TYPE_UNKNOWN; + + std::string sinkName = pipeManager_->GetAdapterNameBySessionId(sinkInputIds[i].streamId); + AUDIO_INFO_LOG("Session %{public}d, sinkName %{public}s", sinkInputIds[i].streamId, sinkName.c_str()); + if (sinkName == BLUETOOTH_SPEAKER) { + std::string activePort = BLUETOOTH_SPEAKER; + audioPolicyManager_.SuspendAudioDevice(activePort, false); + } + AUDIO_INFO_LOG("move for session [%{public}d], portName %{public}s pipeType %{public}d", + sinkInputIds[i].streamId, sinkName.c_str(), pipeType); + int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, sinkName); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, + "move [%{public}d] to local failed", sinkInputIds[i].streamId); + audioRouteMap_.AddRouteMapInfo(sinkInputIds[i].uid, LOCAL_NETWORK_ID, sinkInputIds[i].pid); + } + + isCurrentRemoteRenderer_ = false; + return SUCCESS; +} + +void AudioCoreService::UpdateDeviceInfo(std::shared_ptr oldDeviceDesc, + const std::shared_ptr newDeviceDesc, bool hasBTPermission, bool hasSystemPermission) +{ + oldDeviceDesc->deviceType_ = newDeviceDesc->deviceType_; + oldDeviceDesc->deviceRole_ = newDeviceDesc->deviceRole_; + oldDeviceDesc->deviceId_ = newDeviceDesc->deviceId_; + oldDeviceDesc->channelMasks_ = newDeviceDesc->channelMasks_; + oldDeviceDesc->channelIndexMasks_ = newDeviceDesc->channelIndexMasks_; + oldDeviceDesc->displayName_ = newDeviceDesc->displayName_; + oldDeviceDesc->connectState_ = newDeviceDesc->connectState_; + + if (oldDeviceDesc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { + oldDeviceDesc->a2dpOffloadFlag_ = audioA2dpOffloadFlag_.GetA2dpOffloadFlag(); + } + + if (hasBTPermission) { + oldDeviceDesc->deviceName_ = newDeviceDesc->deviceName_; + oldDeviceDesc->macAddress_ = newDeviceDesc->macAddress_; + oldDeviceDesc->deviceCategory_ = newDeviceDesc->deviceCategory_; + } else { + oldDeviceDesc->deviceName_ = ""; + oldDeviceDesc->macAddress_ = ""; + oldDeviceDesc->deviceCategory_ = CATEGORY_DEFAULT; + } + + oldDeviceDesc->isLowLatencyDevice_ = HasLowLatencyCapability(oldDeviceDesc->deviceType_, + newDeviceDesc->networkId_ != LOCAL_NETWORK_ID); + + if (hasSystemPermission) { + oldDeviceDesc->networkId_ = newDeviceDesc->networkId_; + oldDeviceDesc->volumeGroupId_ = newDeviceDesc->volumeGroupId_; + oldDeviceDesc->interruptGroupId_ = newDeviceDesc->interruptGroupId_; + } else { + oldDeviceDesc->networkId_ = ""; + oldDeviceDesc->volumeGroupId_ = GROUP_ID_NONE; + oldDeviceDesc->interruptGroupId_ = GROUP_ID_NONE; + } + oldDeviceDesc->audioStreamInfo_.samplingRate = newDeviceDesc->audioStreamInfo_.samplingRate; + oldDeviceDesc->audioStreamInfo_.encoding = newDeviceDesc->audioStreamInfo_.encoding; + oldDeviceDesc->audioStreamInfo_.format = newDeviceDesc->audioStreamInfo_.format; + oldDeviceDesc->audioStreamInfo_.channels = newDeviceDesc->audioStreamInfo_.channels; +} + +bool AudioCoreService::HasLowLatencyCapability(DeviceType deviceType, bool isRemote) +{ + // Distributed devices are low latency devices + if (isRemote) { + return true; + } + + switch (deviceType) { + case DeviceType::DEVICE_TYPE_EARPIECE: + case DeviceType::DEVICE_TYPE_SPEAKER: + case DeviceType::DEVICE_TYPE_WIRED_HEADSET: + case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES: + case DeviceType::DEVICE_TYPE_USB_HEADSET: + case DeviceType::DEVICE_TYPE_DP: + return true; + + case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO: + case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP: + return false; + default: + return false; + } +} + +void AudioCoreService::TriggerRecreateRendererStreamCallback(int32_t callerPid, int32_t sessionId, + uint32_t routeFlag, const AudioStreamDeviceChangeReasonExt::ExtEnum reason) +{ + Trace trace("AudioDeviceCommon::TriggerRecreateRendererStreamCallback"); + AUDIO_INFO_LOG("Trigger recreate renderer stream, pid: %{public}d, sessionId: %{public}d, flag: %{public}d", + callerPid, sessionId, routeFlag); + if (audioPolicyServerHandler_ != nullptr) { + audioPolicyServerHandler_->SendRecreateRendererStreamEvent(callerPid, sessionId, routeFlag, reason); + } else { + AUDIO_WARNING_LOG("No audio policy server handler"); + } +} + +void AudioCoreService::TriggerRecreateCapturerStreamCallback(int32_t callerPid, int32_t sessionId, + uint32_t routeFlag) +{ + Trace trace("AudioCoreService::TriggerRecreateCapturerStreamCallback"); + AUDIO_INFO_LOG("Trigger recreate capturer stream, pid: %{public}d, sessionId: %{public}d, flag: %{public}d", + callerPid, sessionId, routeFlag); + if (audioPolicyServerHandler_ != nullptr) { + audioPolicyServerHandler_->SendRecreateCapturerStreamEvent(callerPid, sessionId, routeFlag, + AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN); + } else { + AUDIO_WARNING_LOG("No audio policy server handler"); + } +} + +uint32_t AudioCoreService::OpenNewAudioPortAndRoute(std::shared_ptr pipeInfo, uint32_t &paIndex) +{ + AUDIO_INFO_LOG("Flag: %{public}u, role: %{public}s", pipeInfo->routeFlag_, pipeInfo->moduleInfo_.role.c_str()); + uint32_t id = OPEN_PORT_FAILURE; + if (pipeInfo->streamDescriptors_.front()->newDeviceDescs_.front()->deviceType_ == DEVICE_TYPE_REMOTE_CAST) { + // DEVICE_TYPE_REMOTE_CAST no need to open audioport + id = pipeInfo->streamDescriptors_.front()->sessionId_; + } else { + id = audioPolicyManager_.OpenAudioPort(pipeInfo, paIndex); + } + CHECK_AND_RETURN_RET_LOG(id != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED, "OpenAudioPort failed %{public}d", id); + audioIOHandleMap_.AddIOHandleInfo(pipeInfo->moduleInfo_.name, id); + AUDIO_INFO_LOG("Get HDI id: %{public}u, paIndex %{public}u", id, paIndex); + return id; +} + +bool AudioCoreService::IsPaRoute(uint32_t routeFlag) +{ + if ((routeFlag & AUDIO_OUTPUT_FLAG_DIRECT) || + (routeFlag & AUDIO_OUTPUT_FLAG_FAST) || + (routeFlag & AUDIO_INPUT_FLAG_FAST)) { + return false; + } + return true; +} + +int32_t AudioCoreService::HandleScoOutputDeviceFetched( + shared_ptr &desc, const AudioStreamDeviceChangeReasonExt reason) +{ + AUDIO_INFO_LOG("In"); + Trace trace("AudioCoreService::HandleScoOutputDeviceFetched"); +#ifdef BLUETOOTH_ENABLE + int32_t ret = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_); + if (ret != SUCCESS) { + AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch output device."); + desc->exceptionFlag_ = true; + audioDeviceManager_.UpdateDevicesListInfo( + std::make_shared(*desc), EXCEPTION_FLAG_UPDATE); + FetchOutputDeviceAndRoute(reason); + return ERROR; + } + if (desc->connectState_ == DEACTIVE_CONNECTED || !audioSceneManager_.IsSameAudioScene()) { + Bluetooth::AudioHfpManager::ConnectScoWithAudioScene(audioSceneManager_.GetAudioScene(true)); + return SUCCESS; + } +#endif + AUDIO_INFO_LOG("out"); + return SUCCESS; +} + +int32_t AudioCoreService::GetRealUid(std::shared_ptr streamDesc) +{ + if (streamDesc->callerUid_ == MEDIA_SERVICE_UID) { + return streamDesc->appInfo_.appUid; + } + return streamDesc->callerUid_; +} + +void AudioCoreService::UpdateRendererInfoWhenNoPermission( + const shared_ptr &audioRendererChangeInfos, bool hasSystemPermission) +{ + if (!hasSystemPermission) { + audioRendererChangeInfos->clientUID = 0; + audioRendererChangeInfos->rendererState = RENDERER_INVALID; + } +} + +void AudioCoreService::UpdateCapturerInfoWhenNoPermission( + const shared_ptr &audioCapturerChangeInfos, bool hasSystemPermission) +{ + if (!hasSystemPermission) { + audioCapturerChangeInfos->clientUID = 0; + audioCapturerChangeInfos->capturerState = CAPTURER_INVALID; + } +} + +void AudioCoreService::SendA2dpConnectedWhileRunning(const RendererState &rendererState, const uint32_t &sessionId) +{ + if ((rendererState == RENDERER_RUNNING) && (audioA2dpOffloadManager_ != nullptr) && + !audioA2dpOffloadManager_->IsA2dpOffloadConnecting(sessionId)) { + AUDIO_INFO_LOG("Notify client not to block."); + std::thread sendConnectedToClient(&AudioCoreService::UpdateSessionConnectionState, this, sessionId, + DATA_LINK_CONNECTED); + sendConnectedToClient.detach(); + } +} + +void AudioCoreService::UpdateSessionConnectionState(const int32_t &sessionID, const int32_t &state) +{ + AudioServerProxy::GetInstance().UpdateSessionConnectionStateProxy(sessionID, state); +} + +void AudioCoreService::UpdateTrackerDeviceChange(const vector> &desc) +{ + AUDIO_INFO_LOG("Start"); + + DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType(); + for (std::shared_ptr deviceDesc : desc) { + if (deviceDesc->deviceRole_ == OUTPUT_DEVICE) { + DeviceType type = curOutputDeviceType; + std::string macAddress = audioActiveDevice_.GetCurrentOutputDeviceMacAddr(); + auto itr = audioConnectedDevice_.CheckExistOutputDevice(type, macAddress); + if (itr != nullptr) { + AudioDeviceDescriptor outputDevice(AudioDeviceDescriptor::DEVICE_INFO); + audioDeviceCommon_.UpdateDeviceInfo(outputDevice, itr, true, true); + streamCollector_.UpdateTracker(AUDIO_MODE_PLAYBACK, outputDevice); + } + } + if (deviceDesc->deviceRole_ == INPUT_DEVICE) { + DeviceType type = audioActiveDevice_.GetCurrentInputDeviceType(); + auto itr = audioConnectedDevice_.CheckExistInputDevice(type); + if (itr != nullptr) { + AudioDeviceDescriptor inputDevice(AudioDeviceDescriptor::DEVICE_INFO); + audioDeviceCommon_.UpdateDeviceInfo(inputDevice, itr, true, true); + audioMicrophoneDescriptor_.UpdateAudioCapturerMicrophoneDescriptor(itr->deviceType_); + streamCollector_.UpdateTracker(AUDIO_MODE_RECORD, inputDevice); + } + } + } +} + +bool AudioCoreService::GetFastControlParam() +{ + int32_t fastControlFlag = 1; // default 1, set isFastControlled_ true + GetSysPara("persist.multimedia.audioflag.fastcontrolled", fastControlFlag); + if (fastControlFlag == 0) { + isFastControlled_ = false; + } + return isFastControlled_; +} + +void AudioCoreService::StoreDistributedRoutingRoleInfo( + const std::shared_ptr descriptor, CastType type) +{ + distributedRoutingInfo_.descriptor = descriptor; + distributedRoutingInfo_.type = type; +} + +int32_t AudioCoreService::GetSystemVolumeLevel(AudioStreamType streamType) +{ + return audioVolumeManager_.GetSystemVolumeLevel(streamType); +} + +float AudioCoreService::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel, + DeviceType deviceType) const +{ + return audioPolicyManager_.GetSystemVolumeInDb(volumeType, volumeLevel, deviceType); +} + +bool AudioCoreService::IsStreamSupportLowpower(std::shared_ptr streamDesc) +{ + Trace trace("IsStreamSupportLowpower"); + if (pipeManager_->PcmOffloadSessionCount() > 0) { + AUDIO_INFO_LOG("PIPE_TYPE_OFFLOAD already exist."); + return false; + } + if (!streamDesc->rendererInfo_.isOffloadAllowed) { + AUDIO_INFO_LOG("normal stream beacuse renderInfo not support offload."); + return false; + } + if (streamDesc->streamInfo_.channels < MONO || streamDesc->streamInfo_.channels > STEREO) { + AUDIO_INFO_LOG("normal stream beacuse channels."); + return false; + } + + if (streamDesc->rendererInfo_.streamUsage != STREAM_USAGE_MUSIC && + streamDesc->rendererInfo_.streamUsage != STREAM_USAGE_AUDIOBOOK) { + AUDIO_INFO_LOG("normal stream beacuse streamUsage."); + return false; + } + + AudioSpatializationState spatialState = + AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState(); + bool effectOffloadFlag = AudioServerProxy::GetInstance().GetEffectOffloadEnabledProxy(); + if (spatialState.spatializationEnabled && !effectOffloadFlag) { + AUDIO_INFO_LOG("spatialization effect in arm, Skipped."); + return false; + } + + if (streamDesc->newDeviceDescs_[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { + // a2dp offload + return true; + } + + if (streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_SPEAKER && + streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_USB_HEADSET) { + AUDIO_INFO_LOG("normal stream, deviceType: %{public}d", streamDesc->newDeviceDescs_[0]->deviceType_); + return false; + } + return true; +} + +int32_t AudioCoreService::SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionID, + const StreamUsage streamUsage, bool isRunning) +{ + CHECK_AND_RETURN_RET_LOG(policyConfigMananger_.GetHasEarpiece(), ERR_NOT_SUPPORTED, "the device has no earpiece"); + int32_t ret = audioDeviceManager_.SetDefaultOutputDevice(deviceType, sessionID, streamUsage, isRunning); + if (ret == NEED_TO_FETCH) { + FetchOutputDeviceAndRoute(AudioStreamDeviceChangeReasonExt::ExtEnum::SET_DEFAULT_OUTPUT_DEVICE); + return SUCCESS; + } + return ret; +} +} +} diff --git a/services/audio_policy/services/pipe/include/audio_pipe_manager.h b/services/audio_policy/services/pipe/include/audio_pipe_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..3bf22a19b59d16758806e5ee741950d1ee53d05c --- /dev/null +++ b/services/audio_policy/services/pipe/include/audio_pipe_manager.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef AUDIO_PIPE_MANAGER_H +#define AUDIO_PIPE_MANAGER_H + +#include +#include +#include + +#include "audio_stream_descriptor.h" +#include "audio_module_info.h" +#include "audio_pipe_info.h" + +namespace OHOS { +namespace AudioStandard { +class AudioPipeManager { +public: + AudioPipeManager(); + ~AudioPipeManager(); + + static std::shared_ptr GetPipeManager() + { + static std::shared_ptr instance = std::make_shared(); + return instance; + } + + void AddAudioPipeInfo(std::shared_ptr info); + void RemoveAudioPipeInfo(std::shared_ptr info); + void RemoveAudioPipeInfo(AudioIOHandle id); + void UpdateAudioPipeInfo(std::shared_ptr newPipe); + void Assign(std::shared_ptr dst, std::shared_ptr src); + bool IsSamePipe(std::shared_ptr info, std::shared_ptr cmpInfo); + + const std::vector> GetPipeList(); + std::vector> GetUnusedPipe(); + std::shared_ptr GetPipeinfoByNameAndFlag(const std::string adapterName, const uint32_t routeFlag); + std::string GetAdapterNameBySessionId(uint32_t sessionId); + std::shared_ptr GetProcessDeviceInfoBySessionId(uint32_t sessionId); + + void StartClient(uint32_t sessionId); + void PauseClient(uint32_t sessionId); + void StopClient(uint32_t sessionId); + void RemoveClient(uint32_t sessionId); + + std::vector> GetAllOutputStreamDescs(); + std::vector> GetAllInputStreamDescs(); + std::shared_ptr GetStreamDescById(uint32_t sessionId); + std::shared_ptr GetStreamDescByIdInner(uint32_t sessionId); + int32_t GetStreamCount(const std::string adapterName, const uint32_t routeFlag); + uint32_t GetPaIndexByIoHandle(AudioIOHandle id); + void UpdateRendererPipeInfos(std::vector> &pipeInfos); + void UpdateCapturerPipeInfos(std::vector> &pipeInfos); + uint32_t PcmOffloadSessionCount(); + + void Dump(std::string &dumpString); + uint32_t GetModemCommunicationId(); + void SetModemCommunicationId(uint32_t id); + void ResetModemCommunicationId(); + +private: + bool IsSpecialPipe(uint32_t routeFlag); + + std::atomic modemCommunicationId_ = 0; + std::vector> curPipeList_; + std::shared_mutex pipeListLock_; +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // AUDIO_PIPE_MANAGER_H diff --git a/services/audio_policy/services/pipe/include/audio_pipe_selector.h b/services/audio_policy/services/pipe/include/audio_pipe_selector.h new file mode 100644 index 0000000000000000000000000000000000000000..805d4eb6d52c9f2a8a8d41f1cb996d5760bbb55a --- /dev/null +++ b/services/audio_policy/services/pipe/include/audio_pipe_selector.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef AUDIO_PIPE_SELECTOR_H +#define AUDIO_PIPE_SELECTOR_H + +#include +#include "audio_pipe_manager.h" +#include "audio_stream_info.h" +#include "audio_policy_config_manager.h" + +namespace OHOS { +namespace AudioStandard { + +class AudioPipeSelector { +public: + AudioPipeSelector(); + ~AudioPipeSelector() = default; + + static std::shared_ptr GetPipeSelector(); + + std::vector> FetchPipeAndExecute(std::shared_ptr &streamDesc); + std::vector> FetchPipesAndExecute( + std::vector> &streamDescs); + +private: + void ScanPipeListForStreamDesc(std::vector> &pipeInfoList, + std::shared_ptr streamDesc); + bool ProcessConcurrency(std::shared_ptr stream, + std::shared_ptr cmpStream); + uint32_t GetRouteFlagByStreamDesc(std::shared_ptr streamDesc); + std::string GetAdapterNameByStreamDesc(std::shared_ptr streamDesc); + void ConvertStreamDescToPipeInfo(std::shared_ptr streamDesc, + std::shared_ptr streamPropInfo, AudioPipeInfo &info); + AudioStreamAction JudgeStreamAction(std::shared_ptr newPipe, std::shared_ptr oldPipe); + void SortStreamDescsByStartTime(std::vector> &streamDescs); + AudioPipeType GetPipeType(uint32_t flag, AudioMode audioMode); + bool IsPipeExist(std::vector> &newPipeInfoList, + std::string &adapterName, std::shared_ptr &streamDesc, + std::map> &streamDescToPipeInfo); + void HandlePipeNotExist(std::vector> &newPipeInfoList, + std::shared_ptr &streamDesc, + std::map> &streamDescToPipeInfo); + + AudioPolicyConfigManager& configManager_; +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // AUDIO_PIPE_SELECTOR_H diff --git a/services/audio_policy/services/pipe/src/audio_pipe_manager.cpp b/services/audio_policy/services/pipe/src/audio_pipe_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cff84c49ae27adf3b39df2add8e13fc70bf97937 --- /dev/null +++ b/services/audio_policy/services/pipe/src/audio_pipe_manager.cpp @@ -0,0 +1,355 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef LOG_TAG +#define LOG_TAG "AudioPipeManager" +#endif + +#include "audio_pipe_manager.h" + +namespace OHOS { +namespace AudioStandard { + +const uint32_t FIRST_SESSIONID = 100000; +constexpr uint32_t MAX_VALID_SESSIONID = UINT32_MAX - FIRST_SESSIONID; +AudioPipeManager::AudioPipeManager() +{ +} + +AudioPipeManager::~AudioPipeManager() +{ + AUDIO_INFO_LOG("Dtor"); + curPipeList_.clear(); +} + +void AudioPipeManager::AddAudioPipeInfo(std::shared_ptr info) +{ + std::unique_lock pLock(pipeListLock_); + AUDIO_INFO_LOG("Add pipe %{public}s, pipeRole: %{public}d", info->adapterName_.c_str(), info->pipeRole_); + curPipeList_.push_back(info); +} + +void AudioPipeManager::RemoveAudioPipeInfo(std::shared_ptr info) +{ + std::unique_lock pLock(pipeListLock_); + AUDIO_INFO_LOG("Adapter name: %{public}s", info->adapterName_.c_str()); + for (auto iter = curPipeList_.begin(); iter != curPipeList_.end(); iter++) { + if (IsSamePipe(info, *iter)) { + curPipeList_.erase(iter); + break; + } + } +} + +void AudioPipeManager::RemoveAudioPipeInfo(AudioIOHandle id) +{ + std::unique_lock pLock(pipeListLock_); + for (auto iter = curPipeList_.begin(); iter != curPipeList_.end(); iter++) { + if ((*iter)->id_ == id) { + AUDIO_INFO_LOG("Find id :%{public}d, adapterName: %{public}s", id, (*iter)->adapterName_.c_str()); + curPipeList_.erase(iter); + break; + } + } +} + +void AudioPipeManager::UpdateAudioPipeInfo(std::shared_ptr newPipe) +{ + std::unique_lock pLock(pipeListLock_); + for (auto iter = curPipeList_.begin(); iter != curPipeList_.end(); iter++) { + if (IsSamePipe(newPipe, *iter)) { + Assign(*iter, newPipe); + break; + } + } +} + +bool AudioPipeManager::IsSamePipe(std::shared_ptr info, std::shared_ptr cmpInfo) +{ + AUDIO_INFO_LOG("adapterName: %{public}s, cmp: %{public}s, routeFlag: %{public}d, cmp: %{public}d", + info->adapterName_.c_str(), cmpInfo->adapterName_.c_str(), info->routeFlag_, cmpInfo->routeFlag_); + if ((info->adapterName_ == cmpInfo->adapterName_ && info->routeFlag_ == cmpInfo->routeFlag_) || + info->id_ == cmpInfo->id_) { + return true; + } + return false; +} + +void AudioPipeManager::Assign(std::shared_ptr dst, std::shared_ptr src) +{ + dst = src; +} + +void AudioPipeManager::StartClient(uint32_t sessionId) +{ + std::unique_lock pLock(pipeListLock_); + std::shared_ptr streamDesc = GetStreamDescByIdInner(sessionId); + streamDesc->streamStatus_ = STREAM_STATUS_STARTTING; +} + +void AudioPipeManager::PauseClient(uint32_t sessionId) +{ + std::unique_lock pLock(pipeListLock_); + std::shared_ptr streamDesc = GetStreamDescByIdInner(sessionId); + streamDesc->streamStatus_ = STREAM_STATUS_PAUSED; +} + +void AudioPipeManager::StopClient(uint32_t sessionId) +{ + std::unique_lock pLock(pipeListLock_); + std::shared_ptr streamDesc = GetStreamDescByIdInner(sessionId); + streamDesc->streamStatus_ = STREAM_STATUS_STOPPED; +} + +void AudioPipeManager::RemoveClient(uint32_t sessionId) +{ + std::unique_lock pLock(pipeListLock_); + AUDIO_INFO_LOG("Cur pipe list size %{public}zu, sessionId %{public}u", curPipeList_.size(), sessionId); + for (auto pipeInfo : curPipeList_) { + pipeInfo->streamDescriptors_.erase(std::remove_if(pipeInfo->streamDescriptors_.begin(), + pipeInfo->streamDescriptors_.end(), [sessionId](std::shared_ptr streamDesc) { + return streamDesc->sessionId_ == sessionId; + }), pipeInfo->streamDescriptors_.end()); + } +} + +const std::vector> AudioPipeManager::GetPipeList() +{ + std::shared_lock pLock(pipeListLock_); + AUDIO_INFO_LOG("List size: %{public}zu", curPipeList_.size()); + return curPipeList_; +} + +std::vector> AudioPipeManager::GetUnusedPipe() +{ + std::unique_lock pLock(pipeListLock_); + std::vector> newList; + for (auto pipe : curPipeList_) { + if (pipe->streamDescriptors_.empty() && IsSpecialPipe(pipe->routeFlag_)) { + newList.push_back(pipe); + } + } + return newList; +} + +bool AudioPipeManager::IsSpecialPipe(uint32_t routeFlag) +{ + AUDIO_INFO_LOG("Flag %{public}d", routeFlag); + if ((routeFlag & AUDIO_OUTPUT_FLAG_FAST) || + (routeFlag & AUDIO_INPUT_FLAG_FAST) || + (routeFlag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) { + return true; + } + return false; +} + +std::shared_ptr AudioPipeManager::GetPipeinfoByNameAndFlag( + const std::string adapterName, const uint32_t routeFlag) +{ + std::shared_lock pLock(pipeListLock_); + for (auto it : curPipeList_) { + if (it->adapterName_ == adapterName && it->routeFlag_ == routeFlag) { + return it; + } + } + AUDIO_ERR_LOG("Can not find pipe %{public}s", adapterName.c_str()); + return nullptr; +} + +std::string AudioPipeManager::GetAdapterNameBySessionId(uint32_t sessionId) +{ + AUDIO_INFO_LOG("Cur Pipe list size %{public}zu, sessionId %{public}u", curPipeList_.size(), sessionId); + for (auto pipeInfo : curPipeList_) { + for (auto desc : pipeInfo->streamDescriptors_) { + if (desc->sessionId_ != sessionId) { + continue; + } + AUDIO_INFO_LOG("adapter name: %{public}s", pipeInfo->moduleInfo_.name.c_str()); + return desc->newDeviceDescs_.front()->deviceType_ == DEVICE_TYPE_REMOTE_CAST ? + "RemoteCastInnerCapturer" : pipeInfo->moduleInfo_.name; + } + } + AUDIO_WARNING_LOG("cannot find sessionId: %{public}u", sessionId); + return ""; +} + +std::shared_ptr AudioPipeManager::GetProcessDeviceInfoBySessionId(uint32_t sessionId) +{ + AUDIO_INFO_LOG("Cur pipe list size %{public}zu, sessionId %{public}u", curPipeList_.size(), sessionId); + for (auto pipeInfo : curPipeList_) { + for (auto desc : pipeInfo->streamDescriptors_) { + if (desc->sessionId_ == sessionId) { + AUDIO_INFO_LOG("Device type: %{public}d", desc->newDeviceDescs_.front()->deviceType_); + return desc->newDeviceDescs_.front(); + } + } + } + AUDIO_ERR_LOG("Cannot find session: %{public}u", sessionId); + return nullptr; +} + +std::vector> AudioPipeManager::GetAllOutputStreamDescs() +{ + std::shared_lock pLock(pipeListLock_); + std::vector> streamDescs; + for (auto it : curPipeList_) { + if (it->pipeRole_ == PIPE_ROLE_OUTPUT) { + streamDescs.insert(streamDescs.end(), it->streamDescriptors_.begin(), it->streamDescriptors_.end()); + } + } + return streamDescs; +} + +std::vector> AudioPipeManager::GetAllInputStreamDescs() +{ + std::shared_lock pLock(pipeListLock_); + std::vector> streamDescs; + for (auto it : curPipeList_) { + if (it->pipeRole_ == PIPE_ROLE_INPUT) { + streamDescs.insert(streamDescs.end(), it->streamDescriptors_.begin(), it->streamDescriptors_.end()); + } + } + return streamDescs; +} + +std::shared_ptr AudioPipeManager::GetStreamDescById(uint32_t sessionId) +{ + std::shared_lock pLock(pipeListLock_); + return GetStreamDescByIdInner(sessionId); +} + +std::shared_ptr AudioPipeManager::GetStreamDescByIdInner(uint32_t sessionId) +{ + AUDIO_INFO_LOG("Cur pipe list size %{public}zu, sessionId %{public}u", curPipeList_.size(), sessionId); + for (auto pipeInfo : curPipeList_) { + for (auto desc : pipeInfo->streamDescriptors_) { + if (desc->sessionId_ == sessionId) { + return desc; + } + } + } + return nullptr; +} + +int32_t AudioPipeManager::GetStreamCount(const std::string adapterName, const uint32_t routeFlag) +{ + std::shared_lock pLock(pipeListLock_); + int32_t count = 0; + for (auto it : curPipeList_) { + if (it->adapterName_ == adapterName && it->routeFlag_ == routeFlag) { + count = it->streamDescriptors_.size(); + } + } + return count; +} + +uint32_t AudioPipeManager::GetPaIndexByIoHandle(AudioIOHandle id) +{ + std::shared_lock pLock(pipeListLock_); + for (auto it : curPipeList_) { + if (it->id_ == id) { + return it->paIndex_; + } + } + return HDI_INVALID_ID; +} + +void AudioPipeManager::UpdateRendererPipeInfos(std::vector> &pipeInfos) +{ + std::shared_lock pLock(pipeListLock_); + std::vector> tempList; + for (auto pipeInfo : curPipeList_) { + if (pipeInfo->pipeRole_ == PIPE_ROLE_INPUT) { + tempList.push_back(pipeInfo); + } + } + tempList.insert(tempList.end(), pipeInfos.begin(), pipeInfos.end()); + curPipeList_.clear(); + curPipeList_ = tempList; +} + +void AudioPipeManager::UpdateCapturerPipeInfos(std::vector> &pipeInfos) +{ + std::shared_lock pLock(pipeListLock_); + std::vector> tempList; + for (auto pipeInfo : curPipeList_) { + if (pipeInfo->pipeRole_ == PIPE_ROLE_OUTPUT) { + tempList.push_back(pipeInfo); + } + } + tempList.insert(tempList.end(), pipeInfos.begin(), pipeInfos.end()); + curPipeList_.clear(); + curPipeList_ = tempList; +} + +uint32_t AudioPipeManager::PcmOffloadSessionCount() +{ + std::shared_lock pLock(pipeListLock_); + for (auto pipeInfo : curPipeList_) { + if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_LOWPOWER) { + return pipeInfo->streamDescriptors_.size(); + } + } + return 0; +} + +void AudioPipeManager::Dump(std::string &dumpString) +{ + std::shared_lock pLock(pipeListLock_); + AUDIO_INFO_LOG("AudioPipeManager Dump Start!"); + dumpString += "\n^^^^^^^^^^AudioPipeManager Infos^^^^^^^^^^\n"; + dumpString += "\nTotalPipeNums: " + std::to_string(curPipeList_.size()) + "\n\n"; + + std::shared_ptr curPipeInfo = nullptr; + for (size_t pipeIdx = 0; pipeIdx < curPipeList_.size(); ++pipeIdx) { + curPipeInfo = curPipeList_[pipeIdx]; + dumpString += "\n**********Pipe " + std::to_string(pipeIdx + 1) + "**********\n"; // pipeinfo start + dumpString += "\nadapterName_: " + curPipeInfo->adapterName_ + "\tid_: " + std::to_string(curPipeInfo->id_) + + "\tpaIndex: " + std::to_string(curPipeInfo->paIndex_); + dumpString += "\nPipeRole_: "; + dumpString += (curPipeInfo->pipeRole_ == PIPE_ROLE_OUTPUT ? "OUTPUT" : "INPUT"); + dumpString += "\npipeAction_: " + std::to_string(curPipeInfo->pipeAction_); + dumpString += "\nrouteFlag_: " + std::to_string(curPipeInfo->routeFlag_); + for (size_t streamIdx = 0; streamIdx < curPipeInfo->streamDescriptors_.size(); ++streamIdx) { + dumpString += "\n----------Stream " + std::to_string(streamIdx + 1) + " in Pipe " + + std::to_string(pipeIdx + 1) + "----------\n"; // streaminfo start + curPipeInfo->streamDescriptors_[streamIdx]->Dump(dumpString); + dumpString += "\n"; //streaminfo end + } + dumpString += "\n"; // pipeinfo end + } + dumpString += "\n^^^^^^^^^^AudioPipeManager Infos^^^^^^^^^^\n"; +} + +uint32_t AudioPipeManager::GetModemCommunicationId() +{ + return modemCommunicationId_.load(); +} + +void AudioPipeManager::SetModemCommunicationId(uint32_t id) +{ + if (id < FIRST_SESSIONID || id > MAX_VALID_SESSIONID) { + AUDIO_ERR_LOG("Invalid id %{public}u", id); + } + modemCommunicationId_.store(id); +} + +void AudioPipeManager::ResetModemCommunicationId() +{ + AUDIO_INFO_LOG("In"); + modemCommunicationId_.store(0); +} + +} // namespace AudioStandard +} // namespace OHOS diff --git a/services/audio_policy/services/pipe/src/audio_pipe_selector.cpp b/services/audio_policy/services/pipe/src/audio_pipe_selector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c13ae109fcbb0c8cc895bfd89a3bc0a79bf81ad8 --- /dev/null +++ b/services/audio_policy/services/pipe/src/audio_pipe_selector.cpp @@ -0,0 +1,383 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef LOG_TAG +#define LOG_TAG "AudioPipeSelector" +#endif + +#include "audio_pipe_selector.h" +#include "audio_stream_collector.h" +#include "audio_stream_info.h" +#include "audio_definition_adapter_info.h" +#include + +namespace OHOS { +namespace AudioStandard { + +static std::map flagPipeTypeMap_ = { + {AUDIO_OUTPUT_FLAG_NORMAL, PIPE_TYPE_NORMAL_OUT}, + {AUDIO_INPUT_FLAG_NORMAL, PIPE_TYPE_NORMAL_IN}, + {AUDIO_OUTPUT_FLAG_FAST, PIPE_TYPE_NORMAL_OUT}, + {AUDIO_INPUT_FLAG_FAST, PIPE_TYPE_NORMAL_IN}, + {AUDIO_OUTPUT_FLAG_LOWPOWER, PIPE_TYPE_OFFLOAD}, + {AUDIO_OUTPUT_FLAG_MULTICHANNEL, PIPE_TYPE_MULTICHANNEL}, + {AUDIO_OUTPUT_FLAG_DIRECT, PIPE_TYPE_DIRECT_OUT}, +}; + +AudioPipeSelector::AudioPipeSelector() : configManager_(AudioPolicyConfigManager::GetInstance()) +{ +} + +std::shared_ptr AudioPipeSelector::GetPipeSelector() +{ + static std::shared_ptr instance = std::make_shared(); + return instance; +} + +std::vector> AudioPipeSelector::FetchPipeAndExecute( + std::shared_ptr &streamDesc) +{ + std::vector> pipeInfoList = AudioPipeManager::GetPipeManager()->GetPipeList(); + + if (streamDesc->routeFlag_ == AUDIO_FLAG_NONE) { + AUDIO_INFO_LOG("Start get route flag"); + ScanPipeListForStreamDesc(pipeInfoList, streamDesc); + } + AUDIO_INFO_LOG("Pipe list size: %{public}zu, routeFlag: %{public}u", pipeInfoList.size(), streamDesc->routeFlag_); + + std::vector> selectedPipeInfoList {}; + for (auto &curPipeInfo : pipeInfoList) { + if (curPipeInfo->pipeRole_ == static_cast(streamDesc->audioMode_)) { + selectedPipeInfoList.push_back(curPipeInfo); + } + } + + streamDesc->streamAction_ = AUDIO_STREAM_ACTION_NEW; + std::shared_ptr streamPropInfo = std::make_shared(); + configManager_.GetStreamPropInfo(streamDesc, streamPropInfo); + std::shared_ptr pipeInfoPtr = streamPropInfo->pipeInfo_.lock(); + if (pipeInfoPtr == nullptr) { + AUDIO_ERR_LOG("Pipe info is null"); + return selectedPipeInfoList; + } + for (auto &pipeInfo : selectedPipeInfoList) { + std::shared_ptr adapterInfoPtr = pipeInfoPtr->adapterInfo_.lock(); + if (adapterInfoPtr == nullptr) { + AUDIO_ERR_LOG("Adapter info is null"); + continue; + } + AUDIO_INFO_LOG("[Cur][XML]: {adapterName}[%{public}s][%{public}s], {routeFlag}[%{public}u][%{public}u]", + pipeInfo->adapterName_.c_str(), adapterInfoPtr->adapterName.c_str(), + pipeInfo->routeFlag_, streamDesc->routeFlag_); + + if (pipeInfo->adapterName_ == adapterInfoPtr->adapterName && + pipeInfo->routeFlag_ == streamDesc->routeFlag_) { + pipeInfo->streamDescriptors_.push_back(streamDesc); + pipeInfo->streamDescMap_[streamDesc->sessionId_] = streamDesc; + pipeInfo->pipeAction_ = PIPE_ACTION_UPDATE; + return selectedPipeInfoList; + } + } + AudioPipeInfo info = {}; + ConvertStreamDescToPipeInfo(streamDesc, streamPropInfo, info); + info.pipeAction_ = PIPE_ACTION_NEW; + selectedPipeInfoList.push_back(std::make_shared(info)); + return selectedPipeInfoList; +} + +std::vector> AudioPipeSelector::FetchPipesAndExecute( + std::vector> &streamDescs) +{ + std::vector> pipeInfoList = AudioPipeManager::GetPipeManager()->GetPipeList(); + + std::vector> selectedPipeInfoList{}; + if (streamDescs.size() == 0) { + return selectedPipeInfoList; + } + for (auto &curPipeInfo : pipeInfoList) { + if (curPipeInfo->pipeRole_ == static_cast(streamDescs[0]->audioMode_)) { + selectedPipeInfoList.push_back(curPipeInfo); + } + } + AUDIO_INFO_LOG("Selected pipe size: %{public}zu", selectedPipeInfoList.size()); + + //Record current pipe--stream info for later use (Judge stream action) + std::map> streamDescToPipeInfo; + for (auto &pipeInfo : selectedPipeInfoList) { + pipeInfo->pipeAction_ = PIPE_ACTION_DEFAULT; + for (auto &streamDesc : pipeInfo->streamDescriptors_) { + streamDescToPipeInfo[streamDesc->sessionId_] = pipeInfo; + } + } + + // deep copy to new pipeList + std::vector> newPipeInfoList; + for (auto &pipeInfo : selectedPipeInfoList) { + std::shared_ptr temp = std::make_shared(*pipeInfo); + temp->streamDescriptors_.clear(); + temp->streamDescMap_.clear(); + newPipeInfoList.push_back(temp); + } + + SortStreamDescsByStartTime(streamDescs); + // traversal each streamDesc + for (auto &streamDesc : streamDescs) { + std::string adapterName = GetAdapterNameByStreamDesc(streamDesc); + AUDIO_INFO_LOG("adapter name: %{public}s", adapterName.c_str()); + ScanPipeListForStreamDesc(newPipeInfoList, streamDesc); // Get route flag and apply concurrency + bool isFindPipeInfo = IsPipeExist(newPipeInfoList, adapterName, streamDesc, streamDescToPipeInfo); + if (!isFindPipeInfo) { + AUDIO_INFO_LOG("Cannot find pipe info: %{public}s", adapterName.c_str()); + HandlePipeNotExist(newPipeInfoList, streamDesc, streamDescToPipeInfo); + } + } + // Check is pipe update + for (auto &pipeInfo : selectedPipeInfoList) { + if (pipeInfo->streamDescriptors_.size() == 0) { + pipeInfo->pipeAction_ = PIPE_ACTION_DEFAULT; + } + } + return newPipeInfoList; +} + +void AudioPipeSelector::HandlePipeNotExist(std::vector> &newPipeInfoList, + std::shared_ptr &streamDesc, + std::map> &streamDescToPipeInfo) +{ + AudioPipeInfo pipeInfo = {}; + std::shared_ptr streamPropInfo = std::make_shared(); + configManager_.GetStreamPropInfo(streamDesc, streamPropInfo); + ConvertStreamDescToPipeInfo(streamDesc, streamPropInfo, pipeInfo); + pipeInfo.pipeAction_ = PIPE_ACTION_NEW; + std::shared_ptr tempPipeInfo = std::make_shared(pipeInfo); + newPipeInfoList.push_back(tempPipeInfo); + streamDesc->streamAction_ = JudgeStreamAction(tempPipeInfo, streamDescToPipeInfo[streamDesc->sessionId_]); + AUDIO_INFO_LOG("Stream action: %{public}d", streamDesc->streamAction_); +} + +bool AudioPipeSelector::IsPipeExist(std::vector> &newPipeInfoList, + std::string &adapterName, std::shared_ptr &streamDesc, + std::map> &streamDescToPipeInfo) +{ + bool isFindPipeInfo = false; + for (auto &newPipeInfo : newPipeInfoList) { + if (newPipeInfo->adapterName_ != adapterName || newPipeInfo->routeFlag_ != streamDesc->routeFlag_) { + continue; + } + newPipeInfo->streamDescriptors_.push_back(streamDesc); + if (streamDescToPipeInfo.find(streamDesc->sessionId_) == streamDescToPipeInfo.end()) { + AUDIO_INFO_LOG("Cannot find session: %{public}u", streamDesc->sessionId_); + } else { + streamDesc->streamAction_ = + JudgeStreamAction(newPipeInfo, streamDescToPipeInfo[streamDesc->sessionId_]); + AUDIO_INFO_LOG("Stream action: %{public}d", streamDesc->streamAction_); + } + newPipeInfo->streamDescMap_[streamDesc->sessionId_] = streamDesc; + newPipeInfo->pipeAction_ = PIPE_ACTION_UPDATE; + isFindPipeInfo = true; + break; + } + return isFindPipeInfo; +} + +void AudioPipeSelector::ScanPipeListForStreamDesc(std::vector> &pipeInfoList, + std::shared_ptr streamDesc) +{ + streamDesc->routeFlag_ = GetRouteFlagByStreamDesc(streamDesc); + AUDIO_INFO_LOG("Route flag: %{public}u", streamDesc->routeFlag_); + + for (auto &pipeInfo : pipeInfoList) { + bool isUpdate = false; + for (auto &streamDescInPipe : pipeInfo->streamDescriptors_) { + isUpdate = ProcessConcurrency(streamDescInPipe, streamDesc); + AUDIO_INFO_LOG("isUpdate: %{public}d, action: %{public}d", isUpdate, streamDescInPipe->streamAction_); + } + pipeInfo->pipeAction_ = isUpdate ? PIPE_ACTION_UPDATE : PIPE_ACTION_DEFAULT; + } + AUDIO_INFO_LOG("Route flag after concurrency: %{public}u", streamDesc->routeFlag_); +} + +AudioPipeType AudioPipeSelector::GetPipeType(uint32_t flag, AudioMode audioMode) +{ + AUDIO_INFO_LOG("Route flag: %{public}u", flag); + if (audioMode == AUDIO_MODE_PLAYBACK) { + if (flag & AUDIO_OUTPUT_FLAG_FAST) { + if (flag & AUDIO_OUTPUT_FLAG_VOIP) { + return PIPE_TYPE_CALL_OUT; + } else { + return PIPE_TYPE_LOWLATENCY_OUT; + } + } else if (flag & AUDIO_OUTPUT_FLAG_DIRECT) { + if (flag & AUDIO_OUTPUT_FLAG_VOIP) { + return PIPE_TYPE_CALL_OUT; + } else { + return PIPE_TYPE_DIRECT_OUT; + } + } else if (flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { + return PIPE_TYPE_OFFLOAD; + } else if (flag & AUDIO_OUTPUT_FLAG_MULTICHANNEL) { + return PIPE_TYPE_MULTICHANNEL; + } else { + return PIPE_TYPE_NORMAL_OUT; + } + } else { + if (flag & AUDIO_INPUT_FLAG_FAST) { + if (flag & AUDIO_INPUT_FLAG_VOIP) { + return PIPE_TYPE_CALL_IN; + } else { + return PIPE_TYPE_LOWLATENCY_IN; + } + } else { + return PIPE_TYPE_NORMAL_IN; + } + } +} + +bool AudioPipeSelector::ProcessConcurrency(std::shared_ptr stream, + std::shared_ptr cmpStream) +{ + bool isUpdate = false; + std::map, ConcurrencyAction> ruleMap = + AudioStreamCollector::GetAudioStreamCollector().GetConcurrencyMap(); + ConcurrencyAction action = ruleMap[std::make_pair(GetPipeType(stream->routeFlag_, stream->audioMode_), + GetPipeType(cmpStream->routeFlag_, cmpStream->audioMode_))]; + uint32_t newFlag; + AUDIO_INFO_LOG("Action: %{public}u", action); + switch (action) { + case PLAY_BOTH: + stream->streamAction_ = AUDIO_STREAM_ACTION_DEFAULT; + break; + case CONCEDE_INCOMING: + stream->streamAction_ = AUDIO_STREAM_ACTION_DEFAULT; + cmpStream->routeFlag_ = cmpStream->audioMode_ == AUDIO_MODE_PLAYBACK ? + AUDIO_OUTPUT_FLAG_NORMAL : AUDIO_INPUT_FLAG_NORMAL; + break; + case CONCEDE_EXISTING: + isUpdate = true; + newFlag = stream->audioMode_ == AUDIO_MODE_PLAYBACK ? + AUDIO_OUTPUT_FLAG_NORMAL : AUDIO_INPUT_FLAG_NORMAL; + stream->streamAction_ = AUDIO_STREAM_ACTION_RECREATE; + stream->routeFlag_ = newFlag; + break; + default: + break; + } + return isUpdate; +} + +uint32_t AudioPipeSelector::GetRouteFlagByStreamDesc(std::shared_ptr streamDesc) +{ + uint32_t flag = AUDIO_FLAG_NONE; + CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, flag, "streamDesc is nullptr"); + flag = configManager_.GetRouteFlag(streamDesc); + return flag; +} + +std::string AudioPipeSelector::GetAdapterNameByStreamDesc(std::shared_ptr streamDesc) +{ + std::string name = ""; + CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, name, "streamDesc is nullptr"); + std::shared_ptr streamPropInfo = std::make_shared(); + configManager_.GetStreamPropInfo(streamDesc, streamPropInfo); + + std::shared_ptr pipeInfoPtr = streamPropInfo->pipeInfo_.lock(); + if (pipeInfoPtr == nullptr) { + AUDIO_ERR_LOG("Adapter info is null"); + return ""; + } + + std::shared_ptr adapterInfoPtr = pipeInfoPtr->adapterInfo_.lock(); + if (adapterInfoPtr == nullptr) { + AUDIO_ERR_LOG("Pipe info is null"); + return ""; + } + name = adapterInfoPtr->adapterName; + return name; +} + +void AudioPipeSelector::ConvertStreamDescToPipeInfo(std::shared_ptr streamDesc, + std::shared_ptr streamPropInfo, AudioPipeInfo &info) +{ + std::shared_ptr pipeInfoPtr = streamPropInfo->pipeInfo_.lock(); + if (pipeInfoPtr == nullptr) { + AUDIO_ERR_LOG("Adapter info is null"); + return ; + } + + std::shared_ptr adapterInfoPtr = pipeInfoPtr->adapterInfo_.lock(); + if (adapterInfoPtr == nullptr) { + AUDIO_ERR_LOG("Pipe info is null"); + return ; + } + + info.moduleInfo_.format = AudioDefinitionPolicyUtils::enumToFormatStr[streamPropInfo->format_]; + info.moduleInfo_.rate = std::to_string(streamPropInfo->sampleRate_); + info.moduleInfo_.channels = std::to_string(AudioDefinitionPolicyUtils::ConvertLayoutToAudioChannel( + streamPropInfo->channelLayout_)); + info.moduleInfo_.bufferSize = std::to_string(streamPropInfo->bufferSize_); + + info.moduleInfo_.lib = pipeInfoPtr->paProp_.lib_; + info.moduleInfo_.role = pipeInfoPtr->paProp_.role_; + info.moduleInfo_.name = pipeInfoPtr->paProp_.moduleName_; + info.moduleInfo_.adapterName = adapterInfoPtr->adapterName; + + AUDIO_INFO_LOG("Pipe name: %{public}s", pipeInfoPtr->name_.c_str()); + if (pipeInfoPtr->name_ == "multichannel_output") { + info.moduleInfo_.className = "multichannel"; + info.moduleInfo_.fileName = "mch_dump_file"; + info.moduleInfo_.fixedLatency = "1"; // for fix max request + info.moduleInfo_.bufferSize = + std::to_string(((streamPropInfo->bufferSize_ / std::stoul(info.moduleInfo_.channels)) * STEREO)); + AUDIO_INFO_LOG("Buffer size: %{public}s", info.moduleInfo_.bufferSize.c_str()); + } else if (pipeInfoPtr->name_ == "offload_output") { + info.moduleInfo_.className = "offload"; + info.moduleInfo_.offloadEnable = "1"; + info.moduleInfo_.fixedLatency = "1"; + info.moduleInfo_.fileName = "offload_dump_file"; + } + + info.moduleInfo_.deviceType = std::to_string(streamDesc->newDeviceDescs_[0]->deviceType_); + info.moduleInfo_.networkId = streamDesc->newDeviceDescs_[0]->networkId_; + info.moduleInfo_.sourceType = std::to_string(streamDesc->capturerInfo_.sourceType); + + info.streamDescriptors_.push_back(streamDesc); + info.streamDescMap_[streamDesc->sessionId_] = streamDesc; + info.routeFlag_ = streamDesc->routeFlag_; + info.adapterName_ = adapterInfoPtr->adapterName; + info.pipeRole_ = pipeInfoPtr->role_; +} + +AudioStreamAction AudioPipeSelector::JudgeStreamAction( + std::shared_ptr newPipe, std::shared_ptr oldPipe) +{ + if (newPipe->adapterName_ == oldPipe->adapterName_ && newPipe->routeFlag_ == oldPipe->routeFlag_) { + return AUDIO_STREAM_ACTION_DEFAULT; + } + if (oldPipe->routeFlag_ == AUDIO_OUTPUT_FLAG_FAST || newPipe->routeFlag_ == AUDIO_OUTPUT_FLAG_FAST || + oldPipe->routeFlag_ == AUDIO_OUTPUT_FLAG_DIRECT || newPipe->routeFlag_ == AUDIO_OUTPUT_FLAG_DIRECT) { + return AUDIO_STREAM_ACTION_RECREATE; + } else { + return AUDIO_STREAM_ACTION_MOVE; + } +} + +void AudioPipeSelector::SortStreamDescsByStartTime(std::vector> &streamDescs) +{ + sort(streamDescs.begin(), streamDescs.end(), [](const std::shared_ptr &streamDesc1, + const std::shared_ptr &streamDesc2) { + return streamDesc1->startTimeStamp_ < streamDesc2->startTimeStamp_; + }); +} +} // namespace AudioStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/audio_policy/test/unittest/audio_device_common_unit_test/src/audio_device_common_unit_test.cpp b/services/audio_policy/test/unittest/audio_device_common_unit_test/src/audio_device_common_unit_test.cpp index 7e968255e2b4f046224afb870249dc814358fbda..a1aaae962b3aa75602b8f703713ee85ca4597292 100644 --- a/services/audio_policy/test/unittest/audio_device_common_unit_test/src/audio_device_common_unit_test.cpp +++ b/services/audio_policy/test/unittest/audio_device_common_unit_test/src/audio_device_common_unit_test.cpp @@ -411,8 +411,6 @@ HWTEST_F(AudioDeviceCommonUnitTest, AudioDeviceCommon_014, TestSize.Level1) int32_t flags = 1; std::string networkId = ""; AudioSamplingRate samplingRate = SAMPLE_RATE_8000; - const std::unordered_map adapterInfoMap; - audioDeviceCommon.audioConfigManager_.OnAudioPolicyXmlParsingCompleted(adapterInfoMap); int32_t ret = audioDeviceCommon.GetPreferredOutputStreamTypeInner(streamUsage, deviceType, flags, networkId, samplingRate); EXPECT_EQ(AUDIO_FLAG_NORMAL, ret); @@ -432,9 +430,6 @@ HWTEST_F(AudioDeviceCommonUnitTest, AudioDeviceCommon_015, TestSize.Level1) std::string networkId = ""; AudioSamplingRate samplingRate = SAMPLE_RATE_8000; AudioAdapterInfo adapterInfo = {}; - std::unordered_map adapterInfoMap = {}; - adapterInfoMap.insert({AdaptersType::TYPE_PRIMARY, adapterInfo}); - audioDeviceCommon.audioConfigManager_.OnAudioPolicyXmlParsingCompleted(adapterInfoMap); int32_t ret = audioDeviceCommon.GetPreferredOutputStreamTypeInner(streamUsage, deviceType, flags, networkId, samplingRate); EXPECT_EQ(AUDIO_FLAG_INVALID, ret); @@ -491,8 +486,6 @@ HWTEST_F(AudioDeviceCommonUnitTest, AudioDeviceCommon_018, TestSize.Level1) int32_t flags = 1; std::string networkId = "LocalDevice"; AudioSamplingRate samplingRate = SAMPLE_RATE_16000; - const std::unordered_map adapterInfoMap; - audioDeviceCommon.audioConfigManager_.OnAudioPolicyXmlParsingCompleted(adapterInfoMap); int32_t ret = audioDeviceCommon.GetPreferredInputStreamTypeInner(sourceType, deviceType, flags, networkId, samplingRate); EXPECT_EQ(AUDIO_FLAG_INVALID, ret); @@ -512,9 +505,6 @@ HWTEST_F(AudioDeviceCommonUnitTest, AudioDeviceCommon_019, TestSize.Level1) std::string networkId = "LocalDevice"; AudioSamplingRate samplingRate = SAMPLE_RATE_16000; AudioAdapterInfo adapterInfo = {}; - std::unordered_map adapterInfoMap = {}; - adapterInfoMap.insert({AdaptersType::TYPE_PRIMARY, adapterInfo}); - audioDeviceCommon.audioConfigManager_.OnAudioPolicyXmlParsingCompleted(adapterInfoMap); int32_t ret = audioDeviceCommon.GetPreferredInputStreamTypeInner(sourceType, deviceType, flags, networkId, samplingRate); EXPECT_EQ(AUDIO_FLAG_INVALID, ret); diff --git a/services/audio_policy/test/unittest/audio_ec_manager_unit_test/src/audio_ec_manager_unit_test.cpp b/services/audio_policy/test/unittest/audio_ec_manager_unit_test/src/audio_ec_manager_unit_test.cpp index 9a3bf530e82d7149feae41635cac73b91debf0a8..0a14c1dc8afd8388a1837aba61890819e2d48ec6 100644 --- a/services/audio_policy/test/unittest/audio_ec_manager_unit_test/src/audio_ec_manager_unit_test.cpp +++ b/services/audio_policy/test/unittest/audio_ec_manager_unit_test/src/audio_ec_manager_unit_test.cpp @@ -34,11 +34,11 @@ void AudioEcManagerUnitTest::TearDown(void) {} HWTEST_F(AudioEcManagerUnitTest, AudioEcManager_001, TestSize.Level1) { std::string halName = DP_CLASS; - StreamPropInfo outModuleInfo; + std::shared_ptr outModuleInfo; AudioEcManager& ecManager(AudioEcManager::GetInstance()); std::string sRet; - outModuleInfo.sampleRate_ = 41000; + outModuleInfo->sampleRate_ = 41000; sRet = ecManager.GetEcSamplingRate(halName, outModuleInfo); EXPECT_EQ(sRet, "41000"); @@ -68,11 +68,11 @@ HWTEST_F(AudioEcManagerUnitTest, AudioEcManager_001, TestSize.Level1) HWTEST_F(AudioEcManagerUnitTest, AudioEcManager_002, TestSize.Level1) { std::string halName = DP_CLASS; - StreamPropInfo outModuleInfo; + std::shared_ptr outModuleInfo; AudioEcManager& ecManager(AudioEcManager::GetInstance()); std::string sRet; - outModuleInfo.channelLayout_ = 3; + outModuleInfo->channelLayout_ = CH_LAYOUT_STEREO; sRet = ecManager.GetEcChannels(halName, outModuleInfo); EXPECT_EQ(sRet, "3"); @@ -101,11 +101,11 @@ HWTEST_F(AudioEcManagerUnitTest, AudioEcManager_002, TestSize.Level1) HWTEST_F(AudioEcManagerUnitTest, AudioEcManager_003, TestSize.Level1) { std::string halName = DP_CLASS; - StreamPropInfo outModuleInfo; + std::shared_ptr outModuleInfo; AudioEcManager& ecManager(AudioEcManager::GetInstance()); std::string sRet; - outModuleInfo.format_ = "3"; + outModuleInfo->format_ = SAMPLE_S32LE; sRet = ecManager.GetEcFormat(halName, outModuleInfo); EXPECT_EQ(sRet, "3"); @@ -197,7 +197,7 @@ HWTEST_F(AudioEcManagerUnitTest, AudioEcManager_005, TestSize.Level1) { std::string role = ROLE_SOURCE; DeviceType deviceType = DEVICE_TYPE_SPEAKER; - PipeInfo pipeInfo; + std::shared_ptr pipeInfo; AudioEcManager& ecManager(AudioEcManager::GetInstance()); int32_t ret; diff --git a/services/audio_policy/test/unittest/audio_policy_service_unit_test/src/audio_policy_service_first_unit_test.cpp b/services/audio_policy/test/unittest/audio_policy_service_unit_test/src/audio_policy_service_first_unit_test.cpp index 0e78ee3b9f7e473dac64fafa8bf655b3446c3b15..9d33f2a1540dd5265304512c585d023a05b7c33a 100644 --- a/services/audio_policy/test/unittest/audio_policy_service_unit_test/src/audio_policy_service_first_unit_test.cpp +++ b/services/audio_policy/test/unittest/audio_policy_service_unit_test/src/audio_policy_service_first_unit_test.cpp @@ -1903,9 +1903,6 @@ HWTEST_F(AudioPolicyServiceUnitTest, OnCapturerSessionAdded_001, TestSize.Level1 pipeInfo.streamPropInfos_.push_back(streamPropInfo); pipeInfos_.push_back(pipeInfo); adapterInfo.pipeInfos_ = pipeInfos_; - GetServerPtr()->audioPolicyService_.audioConfigManager_.adapterInfoMap_ = {}; - GetServerPtr()->audioPolicyService_.audioConfigManager_.adapterInfoMap_.insert({AdaptersType::TYPE_PRIMARY, - adapterInfo}); int32_t ret = SUCCESS; GetServerPtr()->audioPolicyService_.audioEcManager_.normalSourceOpened_ = SOURCE_TYPE_VOICE_CALL; diff --git a/services/audio_policy/test/unittest/audio_policy_service_unit_test/src/audio_policy_service_second_unit_test.cpp b/services/audio_policy/test/unittest/audio_policy_service_unit_test/src/audio_policy_service_second_unit_test.cpp index 370f08fe4082b298254ed7bddbe4cc08538df693..89745f42e389ceb3b9a8a1e0eaad08c8a9b264cc 100644 --- a/services/audio_policy/test/unittest/audio_policy_service_unit_test/src/audio_policy_service_second_unit_test.cpp +++ b/services/audio_policy/test/unittest/audio_policy_service_unit_test/src/audio_policy_service_second_unit_test.cpp @@ -858,7 +858,7 @@ HWTEST_F(AudioPolicyServiceExtUnitTest, GetPipeInfoByDeviceTypeForEc_001, TestSi auto server = GetServerUtil::GetServerPtr(); std::string role = ROLE_SOURCE; DeviceType deviceType = DeviceType::DEVICE_TYPE_SPEAKER; - PipeInfo pipeInfo; + std::shared_ptr pipeInfo; int32_t ret = server->audioPolicyService_.audioEcManager_.GetPipeInfoByDeviceTypeForEc(role, deviceType, pipeInfo); EXPECT_EQ(ret, SUCCESS); @@ -877,7 +877,7 @@ HWTEST_F(AudioPolicyServiceExtUnitTest, GetEcSamplingRate_001, TestSize.Level1) { auto server = GetServerUtil::GetServerPtr(); std::string halName; - StreamPropInfo outModuleInfo; + std::shared_ptr outModuleInfo; std::string ecSamplingRate; halName = DP_CLASS; @@ -912,7 +912,7 @@ HWTEST_F(AudioPolicyServiceExtUnitTest, GetEcFormat_001, TestSize.Level1) { auto server = GetServerUtil::GetServerPtr(); std::string halName; - StreamPropInfo outModuleInfo; + std::shared_ptr outModuleInfo; std::string ecFormat; halName = DP_CLASS; @@ -948,7 +948,7 @@ HWTEST_F(AudioPolicyServiceExtUnitTest, GetEcChannels_001, TestSize.Level1) auto server = GetServerUtil::GetServerPtr(); std::string halName; std::string ecChannels; - StreamPropInfo outModuleInfo; + std::shared_ptr outModuleInfo; halName = DP_CLASS; server->audioPolicyService_.audioEcManager_.dpSinkModuleInfo_.channels = "666"; @@ -1021,7 +1021,7 @@ HWTEST_F(AudioPolicyServiceExtUnitTest, UpdateStreamCommonInfo_001, TestSize.Lev { auto server = GetServerUtil::GetServerPtr(); AudioModuleInfo moduleInfo; - StreamPropInfo targetInfo; + PipeStreamPropInfo targetInfo; SourceType sourceType = SourceType::SOURCE_TYPE_MIC; server->audioPolicyService_.audioEcManager_.isEcFeatureEnable_ = true; diff --git a/services/audio_service/BUILD.gn b/services/audio_service/BUILD.gn index 44e7390e7baf5131476860623a889b05b5550941..90fa1dfdc2e96775a677b3af2770371166c90b8e 100644 --- a/services/audio_service/BUILD.gn +++ b/services/audio_service/BUILD.gn @@ -45,8 +45,9 @@ ohos_shared_library("audio_common") { include_dirs = [ "common/include", "common/include/limiter", - "../audio_policy/server/include", "common/include/dfx", + "../audio_policy/server/include", + "../audio_policy/services/pipe/include", "../../frameworks/native/audioschedule/include", "../../interfaces/inner_api/native/audiocommon/include", ] @@ -133,9 +134,12 @@ config("audio_client_public_config") { "../audio_policy/common/include", "../audio_policy/util/include", "../audio_policy/server/include", + "../../frameworks/native/audiodefinitions/include", "../../frameworks/native/audiopolicy/include", "../../frameworks/native/audiostream/include", "../../frameworks/native/audioutils/include", + "../../frameworks/native/hdiadapter_new/include", + "../../frameworks/native/hdiadapter_new/include/common", "../../interfaces/inner_api/native/audiocapturer/include", "../../interfaces/inner_api/native/audiocommon/include", "../../interfaces/inner_api/native/audiomanager/include", @@ -303,7 +307,11 @@ config("audio_service_config") { "client/include", "server/include", "server/include/config", + "../audio_policy/common/definitions/include", + "../audio_policy/server/include/service/common", "../audio_policy/server/include/service/effect", + "../audio_policy/services/pipe/include", + "../../frameworks/native/audiodefinitions/include", "../../frameworks/native/audioeffect/include", "../../frameworks/native/offlineaudioeffect/include", "../../frameworks/native/audioinnercall/include", @@ -313,6 +321,7 @@ config("audio_service_config") { "../../frameworks/native/audioutils/include", "../../frameworks/native/playbackcapturer/include", "../../frameworks/native/hdiadapter_new/include", + "../../frameworks/native/hdiadapter_new/include/common", "../../interfaces/inner_api/native/audiocommon/include", "../../interfaces/inner_api/native/audiomanager/include", ] @@ -350,6 +359,8 @@ audio_ohos_library("audio_process_service") { "server/src/audio_process_stub.cpp", "server/src/audio_service.cpp", "server/src/capturer_in_server.cpp", + "server/src/core_service_handler.cpp", + "server/src/core_service_provider_proxy.cpp", "server/src/i_stream_manager.cpp", "server/src/ipc_offline_stream_stub.cpp", "server/src/ipc_stream_in_server.cpp", @@ -568,12 +579,14 @@ ohos_shared_library("audio_sasdk") { include_dirs = [ "../../interfaces/inner_api/native/audiocommon/include", "../../interfaces/inner_api/native/audiosasdk/include", + "../../frameworks/native/audiodefinitions/include", ] public_configs = [ ":audio_sasdk_public_config" ] deps = [ ":audio_common", + "../../frameworks/native/audiodefinitions:audio_definitions", "../audio_policy:audio_policy_client", ] diff --git a/services/audio_service/client/include/audio_manager_base.h b/services/audio_service/client/include/audio_manager_base.h index 660ea1d03d17d179283cf60b91549cb352eeddb4..0f0793c6ddbdb0baa348f15a2d6866cd80be6d1a 100644 --- a/services/audio_service/client/include/audio_manager_base.h +++ b/services/audio_service/client/include/audio_manager_base.h @@ -23,6 +23,8 @@ #include "audio_effect.h" #include "pulseaudio_ipc_interface_code.h" #include "audio_asr.h" +#include "hdi_adapter_type.h" +#include "hdi_adapter_info.h" namespace OHOS { namespace AudioStandard { @@ -320,6 +322,13 @@ public: */ virtual int32_t RegiestPolicyProvider(const sptr &object) = 0; + /** + * Regiest CoreService provider. + * + * @return result code. + */ + virtual int32_t RegistCoreServiceProvider(const sptr &object) = 0; + /** * Create playback capturer manager. * @@ -528,6 +537,66 @@ public: * @return none. */ virtual void UnloadHdiAdapter(uint32_t devMgrType, const std::string &adapterName, bool force) = 0; + + /** + * Create render of hal. + * + * @param deviceClass specify render type. + * @param idInfo info of render id. + * @param attr attribute string of render. + * + * @return Returns render id if success, HDI_INVALID_ID else. + */ + virtual uint32_t CreateHdiSinkPort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSinkAttr &attr) = 0; + + /** + * Create render of hal. + * + * @param idBase specify render type. + * @param idType specify sink type. + * @param info extra info of render. + * @param attr attribute string of render. + * + * @return Returns render id if success, HDI_INVALID_ID else. + */ + virtual uint32_t CreateSinkPort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSinkAttr &attr) = 0; + + /** + * Create capture of hal. + * + * @param deviceClass specify capture type. + * @param idInfo info of capture id. + * @param attr attribute string of capture. + * + * @return Returns capture id if success, HDI_INVALID_ID else. + */ + virtual uint32_t CreateHdiSourcePort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSourceAttr &attr) = 0; + + /** + * Create capture of hal. + * + * @param idBase specify capture type. + * @param idType specify sink type. + * @param info extra info of capture. + * @param attr attribute string of capture. + * + * @return Returns capture id if success, HDI_INVALID_ID else. + */ + virtual uint32_t CreateSourcePort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSourceAttr &attr) = 0; + + /** + * Destroy render/capture of hal. + * + * @param id specify which render or capture to destroy. + * + * @return none. + */ + virtual void DestroyHdiPort(uint32_t id) = 0; + virtual void SetDeviceConnectedFlag(bool flag) = 0; public: DECLARE_INTERFACE_DESCRIPTOR(u"IStandardAudioService"); @@ -563,6 +632,7 @@ private: int HandleSetOutputDeviceSink(MessageParcel &data, MessageParcel &reply); int HandleCreatePlaybackCapturerManager(MessageParcel &data, MessageParcel &reply); int HandleRegiestPolicyProvider(MessageParcel &data, MessageParcel &reply); + int HandleRegistCoreServiceProvider(MessageParcel &data, MessageParcel &reply); int HandleSetWakeupSourceCallback(MessageParcel &data, MessageParcel &reply); int HandleUpdateSpatializationState(MessageParcel &data, MessageParcel &reply); int HandleUpdateSpatialDeviceType(MessageParcel& data, MessageParcel& reply); @@ -617,12 +687,18 @@ private: #endif int HandleLoadHdiAdapter(MessageParcel &data, MessageParcel &reply); int HandleUnloadHdiAdapter(MessageParcel &data, MessageParcel &reply); + int HandleCreateHdiSinkPort(MessageParcel &data, MessageParcel &reply); + int HandleCreateSinkPort(MessageParcel &data, MessageParcel &reply); + int HandleCreateHdiSourcePort(MessageParcel &data, MessageParcel &reply); + int HandleCreateSourcePort(MessageParcel &data, MessageParcel &reply); + int HandleDestroyHdiPort(MessageParcel &data, MessageParcel &reply); int HandleDeviceConnectedFlag(MessageParcel &data, MessageParcel &reply); int HandleSecondPartCode(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); int HandleThirdPartCode(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); int HandleFourthPartCode(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); int HandleFifthPartCode(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + int HandleSixthPartCode(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); }; } // namespace AudioStandard } // namespace OHOS diff --git a/services/audio_service/client/include/audio_manager_proxy.h b/services/audio_service/client/include/audio_manager_proxy.h index 7e6ed5e72db429336bb7bb1c61211e17fa909cda..58a14d4a80462bcebf793e16a2b8d1476b2aa5d5 100644 --- a/services/audio_service/client/include/audio_manager_proxy.h +++ b/services/audio_service/client/include/audio_manager_proxy.h @@ -65,6 +65,7 @@ public: void SetOutputDeviceSink(int32_t deviceType, std::string &sinkName) override; bool CreatePlaybackCapturerManager() override; int32_t RegiestPolicyProvider(const sptr &object) override; + int32_t RegistCoreServiceProvider(const sptr &object) override; int32_t UpdateSpatializationState(AudioSpatializationState spatializationState) override; int32_t UpdateSpatialDeviceType(AudioSpatialDeviceType spatialDeviceType) override; int32_t NotifyStreamVolumeChanged(AudioStreamType streamType, float volume) override; @@ -123,6 +124,15 @@ public: #endif int32_t LoadHdiAdapter(uint32_t devMgrType, const std::string &adapterName) override; void UnloadHdiAdapter(uint32_t devMgrType, const std::string &adapterName, bool force) override; + uint32_t CreateHdiSinkPort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSinkAttr &attr) override; + uint32_t CreateSinkPort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSinkAttr &attr) override; + uint32_t CreateHdiSourcePort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSourceAttr &attr) override; + uint32_t CreateSourcePort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSourceAttr &attr) override; + void DestroyHdiPort(uint32_t id) override; void SetDeviceConnectedFlag(bool flag) override; private: static inline BrokerDelegator delegator_; diff --git a/services/audio_service/client/include/core_service_provider_stub.h b/services/audio_service/client/include/core_service_provider_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..687d1b7eb9b06e204e9dd5b18a97eb41f18ca971 --- /dev/null +++ b/services/audio_service/client/include/core_service_provider_stub.h @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef CORE_SERVICE_PROVIDER_STUB_H +#define CORE_SERVICE_PROVIDER_STUB_H + +#include "i_core_service_provider_ipc.h" + +namespace OHOS { +namespace AudioStandard { +class CoreServiceProviderStub : public IRemoteStub { +public: + virtual ~CoreServiceProviderStub() = default; + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +private: + static bool CheckInterfaceToken(MessageParcel &data); + int32_t HandleUpdateSessionOperation(MessageParcel &data, MessageParcel &reply); + int32_t HandleSetDefaultOutputDevice(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetAdapterNameBySessionId(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetProcessDeviceInfoBySessionId(MessageParcel &data, MessageParcel &reply); + int32_t HandleGenerateSessionId(MessageParcel &data, MessageParcel &reply); +}; + +class CoreServiceProviderWrapper : public CoreServiceProviderStub { +public: + ~CoreServiceProviderWrapper(); + CoreServiceProviderWrapper(ICoreServiceProvider *coreServiceWorker); + + int32_t UpdateSessionOperation(uint32_t sessionId, SessionOperation operation) override; + int32_t SetDefaultOutputDevice(const DeviceType defaultOutputDevice, + const uint32_t sessionID, const StreamUsage streamUsage, bool isRunning) override; + std::string GetAdapterNameBySessionId(uint32_t sessionId) override; + int32_t GetProcessDeviceInfoBySessionId(uint32_t sessionId, AudioDeviceDescriptor &deviceInfo) override; + uint32_t GenerateSessionId() override; + +private: + ICoreServiceProvider *coreServiceWorker_; +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // CORE_SERVICE_PROVIDER_STUB_H diff --git a/services/audio_service/client/include/pulseaudio_ipc_interface_code.h b/services/audio_service/client/include/pulseaudio_ipc_interface_code.h index 04ceccfaefdca9b134c898502eee2c73e0b2a072..2eda259b03b787678d5c92f4f5a52a576834f598 100644 --- a/services/audio_service/client/include/pulseaudio_ipc_interface_code.h +++ b/services/audio_service/client/include/pulseaudio_ipc_interface_code.h @@ -44,6 +44,7 @@ namespace AudioStandard { SET_OUTPUT_DEVICE_SINK, CREATE_PLAYBACK_CAPTURER_MANAGER, REGISET_POLICY_PROVIDER, + REGISET_CORE_SERVICE_PROVIDER, SET_WAKEUP_CLOSE_CALLBACK, SET_CAPTURE_SILENT_STATE, UPDATE_SPATIALIZATION_STATE, @@ -97,6 +98,11 @@ namespace AudioStandard { UNLOAD_HDI_ADAPTER, CHECK_CAPTURE_LIMIT, RELEASE_CAPTURE_LIMIT, + CREATE_HDI_SINK_PORT, + CREATE_SINK_PORT, + CREATE_HDI_SOURCE_PORT, + CREATE_SOURCE_PORT, + DESTROY_HDI_PORT, DEVICE_CONNECTED_FLAG, AUDIO_SERVER_CODE_MAX = DEVICE_CONNECTED_FLAG, }; diff --git a/services/audio_service/client/src/audio_manager_proxy.cpp b/services/audio_service/client/src/audio_manager_proxy.cpp index b7925552f9e6bdd390f3a9dfcff73519831f9430..9a1643eb82561f191a84afe46c6f64a83a4e5278 100644 --- a/services/audio_service/client/src/audio_manager_proxy.cpp +++ b/services/audio_service/client/src/audio_manager_proxy.cpp @@ -19,12 +19,14 @@ #include "audio_manager_proxy.h" #include +#include #include #include "audio_system_manager.h" #include "audio_service_log.h" #include "audio_utils.h" #include "i_audio_process.h" +#include "common/hdi_adapter_info.h" using namespace std; @@ -588,6 +590,24 @@ int32_t AudioManagerProxy::RegiestPolicyProvider(const sptr &obje return reply.ReadInt32(); } +int32_t AudioManagerProxy::RegistCoreServiceProvider(const sptr &object) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + + CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_NULL_OBJECT, "object is null"); + bool ret = data.WriteInterfaceToken(GetDescriptor()); + CHECK_AND_RETURN_RET_LOG(ret, -1, "WriteInterfaceToken failed"); + + (void)data.WriteRemoteObject(object); + int error = Remote()->SendRequest(static_cast(AudioServerInterfaceCode::REGISET_CORE_SERVICE_PROVIDER), + data, reply, option); + CHECK_AND_RETURN_RET_LOG(error == ERR_NONE, error, "Failed, error: %{public}d", error); + + return reply.ReadInt32(); +} + int32_t AudioManagerProxy::SetWakeupSourceCallback(const sptr& object) { MessageParcel data; @@ -1528,6 +1548,121 @@ void AudioManagerProxy::UnloadHdiAdapter(uint32_t devMgrType, const std::string CHECK_AND_RETURN_LOG(error == ERR_NONE, "UnloadHdiAdapter failed, error: %{public}d", error); } +uint32_t AudioManagerProxy::CreateHdiSinkPort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSinkAttr &attr) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + bool ret = data.WriteInterfaceToken(GetDescriptor()); + CHECK_AND_RETURN_RET_LOG(ret, HDI_INVALID_ID, "WriteInterfaceToken failed"); + data.WriteString(deviceClass); + data.WriteString(idInfo); + std::ostringstream oss; + oss.write(reinterpret_cast(&attr), sizeof(IAudioSinkAttr)); + data.WriteString(oss.str()); + data.WriteString(attr.adapterName == nullptr ? "nullptr" : std::string(attr.adapterName)); + data.WriteString(attr.filePath == nullptr ? "nullptr" : std::string(attr.filePath)); + data.WriteString(attr.deviceNetworkId == nullptr ? "nullptr" : std::string(attr.deviceNetworkId)); + data.WriteString(attr.address); + data.WriteString(attr.aux == nullptr ? "nullptr" : std::string(attr.aux)); + + int32_t error = Remote()->SendRequest( + static_cast(AudioServerInterfaceCode::CREATE_HDI_SINK_PORT), data, reply, option); + CHECK_AND_RETURN_RET_LOG(error == ERR_NONE, HDI_INVALID_ID, "CreateHdiSinkPort failed, error: %{public}d", error); + return reply.ReadUint32(); +} + +uint32_t AudioManagerProxy::CreateSinkPort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSinkAttr &attr) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + bool ret = data.WriteInterfaceToken(GetDescriptor()); + CHECK_AND_RETURN_RET_LOG(ret, HDI_INVALID_ID, "WriteInterfaceToken failed"); + data.WriteUint32(idBase); + data.WriteUint32(idType); + data.WriteString(idInfo); + std::ostringstream oss; + oss.write(reinterpret_cast(&attr), sizeof(IAudioSinkAttr)); + data.WriteString(oss.str()); + data.WriteString(attr.adapterName == nullptr ? "nullptr" : std::string(attr.adapterName)); + data.WriteString(attr.filePath == nullptr ? "nullptr" : std::string(attr.filePath)); + data.WriteString(attr.deviceNetworkId == nullptr ? "nullptr" : std::string(attr.deviceNetworkId)); + data.WriteString(attr.address); + data.WriteString(attr.aux == nullptr ? "nullptr" : std::string(attr.aux)); + + int32_t error = Remote()->SendRequest( + static_cast(AudioServerInterfaceCode::CREATE_SINK_PORT), data, reply, option); + CHECK_AND_RETURN_RET_LOG(error == ERR_NONE, HDI_INVALID_ID, "CreateSinkPort failed, error: %{public}d", error); + return reply.ReadUint32(); +} + +uint32_t AudioManagerProxy::CreateHdiSourcePort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSourceAttr &attr) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + bool ret = data.WriteInterfaceToken(GetDescriptor()); + CHECK_AND_RETURN_RET_LOG(ret, HDI_INVALID_ID, "WriteInterfaceToken failed"); + data.WriteString(deviceClass); + data.WriteString(idInfo); + std::ostringstream oss; + oss.write(reinterpret_cast(&attr), sizeof(IAudioSinkAttr)); + data.WriteString(oss.str()); + data.WriteString(attr.adapterName == nullptr ? "nullptr" : std::string(attr.adapterName)); + data.WriteString(attr.filePath == nullptr ? "nullptr" : std::string(attr.filePath)); + data.WriteString(attr.deviceNetworkId == nullptr ? "nullptr" : std::string(attr.deviceNetworkId)); + int32_t error = Remote()->SendRequest( + static_cast(AudioServerInterfaceCode::CREATE_HDI_SOURCE_PORT), data, reply, option); + CHECK_AND_RETURN_RET_LOG(error == ERR_NONE, HDI_INVALID_ID, "CreateHdiSourcePort failed, error: %{public}d", error); + return reply.ReadUint32(); +} + +uint32_t AudioManagerProxy::CreateSourcePort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSourceAttr &attr) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + bool ret = data.WriteInterfaceToken(GetDescriptor()); + CHECK_AND_RETURN_RET_LOG(ret, HDI_INVALID_ID, "WriteInterfaceToken failed"); + data.WriteUint32(idBase); + data.WriteUint32(idType); + data.WriteString(idInfo); + std::ostringstream oss; + oss.write(reinterpret_cast(&attr), sizeof(IAudioSinkAttr)); + data.WriteString(oss.str()); + data.WriteString(attr.adapterName == nullptr ? "nullptr" : std::string(attr.adapterName)); + data.WriteString(attr.filePath == nullptr ? "nullptr" : std::string(attr.filePath)); + data.WriteString(attr.deviceNetworkId == nullptr ? "nullptr" : std::string(attr.deviceNetworkId)); + int32_t error = Remote()->SendRequest( + static_cast(AudioServerInterfaceCode::CREATE_HDI_SOURCE_PORT), data, reply, option); + CHECK_AND_RETURN_RET_LOG(error == ERR_NONE, HDI_INVALID_ID, "CreateHdiSourcePort failed, error: %{public}d", error); + return reply.ReadUint32(); +} + +void AudioManagerProxy::DestroyHdiPort(uint32_t id) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + bool ret = data.WriteInterfaceToken(GetDescriptor()); + CHECK_AND_RETURN_LOG(ret, "WriteInterfaceToken failed"); + data.WriteUint32(id); + + int32_t error = Remote()->SendRequest( + static_cast(AudioServerInterfaceCode::DESTROY_HDI_PORT), data, reply, option); + CHECK_AND_RETURN_LOG(error == ERR_NONE, "DestroyHdiPort failed, error: %{public}d", error); +} + void AudioManagerProxy::SetDeviceConnectedFlag(bool flag) { MessageParcel data; diff --git a/services/audio_service/client/src/core_service_provider_stub.cpp b/services/audio_service/client/src/core_service_provider_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60f7d03d05bc32f7c329727a89ec1ddea7f90dbd --- /dev/null +++ b/services/audio_service/client/src/core_service_provider_stub.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef LOG_TAG +#define LOG_TAG "CoreServiceProviderStub" +#endif + +#include "core_service_provider_stub.h" +#include "audio_service_log.h" +#include "audio_errors.h" + +namespace OHOS { +namespace AudioStandard { +bool CoreServiceProviderStub::CheckInterfaceToken(MessageParcel &data) +{ + static auto localDescriptor = ICoreServiceProviderIpc::GetDescriptor(); + auto remoteDescriptor = data.ReadInterfaceToken(); + CHECK_AND_RETURN_RET_LOG(remoteDescriptor == localDescriptor, false, "CheckInterFfaceToken failed."); + return true; +} + +int CoreServiceProviderStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + bool ret = CheckInterfaceToken(data); + CHECK_AND_RETURN_RET(ret, AUDIO_ERR); + if (code >= ICoreServiceProviderMsg::CORE_SERVICE_PROVIDER_MAX_MSG) { + AUDIO_WARNING_LOG("Unsupported request code:%{public}d.", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + switch (code) { + case UPDATE_SESSION_OPERATION: + return HandleUpdateSessionOperation(data, reply); + case SET_DEFAULT_OUTPUT_DEVICE: + return HandleSetDefaultOutputDevice(data, reply); + case GET_ADAPTER_NAME_BY_SESSION_ID: + return HandleGetAdapterNameBySessionId(data, reply); + case GET_PROCESS_DEVICE_INFO_BY_SESSION_ID: + return HandleGetProcessDeviceInfoBySessionId(data, reply); + case GENERATE_SESSION_ID: + return HandleGenerateSessionId(data, reply); + default: + AUDIO_WARNING_LOG("Unsupported request code:%{public}d.", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } +} + +int32_t CoreServiceProviderStub::HandleUpdateSessionOperation(MessageParcel &data, MessageParcel &reply) +{ + uint32_t sessionId = data.ReadUint32(); + SessionOperation operation = static_cast(data.ReadUint32()); + int32_t ret = UpdateSessionOperation(sessionId, operation); + reply.WriteInt32(ret); + return AUDIO_OK; +} + +int32_t CoreServiceProviderStub::HandleSetDefaultOutputDevice(MessageParcel &data, MessageParcel &reply) +{ + int32_t deviceType = data.ReadInt32(); + uint32_t sessionID = data.ReadUint32(); + int32_t streamUsage = data.ReadInt32(); + bool isRunning = data.ReadBool(); + reply.WriteInt32(SetDefaultOutputDevice(static_cast(deviceType), + sessionID, static_cast(streamUsage), isRunning)); + return AUDIO_OK; +} + +int32_t CoreServiceProviderStub::HandleGetAdapterNameBySessionId(MessageParcel &data, MessageParcel &reply) +{ + uint32_t sessionID = data.ReadUint32(); + AUDIO_INFO_LOG("SessionId: %{public}u", sessionID); + reply.WriteString(GetAdapterNameBySessionId(sessionID)); + return AUDIO_OK; +} + +int32_t CoreServiceProviderStub::HandleGetProcessDeviceInfoBySessionId(MessageParcel &data, MessageParcel &reply) +{ + uint32_t sessionID = data.ReadUint32(); + AUDIO_INFO_LOG("SessionId: %{public}u", sessionID); + AudioDeviceDescriptor deviceInfo; + int32_t ret = GetProcessDeviceInfoBySessionId(sessionID, deviceInfo); + deviceInfo.Marshalling(reply); + return ret; +} + +int32_t CoreServiceProviderStub::HandleGenerateSessionId(MessageParcel &data, MessageParcel &reply) +{ + uint32_t ret = GenerateSessionId(); + reply.ReadUint32(ret); + return AUDIO_OK; +} + +CoreServiceProviderWrapper::~CoreServiceProviderWrapper() +{ + coreServiceWorker_ = nullptr; +} + +CoreServiceProviderWrapper::CoreServiceProviderWrapper(ICoreServiceProvider *coreServiceWorker) + : coreServiceWorker_(coreServiceWorker) +{ +} + +int32_t CoreServiceProviderWrapper::UpdateSessionOperation(uint32_t sessionId, SessionOperation operation) +{ + CHECK_AND_RETURN_RET_LOG(coreServiceWorker_ != nullptr, AUDIO_INIT_FAIL, "coreServiceWorker_ is null"); + return coreServiceWorker_->UpdateSessionOperation(sessionId, operation); +} + +int32_t CoreServiceProviderWrapper::SetDefaultOutputDevice(const DeviceType defaultOutputDevice, + const uint32_t sessionID, const StreamUsage streamUsage, bool isRunning) +{ + CHECK_AND_RETURN_RET_LOG(coreServiceWorker_ != nullptr, AUDIO_INIT_FAIL, "coreServiceWorker_ is null"); + return coreServiceWorker_->SetDefaultOutputDevice(defaultOutputDevice, sessionID, streamUsage, isRunning); +} + +std::string CoreServiceProviderWrapper::GetAdapterNameBySessionId(uint32_t sessionID) +{ + CHECK_AND_RETURN_RET_LOG(coreServiceWorker_ != nullptr, "", "coreServiceWorker_ is null"); + return coreServiceWorker_->GetAdapterNameBySessionId(sessionID); +} + +int32_t CoreServiceProviderWrapper::GetProcessDeviceInfoBySessionId( + uint32_t sessionId, AudioDeviceDescriptor &deviceInfo) +{ + CHECK_AND_RETURN_RET_LOG(coreServiceWorker_ != nullptr, AUDIO_INIT_FAIL, "coreServiceWorker_ is null"); + return coreServiceWorker_->GetProcessDeviceInfoBySessionId(sessionId, deviceInfo); +} + +uint32_t CoreServiceProviderWrapper::GenerateSessionId() +{ + CHECK_AND_RETURN_RET_LOG(coreServiceWorker_ != nullptr, 0, "coreServiceWorker_ is null"); + return coreServiceWorker_->GenerateSessionId(); +} +} // namespace AudioStandard +} // namespace OHOS diff --git a/services/audio_service/client/src/renderer_in_client_public.cpp b/services/audio_service/client/src/renderer_in_client_public.cpp index 36ffa2e0613296c930dbe0b36e1dcd8dd57d425a..eed1498c24ec2e44bfc941aa70b19798bc07cd0c 100644 --- a/services/audio_service/client/src/renderer_in_client_public.cpp +++ b/services/audio_service/client/src/renderer_in_client_public.cpp @@ -873,10 +873,7 @@ bool RendererInClientInner::StartAudioStream(StateChangeCmdType cmdType, } CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, false, "ipcStream is not inited!"); int32_t ret = ipcStream_->Start(); - if (ret != SUCCESS) { - AUDIO_ERR_LOG("Start call server failed:%{public}u", ret); - return false; - } + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Start call server failed:%{public}u", ret); std::unique_lock waitLock(callServerMutex_); bool stopWaiting = callServerCV_.wait_for(waitLock, std::chrono::milliseconds(OPERATION_TIMEOUT_IN_MS), [this] { return state_ == RUNNING; // will be false when got notified. diff --git a/services/audio_service/common/include/i_core_service_provider.h b/services/audio_service/common/include/i_core_service_provider.h new file mode 100644 index 0000000000000000000000000000000000000000..8140b7cdd687fba7c6c79948a2a06eec3b127ad9 --- /dev/null +++ b/services/audio_service/common/include/i_core_service_provider.h @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef I_CORE_SERVICE_PROVIDER_H +#define I_CORE_SERVICE_PROVIDER_H + +#include +#include "audio_service_enum.h" +#include "audio_device_info.h" +#include "audio_device_descriptor.h" + + +namespace OHOS { +namespace AudioStandard { +class ICoreServiceProvider { +public: + virtual int32_t UpdateSessionOperation(uint32_t sessionId, SessionOperation operation) = 0; + virtual int32_t SetDefaultOutputDevice(const DeviceType defaultOutputDevice, + const uint32_t sessionID, const StreamUsage streamUsage, bool isRunning) = 0; + virtual std::string GetAdapterNameBySessionId(uint32_t sessionID) = 0; + virtual int32_t GetProcessDeviceInfoBySessionId(uint32_t sessionID, AudioDeviceDescriptor &deviceInfo) = 0; + virtual uint32_t GenerateSessionId() = 0; + + virtual ~ICoreServiceProvider() = default; +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // I_CORE_SERVICE_PROVIDER_H diff --git a/services/audio_service/common/include/i_core_service_provider_ipc.h b/services/audio_service/common/include/i_core_service_provider_ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..640270ee39525f68e83e2f140ab009d75563b285 --- /dev/null +++ b/services/audio_service/common/include/i_core_service_provider_ipc.h @@ -0,0 +1,47 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef I_CORE_SERVICE_PROVIDER_IPC_H +#define I_CORE_SERVICE_PROVIDER_IPC_H + +#include "i_core_service_provider.h" + +#include "ipc_types.h" +#include "iremote_broker.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" + + +namespace OHOS { +namespace AudioStandard { +class ICoreServiceProviderIpc : public ICoreServiceProvider, public IRemoteBroker { +public: + virtual ~ICoreServiceProviderIpc() = default; + + // IPC code. + enum ICoreServiceProviderMsg : uint32_t { + UPDATE_SESSION_OPERATION = 0, + SET_DEFAULT_OUTPUT_DEVICE, + GET_ADAPTER_NAME_BY_SESSION_ID, + GET_PROCESS_DEVICE_INFO_BY_SESSION_ID, + GENERATE_SESSION_ID, + CORE_SERVICE_PROVIDER_MAX_MSG, + }; + + DECLARE_INTERFACE_DESCRIPTOR(u"ICoreServiceProviderIpc"); +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // I_CORE_SERVICE_PROVIDER_IPC_H diff --git a/services/audio_service/common/src/audio_process_config.cpp b/services/audio_service/common/src/audio_process_config.cpp index efb5688a8252667fd77184fd2db7cf8fe18fa368..d4720d62c6e29fc9b0ea79fdda984c1acff73968 100644 --- a/services/audio_service/common/src/audio_process_config.cpp +++ b/services/audio_service/common/src/audio_process_config.cpp @@ -329,7 +329,9 @@ std::string ProcessConfig::DumpProcessConfig(const AudioProcessConfig &config) config.capturerInfo.capturerFlags << ") "; } - temp << "streamType<" << config.streamType << ">"; + temp << "streamType<" << config.streamType << "> "; + + temp << "originalSessionId<" << config.originalSessionId << ">"; return temp.str(); } diff --git a/services/audio_service/libaudio_process_service.versionscript b/services/audio_service/libaudio_process_service.versionscript index bc156dba8579aedb0411e053e9eaa9ebcfa02506..2e43afa1ccd4add660c7804d94ec986870026b5d 100644 --- a/services/audio_service/libaudio_process_service.versionscript +++ b/services/audio_service/libaudio_process_service.versionscript @@ -55,6 +55,7 @@ *GenerateSessionId*; *LoadModernInnerCapSink*; *UnloadModernInnerCapSink*; + *ConfigCoreServiceProvider*; local: *; }; \ No newline at end of file diff --git a/services/audio_service/server/include/audio_server.h b/services/audio_service/server/include/audio_server.h index fd310a3d3dddb53513ce127d06208c6de4785e6c..51373db450253ca1c3eba9f21ea3a41550353d9c 100644 --- a/services/audio_service/server/include/audio_server.h +++ b/services/audio_service/server/include/audio_server.h @@ -128,6 +128,8 @@ public: int32_t RegiestPolicyProvider(const sptr &object) override; + int32_t RegistCoreServiceProvider(const sptr &object) override; + int32_t SetWakeupSourceCallback(const sptr& object) override; int32_t UpdateSpatializationState(AudioSpatializationState spatializationState) override; @@ -200,6 +202,15 @@ public: int32_t LoadHdiAdapter(uint32_t devMgrType, const std::string &adapterName) override; void UnloadHdiAdapter(uint32_t devMgrType, const std::string &adapterName, bool force) override; + uint32_t CreateHdiSinkPort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSinkAttr &attr) override; + uint32_t CreateSinkPort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSinkAttr &attr) override; + uint32_t CreateHdiSourcePort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSourceAttr &attr) override; + uint32_t CreateSourcePort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSourceAttr &attr) override; + void DestroyHdiPort(uint32_t id) override; void SetDeviceConnectedFlag(bool flag) override; protected: void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; diff --git a/services/audio_service/server/include/core_service_handler.h b/services/audio_service/server/include/core_service_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..01884d0129662cb7936875f570880f4a6adb00e0 --- /dev/null +++ b/services/audio_service/server/include/core_service_handler.h @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef CORE_SERVICE_HANDLER_H +#define CORE_SERVICE_HANDLER_H + +#include +#include +#include +#include + +#include "i_core_service_provider_ipc.h" + +namespace OHOS { +namespace AudioStandard { +class CoreServiceHandler { +public: + static CoreServiceHandler& GetInstance(); + + ~CoreServiceHandler(); + + // would be called only once + int32_t ConfigCoreServiceProvider(const sptr policyProvider); + + int32_t UpdateSessionOperation(uint32_t sessionId, SessionOperation operation); + int32_t SetDefaultOutputDevice( + const DeviceType defaultOutputDevice, const uint32_t sessionID, const StreamUsage streamUsage, bool isRunning); + std::string GetAdapterNameBySessionId(uint32_t sessionId); + int32_t GetProcessDeviceInfoBySessionId(uint32_t sessionId, AudioDeviceDescriptor &deviceInfo); + uint32_t GenerateSessionId(); +private: + CoreServiceHandler(); + sptr iCoreServiceProvider_ = nullptr; +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // CORE_SERVICE_HANDLER_H diff --git a/services/audio_service/server/include/core_service_provider_proxy.h b/services/audio_service/server/include/core_service_provider_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..30c3b3399d3b6ff7109f8ea9e8b8ebab6bf8c16e --- /dev/null +++ b/services/audio_service/server/include/core_service_provider_proxy.h @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef CORE_SERVICE_PROVIDER_PROXY_H +#define CORE_SERVICE_PROVIDER_PROXY_H + +#include "i_core_service_provider_ipc.h" + +namespace OHOS { +namespace AudioStandard { +class CoreServiceProviderProxy : public IRemoteProxy { +public: + explicit CoreServiceProviderProxy(const sptr& impl); + virtual ~CoreServiceProviderProxy(); + + int32_t UpdateSessionOperation(uint32_t sessionId, SessionOperation operation) override; + int32_t SetDefaultOutputDevice(const DeviceType defaultOutputDevice, + const uint32_t sessionID, const StreamUsage streamUsage, bool isRunning) override; + std::string GetAdapterNameBySessionId(uint32_t sessionId) override; + int32_t GetProcessDeviceInfoBySessionId(uint32_t sessionId, AudioDeviceDescriptor &deviceInfo) override; + uint32_t GenerateSessionId() override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AudioStandard +} // namespace OHOS +#endif // CORE_SERVICE_PROVIDER_PROXY_H diff --git a/services/audio_service/server/include/pa_adapter_manager.h b/services/audio_service/server/include/pa_adapter_manager.h index af83b17df3e2356b032383a419a45053a0a73058..01c335d18b92f68f71c751c9b00276e079d5b6d3 100644 --- a/services/audio_service/server/include/pa_adapter_manager.h +++ b/services/audio_service/server/include/pa_adapter_manager.h @@ -100,10 +100,11 @@ private: std::shared_ptr CreateRendererStream(AudioProcessConfig processConfig, pa_stream *paStream); std::shared_ptr CreateCapturerStream(AudioProcessConfig processConfig, pa_stream *paStream); int32_t ConnectStreamToPA(pa_stream *paStream, pa_sample_spec sampleSpec, - SourceType source, int32_t innerCapId, const std::string &deviceName = ""); + SourceType source, int32_t innerCapId, uint32_t sessionId, const std::string &deviceName = ""); void ReleasePaStream(pa_stream *paStream); - int32_t ConnectRendererStreamToPA(pa_stream *paStream, pa_sample_spec sampleSpec, int32_t innerCapId); - int32_t ConnectCapturerStreamToPA(pa_stream *paStream, pa_sample_spec sampleSpec, + int32_t ConnectRendererStreamToPA( + pa_stream *paStream, pa_sample_spec sampleSpec, uint32_t sessionId, int32_t innerCapId); + int32_t ConnectCapturerStreamToPA(pa_stream *paStream, pa_sample_spec sampleSpec, uint32_t sessionId, SourceType source, const std::string &deviceName); const std::string GetEnhanceSceneName(SourceType sourceType); diff --git a/services/audio_service/server/src/audio_endpoint.cpp b/services/audio_service/server/src/audio_endpoint.cpp index 261b3e29f64d9a78d194acbcf8203e03d5ecd220..079e5e5f3eae17190f21b1c056957447e33186cf 100644 --- a/services/audio_service/server/src/audio_endpoint.cpp +++ b/services/audio_service/server/src/audio_endpoint.cpp @@ -34,6 +34,7 @@ #include "audio_service_log.h" #include "audio_schedule.h" #include "audio_qosmanager.h" +#include "audio_utils.h" #include "manager/hdi_adapter_manager.h" #include "sink/i_audio_render_sink.h" #include "source/i_audio_capture_source.h" @@ -437,12 +438,16 @@ bool AudioEndpointInner::ConfigInputPoint(const AudioDeviceDescriptor &deviceInf return false; } - int32_t err = source->Init(attr); - if (err != SUCCESS || !source->IsInited()) { - AUDIO_ERR_LOG("init remote fast fail, err %{public}d.", err); - HdiAdapterManager::GetInstance().ReleaseId(fastCaptureId_); - return false; + if (!source->IsInited()) { + AUDIO_INFO_LOG("Source is not inited"); + int32_t err = source->Init(attr); + if (err != SUCCESS || !source->IsInited()) { + AUDIO_ERR_LOG("init remote fast fail, err %{public}d.", err); + HdiAdapterManager::GetInstance().ReleaseId(fastCaptureId_); + return false; + } } + if (PrepareDeviceBuffer(deviceInfo) != SUCCESS) { source->DeInit(); HdiAdapterManager::GetInstance().ReleaseId(fastCaptureId_); @@ -492,12 +497,15 @@ std::shared_ptr AudioEndpointInner::GetFastSource(const std attr.adapterName = "primary"; if (type == AudioEndpoint::TYPE_MMAP) { + AUDIO_INFO_LOG("Use mmap"); fastSourceType_ = FAST_SOURCE_TYPE_NORMAL; + return SwitchSource(fastCaptureId_, HDI_ID_TYPE_FAST, HDI_ID_INFO_DEFAULT); } else if (type == AudioEndpoint::TYPE_VOIP_MMAP) { + AUDIO_INFO_LOG("Use voip mmap"); fastSourceType_ = FAST_SOURCE_TYPE_VOIP; + SwitchSource(fastCaptureId_, HDI_ID_TYPE_FAST, HDI_ID_INFO_DEFAULT); // In plan: should use voip mmap } - // voip delete, maybe need fix - return SwitchSource(fastCaptureId_, HDI_ID_TYPE_FAST, HDI_ID_INFO_DEFAULT); + return nullptr; } void AudioEndpointInner::StartThread(const IAudioSinkAttr &attr) @@ -546,11 +554,15 @@ bool AudioEndpointInner::Config(const AudioDeviceDescriptor &deviceInfo) IAudioSinkAttr attr = {}; InitSinkAttr(attr, deviceInfo); - sink->Init(attr); if (!sink->IsInited()) { - HdiAdapterManager::GetInstance().ReleaseId(fastRenderId_); - return false; + AUDIO_INFO_LOG("Sink is not inited"); + sink->Init(attr); + if (!sink->IsInited()) { + HdiAdapterManager::GetInstance().ReleaseId(fastRenderId_); + return false; + } } + if (PrepareDeviceBuffer(deviceInfo) != SUCCESS) { sink->DeInit(); HdiAdapterManager::GetInstance().ReleaseId(fastRenderId_); @@ -568,10 +580,12 @@ bool AudioEndpointInner::Config(const AudioDeviceDescriptor &deviceInfo) static std::shared_ptr SwitchSink(uint32_t &id, HdiIdType type, const std::string &info) { + AUDIO_INFO_LOG("Id: %{public}u", id); if (id != HDI_INVALID_ID) { HdiAdapterManager::GetInstance().ReleaseId(id); } id = HdiAdapterManager::GetInstance().GetId(HDI_ID_BASE_RENDER, type, info, true); + AUDIO_INFO_LOG("Id after process: %{public}u", id); return HdiAdapterManager::GetInstance().GetRenderSink(id, true); } @@ -2233,7 +2247,7 @@ bool AudioEndpointInner::IsInvalidBuffer(uint8_t *buffer, size_t bufferSize, Aud } return isInvalid; } - + void AudioEndpointInner::WriteMuteDataSysEvent(uint8_t *buffer, size_t bufferSize, int32_t index) { auto tempProcess = processList_[index]; @@ -2262,7 +2276,7 @@ void AudioEndpointInner::WriteMuteDataSysEvent(uint8_t *buffer, size_t bufferSiz if (tempProcess->GetSilentState()) { AUDIO_WARNING_LOG("begin write valid data in server"); tempProcess->SetSilentState(false); - + std::unordered_map payload; payload["uid"] = std::to_string(tempProcess->GetAppInfo().appUid); payload["sessionId"] = std::to_string(tempProcess->GetAudioSessionId()); @@ -2273,7 +2287,7 @@ void AudioEndpointInner::WriteMuteDataSysEvent(uint8_t *buffer, size_t bufferSiz } } } - + void AudioEndpointInner::ReportDataToResSched(std::unordered_map payload, uint32_t type) { #ifdef RESSCHE_ENABLE diff --git a/services/audio_service/server/src/audio_manager_stub.cpp b/services/audio_service/server/src/audio_manager_stub.cpp index 393c5dfdcad57e440e2c0f3020af385cfa9127bd..c9d8d6242c17f7671beda8ba07dc94af69923110 100644 --- a/services/audio_service/server/src/audio_manager_stub.cpp +++ b/services/audio_service/server/src/audio_manager_stub.cpp @@ -17,6 +17,7 @@ #endif #include "audio_manager_base.h" +#include #include "audio_system_manager.h" #include "audio_service_log.h" #include "i_audio_process.h" @@ -64,6 +65,7 @@ const char *g_audioServerCodeStrs[] = { "SET_OUTPUT_DEVICE_SINK", "CREATE_PLAYBACK_CAPTURER_MANAGER", "REGISET_POLICY_PROVIDER", + "REGISET_CORE_SERVICE_PROVIDER", "SET_WAKEUP_CLOSE_CALLBACK", "SET_CAPTURE_SILENT_STATE", "UPDATE_SPATIALIZATION_STATE", @@ -117,10 +119,15 @@ const char *g_audioServerCodeStrs[] = { "UNLOAD_HDI_ADAPTER", "CHECK_CAPTURE_LIMIT", "RELEASE_CAPTURE_LIMIT", + "CREATE_HDI_SINK_PORT", + "CREATE_SINK_PORT", + "CREATE_HDI_SOURCE_PORT", + "CREATE_SOURCE_PORT", + "DESTROY_HDI_PORT", "DEVICE_CONNECTED_FLAG", }; -constexpr size_t codeNums = sizeof(g_audioServerCodeStrs) / sizeof(const char *); -static_assert(codeNums == (static_cast (AudioServerInterfaceCode::AUDIO_SERVER_CODE_MAX) + 1), +constexpr size_t CODE_NUMS = sizeof(g_audioServerCodeStrs) / sizeof(const char *); +static_assert(CODE_NUMS == (static_cast (AudioServerInterfaceCode::AUDIO_SERVER_CODE_MAX) + 1), "keep same with AudioServerInterfaceCode"); } static void LoadEffectLibrariesReadData(vector& libList, vector& effectList, MessageParcel &data, @@ -595,6 +602,15 @@ int AudioManagerStub::HandleRegiestPolicyProvider(MessageParcel &data, MessagePa return AUDIO_OK; } +int AudioManagerStub::HandleRegistCoreServiceProvider(MessageParcel &data, MessageParcel &reply) +{ + sptr object = data.ReadRemoteObject(); + CHECK_AND_RETURN_RET_LOG(object != nullptr, AUDIO_ERR, "obj is null"); + int32_t result = RegistCoreServiceProvider(object); + reply.WriteInt32(result); + return AUDIO_OK; +} + int AudioManagerStub::HandleSetWakeupSourceCallback(MessageParcel &data, MessageParcel &reply) { sptr object = data.ReadRemoteObject(); @@ -812,10 +828,29 @@ int AudioManagerStub::HandleFifthPartCode(uint32_t code, MessageParcel &data, Me case static_cast(AudioServerInterfaceCode::RELEASE_CAPTURE_LIMIT): return HandleReleaseCaptureLimit(data, reply); #endif + default: + return HandleSixthPartCode(code, data, reply, option); + } +} + +int AudioManagerStub::HandleSixthPartCode(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + switch (code) { case static_cast(AudioServerInterfaceCode::LOAD_HDI_ADAPTER): return HandleLoadHdiAdapter(data, reply); case static_cast(AudioServerInterfaceCode::UNLOAD_HDI_ADAPTER): return HandleUnloadHdiAdapter(data, reply); + case static_cast(AudioServerInterfaceCode::CREATE_HDI_SINK_PORT): + return HandleCreateHdiSinkPort(data, reply); + case static_cast(AudioServerInterfaceCode::CREATE_SINK_PORT): + return HandleCreateSinkPort(data, reply); + case static_cast(AudioServerInterfaceCode::CREATE_HDI_SOURCE_PORT): + return HandleCreateHdiSourcePort(data, reply); + case static_cast(AudioServerInterfaceCode::CREATE_SOURCE_PORT): + return HandleCreateSourcePort(data, reply); + case static_cast(AudioServerInterfaceCode::DESTROY_HDI_PORT): + return HandleDestroyHdiPort(data, reply); default: AUDIO_ERR_LOG("default case, need check AudioManagerStub"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); @@ -891,6 +926,8 @@ int AudioManagerStub::HandleSecondPartCode(uint32_t code, MessageParcel &data, M return HandleCreatePlaybackCapturerManager(data, reply); case static_cast(AudioServerInterfaceCode::REGISET_POLICY_PROVIDER): return HandleRegiestPolicyProvider(data, reply); + case static_cast(AudioServerInterfaceCode::REGISET_CORE_SERVICE_PROVIDER): + return HandleRegistCoreServiceProvider(data, reply); case static_cast(AudioServerInterfaceCode::SET_WAKEUP_CLOSE_CALLBACK): return HandleSetWakeupSourceCallback(data, reply); case static_cast(AudioServerInterfaceCode::UPDATE_SPATIALIZATION_STATE): @@ -910,7 +947,7 @@ int AudioManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Messag { CHECK_AND_RETURN_RET_LOG(data.ReadInterfaceToken() == GetDescriptor(), -1, "ReadInterfaceToken failed"); - Trace trace(code >= codeNums ? "invalid audio server code!" : g_audioServerCodeStrs[code]); + Trace trace(code >= CODE_NUMS ? "invalid audio server code!" : g_audioServerCodeStrs[code]); if (code <= static_cast(AudioServerInterfaceCode::AUDIO_SERVER_CODE_MAX)) { switch (code) { case static_cast(AudioServerInterfaceCode::GET_AUDIO_PARAMETER): @@ -1189,5 +1226,102 @@ int AudioManagerStub::HandleDeviceConnectedFlag(MessageParcel &data, MessageParc return AUDIO_OK; } +int AudioManagerStub::HandleCreateHdiSinkPort(MessageParcel &data, MessageParcel &reply) +{ + std::string deviceClass = data.ReadString(); + std::string idInfo = data.ReadString(); + IAudioSinkAttr attr; + + std::string attrStr = data.ReadString(); + if (attrStr.size() != sizeof(IAudioSinkAttr)) { + return AUDIO_ERR; + } + std::istringstream iss(attrStr); + iss.read(reinterpret_cast(&attr), sizeof(IAudioSinkAttr)); + attr.adapterName = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.filePath = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.deviceNetworkId = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.address = data.ReadString(); + attr.aux = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + + uint32_t id = CreateHdiSinkPort(deviceClass, idInfo, attr); + reply.WriteUint32(id); + return AUDIO_OK; +} + +int AudioManagerStub::HandleCreateSinkPort(MessageParcel &data, MessageParcel &reply) +{ + HdiIdBase idBase = static_cast(data.ReadUint32()); + HdiIdType idType = static_cast(data.ReadUint32()); + std::string idInfo = data.ReadString(); + IAudioSinkAttr attr; + + std::string attrStr = data.ReadString(); + if (attrStr.size() != sizeof(IAudioSinkAttr)) { + return AUDIO_ERR; + } + std::istringstream iss(attrStr); + iss.read(reinterpret_cast(&attr), sizeof(IAudioSinkAttr)); + attr.adapterName = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.filePath = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.deviceNetworkId = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.address = data.ReadString(); + attr.aux = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + + uint32_t id = CreateSinkPort(idBase, idType, idInfo, attr); + reply.WriteUint32(id); + return AUDIO_OK; +} + +int AudioManagerStub::HandleCreateHdiSourcePort(MessageParcel &data, MessageParcel &reply) +{ + std::string deviceClass = data.ReadString(); + std::string idInfo = data.ReadString(); + IAudioSourceAttr attr; + + std::string attrStr = data.ReadString(); + if (attrStr.size() != sizeof(IAudioSourceAttr)) { + return AUDIO_ERR; + } + std::istringstream iss(attrStr); + iss.read(reinterpret_cast(&attr), sizeof(IAudioSourceAttr)); + attr.adapterName = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.filePath = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.deviceNetworkId = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + + uint32_t id = CreateHdiSourcePort(deviceClass, idInfo, attr); + reply.WriteUint32(id); + return AUDIO_OK; +} + +int AudioManagerStub::HandleCreateSourcePort(MessageParcel &data, MessageParcel &reply) +{ + HdiIdBase idBase = static_cast(data.ReadUint32()); + HdiIdType idType = static_cast(data.ReadUint32()); + std::string idInfo = data.ReadString(); + IAudioSourceAttr attr; + + std::string attrStr = data.ReadString(); + if (attrStr.size() != sizeof(IAudioSourceAttr)) { + return AUDIO_ERR; + } + std::istringstream iss(attrStr); + iss.read(reinterpret_cast(&attr), sizeof(IAudioSourceAttr)); + attr.adapterName = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.filePath = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + attr.deviceNetworkId = data.ReadString() == "nullptr" ? nullptr : data.ReadString().c_str(); + + uint32_t id = CreateSourcePort(idBase, idType, idInfo, attr); + reply.WriteUint32(id); + return AUDIO_OK; +} + +int AudioManagerStub::HandleDestroyHdiPort(MessageParcel &data, MessageParcel &reply) +{ + uint32_t id = data.ReadUint32(); + DestroyHdiPort(id); + return AUDIO_OK; +} + } // namespace AudioStandard } // namespace OHOS diff --git a/services/audio_service/server/src/audio_process_in_server.cpp b/services/audio_service/server/src/audio_process_in_server.cpp index 88a529b7d9062374bcc9a0710ef2639c9c9a6d96..06467b45225ab25493b85ab0f6b149c1358fd89d 100644 --- a/services/audio_service/server/src/audio_process_in_server.cpp +++ b/services/audio_service/server/src/audio_process_in_server.cpp @@ -29,6 +29,7 @@ #include "media_monitor_manager.h" #include "audio_dump_pcm.h" #include "audio_performance_monitor.h" +#include "core_service_handler.h" #ifdef RESSCHE_ENABLE #include "res_type.h" #include "res_sched_client.h" @@ -219,6 +220,8 @@ int32_t AudioProcessInServer::StartInner() SwitchStreamUtil::UpdateSwitchStreamRecord(info, SWITCH_STATE_STARTED); } + int32_t ret = CoreServiceHandler::GetInstance().UpdateSessionOperation(sessionId_, SESSION_OPERATION_START); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Policy start client failed, reason: %{public}d", ret); for (size_t i = 0; i < listenerList_.size(); i++) { listenerList_[i]->OnStart(this); } @@ -372,7 +375,9 @@ int32_t AudioProcessInServer::Release(bool isSwitchStream) PermissionUtil::NotifyPrivacyStop(tokenId, sessionId_); SwitchStreamUtil::UpdateSwitchStreamRecord(info, SWITCH_STATE_FINISHED); } - int32_t ret = releaseCallback_->OnProcessRelease(this, isSwitchStream); + int32_t ret = CoreServiceHandler::GetInstance().UpdateSessionOperation(sessionId_, SESSION_OPERATION_RELEASE); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Policy remove client failed, reason: %{public}d", ret); + ret = releaseCallback_->OnProcessRelease(this, isSwitchStream); AUDIO_INFO_LOG("notify service release result: %{public}d", ret); return SUCCESS; } @@ -664,7 +669,7 @@ void AudioProcessInServer::WriteDumpFile(void *buffer, size_t bufferSize) int32_t AudioProcessInServer::SetDefaultOutputDevice(const DeviceType defaultOutputDevice) { - return PolicyHandler::GetInstance().SetDefaultOutputDevice(defaultOutputDevice, sessionId_, + return CoreServiceHandler::GetInstance().SetDefaultOutputDevice(defaultOutputDevice, sessionId_, processConfig_.rendererInfo.streamUsage, streamStatus_->load() == STREAM_RUNNING); } diff --git a/services/audio_service/server/src/audio_server.cpp b/services/audio_service/server/src/audio_server.cpp index 0a5f44e70495b4b0328fdaec7eee8907c2c6993b..71da8d993bed3d92381e24ee1af1ce611a66e628 100644 --- a/services/audio_service/server/src/audio_server.cpp +++ b/services/audio_service/server/src/audio_server.cpp @@ -35,6 +35,8 @@ #include "hisysevent.h" #include "parameters.h" +#include "core_service_handler.h" +#include "i_core_service_provider_ipc.h" #include "manager/hdi_adapter_manager.h" #include "sink/i_audio_render_sink.h" #include "source/i_audio_capture_source.h" @@ -869,6 +871,7 @@ int32_t AudioServer::OffloadSetVolume(float volume) int32_t AudioServer::SetAudioScene(AudioScene audioScene, std::vector &activeOutputDevices, DeviceType activeInputDevice, BluetoothOffloadState a2dpOffloadFlag) { + AUDIO_INFO_LOG("Scene: %{public}d, device: %{public}d", audioScene, activeInputDevice); std::lock_guard lock(audioSceneMutex_); DeviceType activeOutputDevice = activeOutputDevices.front(); @@ -1093,6 +1096,18 @@ int32_t AudioServer::RegiestPolicyProvider(const sptr &object) return SUCCESS; } +int32_t AudioServer::RegistCoreServiceProvider(const sptr &object) +{ + int32_t callingUid = IPCSkeleton::GetCallingUid(); + CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), ERR_NOT_SUPPORTED, "refused for %{public}d", callingUid); + sptr coreServiceProvider = iface_cast(object); + CHECK_AND_RETURN_RET_LOG(coreServiceProvider != nullptr, ERR_INVALID_PARAM, + "coreServiceProvider obj cast failed"); + int32_t ret = CoreServiceHandler::GetInstance().ConfigCoreServiceProvider(coreServiceProvider); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "ConfigCoreServiceProvider failed!"); + return SUCCESS; +} + int32_t AudioServer::GetHapBuildApiVersion(int32_t callerUid) { AudioXCollie audioXCollie("AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName", @@ -2127,7 +2142,7 @@ void AudioServer::RestoreSession(const uint32_t &sessionID, RestoreInfo restoreI } tryCount--; } - + if (restoreStatus != NEED_RESTORE) { AUDIO_WARNING_LOG("Restore session in server failed, restore status %{public}d", restoreStatus); } @@ -2289,6 +2304,100 @@ void AudioServer::UnloadHdiAdapter(uint32_t devMgrType, const std::string &adapt HdiAdapterManager::GetInstance().UnloadAdapter(static_cast(devMgrType), adapterName, force); } +uint32_t AudioServer::CreateHdiSinkPort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSinkAttr &attr) +{ + int32_t callingUid = IPCSkeleton::GetCallingUid(); + CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), 0, "refused for %{public}d", callingUid); + + uint32_t id = HdiAdapterManager::GetInstance().GetRenderIdByDeviceClass(deviceClass, idInfo, true); + CHECK_AND_RETURN_RET(id != HDI_INVALID_ID, HDI_INVALID_ID); + std::shared_ptr sink = HdiAdapterManager::GetInstance().GetRenderSink(id, true); + if (sink == nullptr) { + HdiAdapterManager::GetInstance().ReleaseId(id); + return HDI_INVALID_ID; + } + if (!sink->IsInited()) { + sink->Init(attr); + } + return id; +} + +uint32_t AudioServer::CreateSinkPort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSinkAttr &attr) +{ + int32_t callingUid = IPCSkeleton::GetCallingUid(); + CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), 0, "refused for %{public}d", callingUid); + + AUDIO_INFO_LOG("In, idBase: %{public}u, idType: %{public}u, info: %{public}s", idBase, idType, idInfo.c_str()); + uint32_t id = HdiAdapterManager::GetInstance().GetRenderIdByDeviceClass(idBase, idType, idInfo, true); + CHECK_AND_RETURN_RET(id != HDI_INVALID_ID, HDI_INVALID_ID); + if (idInfo.find("InnerCapturerSink") != string::npos) { + AUDIO_INFO_LOG("Inner-cap stream return"); + return id; + } + std::shared_ptr sink = HdiAdapterManager::GetInstance().GetRenderSink(id, true); + if (sink == nullptr) { + AUDIO_WARNING_LOG("Sink is nullptr"); + HdiAdapterManager::GetInstance().ReleaseId(id); + return HDI_INVALID_ID; + } + if (!sink->IsInited()) { + sink->Init(attr); + } + return id; +} + +uint32_t AudioServer::CreateSourcePort(HdiIdBase idBase, HdiIdType idType, const std::string &idInfo, + const IAudioSourceAttr &attr) +{ + int32_t callingUid = IPCSkeleton::GetCallingUid(); + CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), HDI_INVALID_ID, "refused for %{public}d", callingUid); + AUDIO_INFO_LOG("In, idBase: %{public}u, idType: %{public}u, info: %{public}s", idBase, idType, idInfo.c_str()); + uint32_t id = HdiAdapterManager::GetInstance().GetCaptureIdByDeviceClass(idBase, idType, + static_cast(attr.sourceType), idInfo, true); + CHECK_AND_RETURN_RET(id != HDI_INVALID_ID, HDI_INVALID_ID); + std::shared_ptr source = HdiAdapterManager::GetInstance().GetCaptureSource(id, true); + if (source == nullptr) { + AUDIO_WARNING_LOG("Source is nullptr"); + HdiAdapterManager::GetInstance().ReleaseId(id); + return HDI_INVALID_ID; + } + if (!source->IsInited()) { + source->Init(attr); + } + return id; +} + +uint32_t AudioServer::CreateHdiSourcePort(const std::string &deviceClass, const std::string &idInfo, + const IAudioSourceAttr &attr) +{ + int32_t callingUid = IPCSkeleton::GetCallingUid(); + CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifyIsAudio(), HDI_INVALID_ID, "refused for %{public}d", callingUid); + + uint32_t id = HdiAdapterManager::GetInstance().GetCaptureIdByDeviceClass(deviceClass, + static_cast(attr.sourceType), idInfo, true); + CHECK_AND_RETURN_RET(id != HDI_INVALID_ID, HDI_INVALID_ID); + std::shared_ptr source = HdiAdapterManager::GetInstance().GetCaptureSource(id, true); + if (source == nullptr) { + AUDIO_WARNING_LOG("Source is nullptr"); + HdiAdapterManager::GetInstance().ReleaseId(id); + return HDI_INVALID_ID; + } + if (!source->IsInited()) { + source->Init(attr); + } + return id; +} + +void AudioServer::DestroyHdiPort(uint32_t id) +{ + int32_t callingUid = IPCSkeleton::GetCallingUid(); + CHECK_AND_RETURN_LOG(PermissionUtil::VerifyIsAudio(), "refused for %{public}d", callingUid); + + HdiAdapterManager::GetInstance().ReleaseId(id); +} + void AudioServer::SetDeviceConnectedFlag(bool flag) { int32_t callingUid = IPCSkeleton::GetCallingUid(); diff --git a/services/audio_service/server/src/audio_server_dump.cpp b/services/audio_service/server/src/audio_server_dump.cpp index c923204e83d8d2eb83bc136a9e56c6e2fbe29a4d..1b2a4232ebb3ed15822c2fa4001db29d31589228 100644 --- a/services/audio_service/server/src/audio_server_dump.cpp +++ b/services/audio_service/server/src/audio_server_dump.cpp @@ -213,6 +213,7 @@ void AudioServerDump::HelpInfoDump(string &dumpString) AppendFormat(dumpString, " -cm\t\t\t|dump AudioCached memory info\n"); AppendFormat(dumpString, " -pm\t\t\t|dump AudioPerformMonitor info\n"); AppendFormat(dumpString, " -ha\t\t\t|dump HdiAdapter info\n"); + AppendFormat(dumpString, " -ap\t\t\t|dump AudioPipeManager info\n"); } void AudioServerDump::AudioDataDump(string &dumpString, std::queue& argQue) diff --git a/services/audio_service/server/src/audio_service.cpp b/services/audio_service/server/src/audio_service.cpp index 368b38fc6ac4200a6ea67b537477f1237439545e..73de09892443baf13558b3e6ebd02e9ca8b1cfa6 100644 --- a/services/audio_service/server/src/audio_service.cpp +++ b/services/audio_service/server/src/audio_service.cpp @@ -24,6 +24,7 @@ #include "audio_common_log.h" #include "audio_utils.h" #include "policy_handler.h" +#include "core_service_handler.h" #include "ipc_stream_in_server.h" #include "common/hdi_adapter_info.h" #include "manager/hdi_adapter_manager.h" @@ -156,6 +157,7 @@ sptr AudioService::GetIpcStream(const AudioProcessConfig &con Trace trace("AudioService::GetIpcStream"); #ifdef HAS_FEATURE_INNERCAPTURER if (!isRegisterCapturerFilterListened_) { + AUDIO_INFO_LOG("isRegisterCapturerFilterListened_ is false"); PlaybackCapturerManager::GetInstance()->RegisterCapturerFilterListener(this); isRegisterCapturerFilterListened_ = true; } @@ -870,15 +872,31 @@ AudioDeviceDescriptor AudioService::GetDeviceInfoForProcess(const AudioProcessCo { // send the config to AudioPolicyServera and get the device info. AudioDeviceDescriptor deviceInfo(AudioDeviceDescriptor::DEVICE_INFO); - bool ret = PolicyHandler::GetInstance().GetProcessDeviceInfo(config, false, deviceInfo); - if (ret) { + int32_t ret = + CoreServiceHandler::GetInstance().GetProcessDeviceInfoBySessionId(config.originalSessionId, deviceInfo); + if (ret == SUCCESS) { AUDIO_INFO_LOG("Get DeviceInfo from policy server success, deviceType: %{public}d, " "supportLowLatency: %{public}d", deviceInfo.deviceType_, deviceInfo.isLowLatencyDevice_); + if (config.rendererInfo.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION || + config.rendererInfo.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION || + config.capturerInfo.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) { + if (config.streamInfo.samplingRate <= SAMPLE_RATE_16000) { + AUDIO_INFO_LOG("VoIP 16K"); + deviceInfo.audioStreamInfo_ = {SAMPLE_RATE_16000, ENCODING_PCM, SAMPLE_S16LE, STEREO}; + } else { + AUDIO_INFO_LOG("VoIP 48K"); + deviceInfo.audioStreamInfo_ = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO}; + } + } else { + AUDIO_INFO_LOG("Fast stream"); + AudioStreamInfo targetStreamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO}; + deviceInfo.audioStreamInfo_ = targetStreamInfo; + deviceInfo.deviceName_ = "mmap_device"; + } return deviceInfo; - } else { - AUDIO_WARNING_LOG("GetProcessDeviceInfo from audio policy server failed!"); } + AUDIO_WARNING_LOG("GetProcessDeviceInfo from audio policy server failed!"); if (config.audioMode == AUDIO_MODE_RECORD) { deviceInfo.deviceId_ = 1; deviceInfo.networkId_ = LOCAL_NETWORK_ID; diff --git a/services/audio_service/server/src/capturer_in_server.cpp b/services/audio_service/server/src/capturer_in_server.cpp index aef864bd55aadf755267395a1d369cff6c9f12d4..911df7d06f0a4a8bb45f5eee1f1ae698a1a6440b 100644 --- a/services/audio_service/server/src/capturer_in_server.cpp +++ b/services/audio_service/server/src/capturer_in_server.cpp @@ -32,6 +32,7 @@ #include "media_monitor_manager.h" #include "audio_dump_pcm.h" #include "volume_tools.h" +#include "core_service_handler.h" namespace OHOS { namespace AudioStandard { @@ -367,10 +368,14 @@ int32_t CapturerInServer::StartInner() SwitchStreamUtil::UpdateSwitchStreamRecord(info, SWITCH_STATE_STARTED); } + if (processConfig_.capturerInfo.sourceType != SOURCE_TYPE_PLAYBACK_CAPTURE) { + CoreServiceHandler::GetInstance().UpdateSessionOperation(streamIndex_, SESSION_OPERATION_START); + } + AudioService::GetInstance()->UpdateSourceType(processConfig_.capturerInfo.sourceType); status_ = I_STATUS_STARTING; - int ret = stream_->Start(); + int32_t ret = stream_->Start(); CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Start stream failed, reason: %{public}d", ret); resetTime_ = true; return SUCCESS; @@ -472,14 +477,19 @@ int32_t CapturerInServer::Stop() int32_t CapturerInServer::Release() { AudioService::GetInstance()->RemoveCapturer(streamIndex_); - { - std::unique_lock lock(statusLock_); - if (status_ == I_STATUS_RELEASED) { - AUDIO_INFO_LOG("Already released"); - return SUCCESS; - } + std::unique_lock lock(statusLock_); + if (status_ == I_STATUS_RELEASED) { + AUDIO_INFO_LOG("Already released"); + return SUCCESS; } + lock.unlock(); AUDIO_INFO_LOG("Start release capturer"); + + if (processConfig_.capturerInfo.sourceType != SOURCE_TYPE_PLAYBACK_CAPTURE) { + int32_t result = + CoreServiceHandler::GetInstance().UpdateSessionOperation(streamIndex_, SESSION_OPERATION_RELEASE); + CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Policy remove client failed, reason: %{public}d", result); + } int32_t ret = IStreamManager::GetRecorderManager().ReleaseCapturer(streamIndex_); if (ret < 0) { AUDIO_ERR_LOG("Release stream failed, reason: %{public}d", ret); @@ -489,7 +499,7 @@ int32_t CapturerInServer::Release() status_ = I_STATUS_RELEASED; #ifdef HAS_FEATURE_INNERCAPTURER if (processConfig_.capturerInfo.sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE) { - AUDIO_INFO_LOG("Disable inner capturer for %{public}u, innerCapId :%{public}d, innerCapMode:%{public}d", + AUDIO_INFO_LOG("Disable inner capturer for %{public}u, innerCapId :%{public}d, innerCapMode:%{public}d", streamIndex_, innerCapId_, processConfig_.innerCapMode); if (processConfig_.innerCapMode == MODERN_INNER_CAP) { PlaybackCapturerManager::GetInstance()->RemovePlaybackCapturerFilterInfo(streamIndex_, innerCapId_); diff --git a/services/audio_service/server/src/core_service_handler.cpp b/services/audio_service/server/src/core_service_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bacabe65fd7521d41a37e8811f85633a897485fd --- /dev/null +++ b/services/audio_service/server/src/core_service_handler.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef LOG_TAG +#define LOG_TAG "CoreServiceHandler" +#endif + +#include "core_service_handler.h" + +#include "audio_errors.h" +#include "audio_common_log.h" + +namespace OHOS { +namespace AudioStandard { +namespace { + +} + +CoreServiceHandler& CoreServiceHandler::GetInstance() +{ + static CoreServiceHandler CoreServiceHandler; + return CoreServiceHandler; +} + +CoreServiceHandler::CoreServiceHandler() +{ + AUDIO_INFO_LOG("Ctor"); +} + +CoreServiceHandler::~CoreServiceHandler() +{ + iCoreServiceProvider_ = nullptr; + AUDIO_INFO_LOG("Dtor"); +} + +int32_t CoreServiceHandler::ConfigCoreServiceProvider(const sptr coreServiceProvider) +{ + CHECK_AND_RETURN_RET_LOG(coreServiceProvider != nullptr, ERR_INVALID_PARAM, "Failed with null provider."); + if (iCoreServiceProvider_ == nullptr) { + iCoreServiceProvider_ = coreServiceProvider; + return SUCCESS; + } + AUDIO_ERR_LOG("Provider is already configed!"); + return ERR_INVALID_OPERATION; +} + +int32_t CoreServiceHandler::UpdateSessionOperation(uint32_t sessionId, SessionOperation operation) +{ + CHECK_AND_RETURN_RET_LOG(iCoreServiceProvider_ != nullptr, ERROR, "iCoreServiceProvider_ is nullptr"); + return iCoreServiceProvider_->UpdateSessionOperation(sessionId, operation); +} + +int32_t CoreServiceHandler::SetDefaultOutputDevice(const DeviceType defaultOutputDevice, const uint32_t sessionID, + const StreamUsage streamUsage, bool isRunning) +{ + CHECK_AND_RETURN_RET_LOG(iCoreServiceProvider_ != nullptr, ERROR, "iCoreServiceProvider_ is nullptr"); + return iCoreServiceProvider_->SetDefaultOutputDevice(defaultOutputDevice, sessionID, streamUsage, isRunning); +} + +std::string CoreServiceHandler::GetAdapterNameBySessionId(uint32_t sessionId) +{ + CHECK_AND_RETURN_RET_LOG(iCoreServiceProvider_ != nullptr, "", "iCoreServiceProvider_ is nullptr"); + return iCoreServiceProvider_->GetAdapterNameBySessionId(sessionId); +} + +int32_t CoreServiceHandler::GetProcessDeviceInfoBySessionId(uint32_t sessionId, AudioDeviceDescriptor &deviceInfo) +{ + CHECK_AND_RETURN_RET_LOG(iCoreServiceProvider_ != nullptr, ERROR, "iCoreServiceProvider_ is nullptr"); + return iCoreServiceProvider_->GetProcessDeviceInfoBySessionId(sessionId, deviceInfo); +} + +uint32_t CoreServiceHandler::GenerateSessionId() +{ + CHECK_AND_RETURN_RET_LOG(iCoreServiceProvider_ != nullptr, ERROR, "iCoreServiceProvider_ is nullptr"); + return iCoreServiceProvider_->GenerateSessionId(); +} +} // namespace AudioStandard +} // namespace OHOS diff --git a/services/audio_service/server/src/core_service_provider_proxy.cpp b/services/audio_service/server/src/core_service_provider_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d0ccb677db68c4b9aa9281aa49bef6b513ceb02 --- /dev/null +++ b/services/audio_service/server/src/core_service_provider_proxy.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef LOG_TAG +#define LOG_TAG "CoreServiceProviderProxy" +#endif + +#include "core_service_provider_proxy.h" +#include "audio_service_log.h" +#include "audio_errors.h" + +namespace OHOS { +namespace AudioStandard { +CoreServiceProviderProxy::CoreServiceProviderProxy(const sptr &impl) + : IRemoteProxy(impl) +{ +} + +CoreServiceProviderProxy::~CoreServiceProviderProxy() +{ +} + +int32_t CoreServiceProviderProxy::UpdateSessionOperation(uint32_t sessionId, SessionOperation operation) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + CHECK_AND_RETURN_RET_LOG(data.WriteInterfaceToken(GetDescriptor()), ERROR, "Write descriptor failed!"); + data.WriteUint32(sessionId); + data.WriteUint32(operation); + + int ret = Remote()->SendRequest(ICoreServiceProviderMsg::UPDATE_SESSION_OPERATION, data, reply, option); + CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ERR_OPERATION_FAILED, "failed, error: %{public}d", ret); + + return reply.ReadInt32(); +} + +int32_t CoreServiceProviderProxy::SetDefaultOutputDevice(const DeviceType defaultOutputDevice, const uint32_t sessionID, + const StreamUsage streamUsage, bool isRunning) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + CHECK_AND_RETURN_RET_LOG(data.WriteInterfaceToken(GetDescriptor()), ERROR, "Write descriptor failed!"); + data.WriteInt32(defaultOutputDevice); + data.WriteUint32(sessionID); + data.WriteInt32(streamUsage); + data.WriteBool(isRunning); + int ret = Remote()->SendRequest(ICoreServiceProviderMsg::SET_DEFAULT_OUTPUT_DEVICE, data, reply, option); + CHECK_AND_RETURN_RET(ret == AUDIO_OK, ret, "set default output device failed, ipc error: %{public}d", ret); + return reply.ReadInt32(); +} + +std::string CoreServiceProviderProxy::GetAdapterNameBySessionId(uint32_t sessionId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + CHECK_AND_RETURN_RET_LOG(data.WriteInterfaceToken(GetDescriptor()), "", "Write descriptor failed!"); + data.WriteUint32(sessionId); + int ret = Remote()->SendRequest(ICoreServiceProviderMsg::GET_ADAPTER_NAME_BY_SESSION_ID, data, reply, option); + CHECK_AND_RETURN_RET(ret == AUDIO_OK, "", "set default output device failed, ipc error: %{public}d", ret); + return reply.ReadString(); +} + +int32_t CoreServiceProviderProxy::GetProcessDeviceInfoBySessionId(uint32_t sessionId, AudioDeviceDescriptor &deviceInfo) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + CHECK_AND_RETURN_RET_LOG(data.WriteInterfaceToken(GetDescriptor()), ERROR, "Write descriptor failed!"); + data.WriteUint32(sessionId); + int ret = Remote()->SendRequest( + ICoreServiceProviderMsg::GET_PROCESS_DEVICE_INFO_BY_SESSION_ID, data, reply, option); + CHECK_AND_RETURN_RET(ret == AUDIO_OK, ret, "set default output device failed, ipc error: %{public}d", ret); + deviceInfo.Unmarshalling(reply); + return SUCCESS; +} + +uint32_t CoreServiceProviderProxy::GenerateSessionId() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + CHECK_AND_RETURN_RET_LOG(data.WriteInterfaceToken(GetDescriptor()), ERROR, "Write descriptor failed!"); + int ret = Remote()->SendRequest(ICoreServiceProviderMsg::GENERATE_SESSION_ID, data, reply, option); + CHECK_AND_RETURN_RET(ret == AUDIO_OK, 0, "set default output device failed, ipc error: %{public}d", ret); + return reply.ReadUint32(); +} +} // namespace AudioStandard +} // namespace OHOS diff --git a/services/audio_service/server/src/pa_adapter_manager.cpp b/services/audio_service/server/src/pa_adapter_manager.cpp index 1d093b2d8b3f800eba8ce3652e9bd11be65d43e5..a91b4de3cebaa4c0ffd98e0403b50f18f1f273ed 100644 --- a/services/audio_service/server/src/pa_adapter_manager.cpp +++ b/services/audio_service/server/src/pa_adapter_manager.cpp @@ -27,6 +27,7 @@ #include "pa_capturer_stream_impl.h" #include "audio_utils.h" #include "policy_handler.h" +#include "core_service_handler.h" namespace OHOS { namespace AudioStandard { @@ -98,7 +99,7 @@ int32_t PaAdapterManager::CreateRender(AudioProcessConfig processConfig, std::sh uint32_t sessionId = 0; if (managerType_ == DUP_PLAYBACK || managerType_ == DUAL_PLAYBACK || processConfig.originalSessionId < MIN_STREAMID || processConfig.originalSessionId > MAX_STREAMID) { - sessionId = PolicyHandler::GetInstance().GenerateSessionId(processConfig.appInfo.appUid); + sessionId = CoreServiceHandler::GetInstance().GenerateSessionId(); } else { sessionId = processConfig.originalSessionId; } @@ -411,7 +412,7 @@ int32_t PaAdapterManager::GetDeviceNameForConnect(AudioProcessConfig processConf pa_stream *PaAdapterManager::InitPaStream(AudioProcessConfig processConfig, uint32_t sessionId, bool isRecording) { - AUDIO_DEBUG_LOG("Enter InitPaStream"); + AUDIO_INFO_LOG("In, isInnerCapturer: %{public}d", processConfig.isInnerCapturer); std::lock_guard lock(paElementsMutex_); PaLockGuard palock(mainLoop_); if (CheckReturnIfinvalid(mainLoop_ && context_, ERR_ILLEGAL_STATE) < 0) { @@ -456,7 +457,7 @@ pa_stream *PaAdapterManager::InitPaStream(AudioProcessConfig processConfig, uint } int32_t ret = ConnectStreamToPA(paStream, sampleSpec, processConfig.capturerInfo.sourceType, - processConfig.innerCapId, deviceName); + processConfig.innerCapId, sessionId, deviceName); if (ret < 0) { AUDIO_ERR_LOG("ConnectStreamToPA Failed"); ReleasePaStream(paStream); @@ -631,9 +632,9 @@ std::shared_ptr PaAdapterManager::CreateCapturerStream(AudioPro } int32_t PaAdapterManager::ConnectStreamToPA(pa_stream *paStream, pa_sample_spec sampleSpec, - SourceType source, int32_t innerCapId, const std::string &deviceName) + SourceType source, int32_t innerCapId, uint32_t sessionId, const std::string &deviceName) { - AUDIO_DEBUG_LOG("Enter PaAdapterManager::ConnectStreamToPA"); + AUDIO_INFO_LOG("In"); if (CheckReturnIfinvalid(mainLoop_ && context_ && paStream, ERROR) < 0) { return ERR_ILLEGAL_STATE; } @@ -641,12 +642,12 @@ int32_t PaAdapterManager::ConnectStreamToPA(pa_stream *paStream, pa_sample_spec PaLockGuard lock(mainLoop_); int32_t XcollieFlag = AUDIO_XCOLLIE_FLAG_LOG; if (managerType_ == PLAYBACK || managerType_ == DUP_PLAYBACK || managerType_ == DUAL_PLAYBACK) { - int32_t rendererRet = ConnectRendererStreamToPA(paStream, sampleSpec, innerCapId); + int32_t rendererRet = ConnectRendererStreamToPA(paStream, sampleSpec, sessionId, innerCapId); CHECK_AND_RETURN_RET_LOG(rendererRet == SUCCESS, rendererRet, "ConnectRendererStreamToPA failed"); } if (managerType_ == RECORDER) { XcollieFlag = AUDIO_XCOLLIE_FLAG_LOG | AUDIO_XCOLLIE_FLAG_RECOVERY; - int32_t capturerRet = ConnectCapturerStreamToPA(paStream, sampleSpec, source, deviceName); + int32_t capturerRet = ConnectCapturerStreamToPA(paStream, sampleSpec, sessionId, source, deviceName); CHECK_AND_RETURN_RET_LOG(capturerRet == SUCCESS, capturerRet, "ConnectCapturerStreamToPA failed"); } while (waitConnect_) { @@ -670,7 +671,8 @@ int32_t PaAdapterManager::ConnectStreamToPA(pa_stream *paStream, pa_sample_spec return SUCCESS; } -int32_t PaAdapterManager::ConnectRendererStreamToPA(pa_stream *paStream, pa_sample_spec sampleSpec, int32_t innerCapId) +int32_t PaAdapterManager::ConnectRendererStreamToPA( + pa_stream *paStream, pa_sample_spec sampleSpec, uint32_t sessionId, int32_t innerCapId) { uint32_t tlength = 4; // 4 is tlength of playback uint32_t maxlength = 4; // 4 is max buffer length of playback @@ -680,8 +682,8 @@ int32_t PaAdapterManager::ConnectRendererStreamToPA(pa_stream *paStream, pa_samp maxlength = 20; // 20 for cover offload prebuf = 2; // 2 is double of normal, use more prebuf for dup stream } - AUDIO_INFO_LOG("Create ipc playback stream tlength: %{public}u, maxlength: %{public}u prebuf: %{public}u", tlength, - maxlength, prebuf); + AUDIO_INFO_LOG("Create ipc playback stream tlength: %{public}u, maxlength: %{public}u prebuf: %{public}u" + "sessionId: %{public}u, innerCapId: %{public}d", tlength, maxlength, prebuf, sessionId, innerCapId); pa_buffer_attr bufferAttr; bufferAttr.fragsize = static_cast(-1); bufferAttr.prebuf = pa_usec_to_bytes(BUF_LENGTH_IN_MSEC * PA_USEC_PER_MSEC * prebuf, &sampleSpec); @@ -690,8 +692,22 @@ int32_t PaAdapterManager::ConnectRendererStreamToPA(pa_stream *paStream, pa_samp bufferAttr.minreq = pa_usec_to_bytes(BUF_LENGTH_IN_MSEC * PA_USEC_PER_MSEC, &sampleSpec); std::string dupSinkName = AppendDeviceName(innerCapId, AppendType::APPEND_RENDER); - const char *sinkName = managerType_ == DUP_PLAYBACK ? dupSinkName.c_str() : - (managerType_ == DUAL_PLAYBACK ? "Speaker" : nullptr); + const char *sinkName = nullptr; + std::string sinkNameStr = ""; + if (managerType_ == DUP_PLAYBACK) { + sinkName = dupSinkName.c_str(); + } else if (managerType_ == DUAL_PLAYBACK) { + sinkName = "Speaker"; + } else { + sinkNameStr = CoreServiceHandler::GetInstance().GetAdapterNameBySessionId(sessionId); + sinkName = strdup(sinkNameStr.c_str()); + } + if (strcmp(sinkName, "") == 0) { + AUDIO_INFO_LOG("Sink name is null"); + sinkName = "Speaker"; + } + AUDIO_INFO_LOG("Sink name: %{public}s", sinkName); + uint32_t flags = PA_STREAM_ADJUST_LATENCY | PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_START_CORKED | PA_STREAM_VARIABLE_RATE; if (managerType_ == DUP_PLAYBACK || managerType_ == DUAL_PLAYBACK) { @@ -708,7 +724,7 @@ int32_t PaAdapterManager::ConnectRendererStreamToPA(pa_stream *paStream, pa_samp return SUCCESS; } -int32_t PaAdapterManager::ConnectCapturerStreamToPA(pa_stream *paStream, pa_sample_spec sampleSpec, +int32_t PaAdapterManager::ConnectCapturerStreamToPA(pa_stream *paStream, pa_sample_spec sampleSpec, uint32_t sessionId, SourceType source, const std::string &deviceName) { uint32_t fragsize = 1; // 1 is frag size of recorder @@ -719,7 +735,15 @@ int32_t PaAdapterManager::ConnectCapturerStreamToPA(pa_stream *paStream, pa_samp AUDIO_INFO_LOG("bufferAttr, maxLength: %{public}d, fragsize: %{public}d", bufferAttr.maxlength, bufferAttr.fragsize); - const char *cDeviceName = (deviceName == "") ? nullptr : deviceName.c_str(); + const char *cDeviceName = "Built_in_mic"; + std::string sourceNameStr = ""; + if (source == SOURCE_TYPE_PLAYBACK_CAPTURE || source == SOURCE_TYPE_REMOTE_CAST) { + cDeviceName = deviceName.c_str(); + } else { + sourceNameStr = CoreServiceHandler::GetInstance().GetAdapterNameBySessionId(sessionId); + cDeviceName = strdup(sourceNameStr.c_str()); + } + AUDIO_INFO_LOG("Source name: %{public}s", cDeviceName); uint32_t flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_START_CORKED | PA_STREAM_VARIABLE_RATE; if (source == SOURCE_TYPE_PLAYBACK_CAPTURE) { diff --git a/services/audio_service/server/src/renderer_in_server.cpp b/services/audio_service/server/src/renderer_in_server.cpp index 82295cbd6371939d4a8b5b728d7eeb8cdf67977b..70b135f0f3df4dabfd5ccb2bda04657b1e8b8588 100644 --- a/services/audio_service/server/src/renderer_in_server.cpp +++ b/services/audio_service/server/src/renderer_in_server.cpp @@ -37,6 +37,8 @@ #include "audio_dump_pcm.h" #include "audio_performance_monitor.h" #include "audio_volume_c.h" +#include "core_service_handler.h" +#include "audio_service_enum.h" namespace OHOS { namespace AudioStandard { @@ -158,6 +160,8 @@ int32_t RendererInServer::Init() AUDIO_WARNING_LOG("One VoIP direct stream has been created! Use normal mode."); } } + streamIndex_ = processConfig_.originalSessionId; + AUDIO_INFO_LOG("Stream index: %{public}u", streamIndex_); int32_t ret = IStreamManager::GetPlaybackManager(managerType_).CreateRender(processConfig_, stream_); if (ret != SUCCESS && (managerType_ == DIRECT_PLAYBACK || managerType_ == VOIP_PLAYBACK)) { @@ -168,7 +172,6 @@ int32_t RendererInServer::Init() } CHECK_AND_RETURN_RET_LOG(ret == SUCCESS && stream_ != nullptr, ERR_OPERATION_FAILED, "Construct rendererInServer failed: %{public}d", ret); - streamIndex_ = stream_->GetStreamIndex(); bool isSystemApp = CheckoutSystemAppUtil::CheckoutSystemApp(processConfig_.appInfo.appUid); AudioVolume::GetInstance()->AddStreamVolume(streamIndex_, processConfig_.streamType, processConfig_.rendererInfo.streamUsage, processConfig_.appInfo.appUid, processConfig_.appInfo.appPid, @@ -745,14 +748,16 @@ int32_t RendererInServer::Start() int32_t RendererInServer::StartInner() { AUDIO_INFO_LOG("sessionId: %{public}u", streamIndex_); + int32_t ret = 0; if (standByEnable_) { AUDIO_INFO_LOG("sessionId: %{public}u call to exit stand by!", streamIndex_); - CHECK_AND_RETURN_RET_LOG(audioServerBuffer_->GetStreamStatus() != nullptr, - ERR_OPERATION_FAILED, "stream status is nullptr"); + CHECK_AND_RETURN_RET_LOG(audioServerBuffer_->GetStreamStatus() != nullptr, ERR_OPERATION_FAILED, "null stream"); standByCounter_ = 0; startedTime_ = ClockTime::GetCurNano(); audioServerBuffer_->GetStreamStatus()->store(STREAM_STARTING); - int32_t ret = (managerType_ == DIRECT_PLAYBACK || managerType_ == VOIP_PLAYBACK) ? + ret = CoreServiceHandler::GetInstance().UpdateSessionOperation(streamIndex_, SESSION_OPERATION_START); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Policy start client failed, reason: %{public}d", ret); + ret = (managerType_ == DIRECT_PLAYBACK || managerType_ == VOIP_PLAYBACK) ? IStreamManager::GetPlaybackManager(managerType_).StartRender(streamIndex_) : stream_->Start(); return ret; } @@ -763,12 +768,13 @@ int32_t RendererInServer::StartInner() return ERR_ILLEGAL_STATE; } status_ = I_STATUS_STARTING; - { - std::lock_guard lock(fadeoutLock_); - AUDIO_INFO_LOG("fadeoutFlag_ = NO_FADING"); - fadeoutFlag_ = NO_FADING; - } - int32_t ret = (managerType_ == DIRECT_PLAYBACK || managerType_ == VOIP_PLAYBACK) ? + std::unique_lock fadeLock(fadeoutLock_); + AUDIO_INFO_LOG("fadeoutFlag_ = NO_FADING"); + fadeoutFlag_ = NO_FADING; + fadeLock.unlock(); + ret = CoreServiceHandler::GetInstance().UpdateSessionOperation(streamIndex_, SESSION_OPERATION_START); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Policy start client failed, reason: %{public}d", ret); + ret = (managerType_ == DIRECT_PLAYBACK || managerType_ == VOIP_PLAYBACK) ? IStreamManager::GetPlaybackManager(managerType_).StartRender(streamIndex_) : stream_->Start(); CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Start stream failed, reason: %{public}d", ret); @@ -779,14 +785,13 @@ int32_t RendererInServer::StartInner() AUDIO_INFO_LOG("Server update position %{public}" PRIu64" time%{public} " PRId64".", currentReadFrame, tempTime); resetTime_ = true; - { - std::lock_guard lock(dupMutex_); - for (auto &capInfo : captureInfos_) { - if (capInfo.second.isInnerCapEnabled && capInfo.second.dupStream != nullptr) { - capInfo.second.dupStream->Start(); - } + std::unique_lock dupLock(dupMutex_); + for (auto &capInfo : captureInfos_) { + if (capInfo.second.isInnerCapEnabled && capInfo.second.dupStream != nullptr) { + capInfo.second.dupStream->Start(); } } + dupLock.unlock(); enterStandbyTime_ = 0; dualToneStreamInStart(); @@ -1026,7 +1031,10 @@ int32_t RendererInServer::Release() AudioService::GetInstance()->CleanAppUseNumMap(processConfig_.appInfo.appUid); } - int32_t ret = IStreamManager::GetPlaybackManager(managerType_).ReleaseRender(streamIndex_); + int32_t ret = CoreServiceHandler::GetInstance().UpdateSessionOperation(streamIndex_, SESSION_OPERATION_RELEASE); + CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Policy remove client failed, reason: %{public}d", ret); + ret = IStreamManager::GetPlaybackManager(managerType_).ReleaseRender(streamIndex_); + AudioVolume::GetInstance()->RemoveStreamVolume(streamIndex_); AudioService::GetInstance()->RemoveRenderer(streamIndex_); if (ret < 0) { @@ -1645,7 +1653,7 @@ RestoreStatus RendererInServer::RestoreSession(RestoreInfo restoreInfo) int32_t RendererInServer::SetDefaultOutputDevice(const DeviceType defaultOutputDevice) { - return PolicyHandler::GetInstance().SetDefaultOutputDevice(defaultOutputDevice, streamIndex_, + return CoreServiceHandler::GetInstance().SetDefaultOutputDevice(defaultOutputDevice, streamIndex_, processConfig_.rendererInfo.streamUsage, status_ == I_STATUS_STARTED); } diff --git a/services/audio_service/test/unittest/audio_manager_stub_unit_test/BUILD.gn b/services/audio_service/test/unittest/audio_manager_stub_unit_test/BUILD.gn index 92f8bd4acaf65ac051ad4ca6fb03bae560a3503f..c784d27585f1965f940c8c7acfe1d704b5a18c7c 100644 --- a/services/audio_service/test/unittest/audio_manager_stub_unit_test/BUILD.gn +++ b/services/audio_service/test/unittest/audio_manager_stub_unit_test/BUILD.gn @@ -50,7 +50,9 @@ ohos_unittest("audio_manager_stub_unit_test") { "../../../../../frameworks/native/hdiadapter/common/include", "../../../../../frameworks/native/hdiadapter/sink/common", "../../../../../frameworks/native/hdiadapter_new/include", + "../../../../../frameworks/native/hdiadapter_new/include/common", "../../../../../interfaces/inner_api/native/audiocommon/include", + "../../../../../frameworks/native/audiodefinitions/include", "../../../../../frameworks/native/audioinnercall/include", "../../../../../frameworks/native/hdiadapter/sink/common", "../../../../../services/audio_service/server/include", diff --git a/services/audio_service/test/unittest/audio_server_dump_unit_test/BUILD.gn b/services/audio_service/test/unittest/audio_server_dump_unit_test/BUILD.gn index 057ba2deece083a2829edec1d76243c1d31fedb4..910b9a4c5141288e57c5ae9c86f64762f806dd63 100644 --- a/services/audio_service/test/unittest/audio_server_dump_unit_test/BUILD.gn +++ b/services/audio_service/test/unittest/audio_server_dump_unit_test/BUILD.gn @@ -50,7 +50,9 @@ ohos_unittest("audio_server_dump_unit_test") { "../../../../../frameworks/native/hdiadapter/common/include", "../../../../../frameworks/native/hdiadapter/sink/common", "../../../../../frameworks/native/hdiadapter_new/include", + "../../../../../frameworks/native/hdiadapter_new/include/common", "../../../../../interfaces/inner_api/native/audiocommon/include", + "../../../../../frameworks/native/audiodefinitions/include", "../../../../../frameworks/native/audioinnercall/include", "../../../../../frameworks/native/hdiadapter/sink/common", "../../../../../services/audio_service/server/include", diff --git a/services/audio_service/test/unittest/renderer_in_server_unit_test/BUILD.gn b/services/audio_service/test/unittest/renderer_in_server_unit_test/BUILD.gn index f638d26314408dbabeeb0d5af2f4ca3aca608659..517c104341cacecbd172a372c93ed304fdcf572d 100644 --- a/services/audio_service/test/unittest/renderer_in_server_unit_test/BUILD.gn +++ b/services/audio_service/test/unittest/renderer_in_server_unit_test/BUILD.gn @@ -51,7 +51,9 @@ ohos_unittest("renderer_in_server_unit_test") { "../../../../../frameworks/native/audioutils/include", "../../../../../frameworks/native/hdiadapter/common/include", "../../../../../frameworks/native/hdiadapter/sink/common", + "../../../../../frameworks/native/hdiadapter_new/include/common", "../../../../../interfaces/inner_api/native/audiocommon/include", + "../../../../../frameworks/native/audiodefinitions/include", "../../../../../frameworks/native/audioinnercall/include", "../../../../../frameworks/native/hdiadapter/sink/common", "../../../../../frameworks/native/hdiadapter_new/include", diff --git a/test/fuzztest/audiohdiadapterdevicemanager_fuzzer/audio_hdi_adapter_devicemanager_fuzzer.cpp b/test/fuzztest/audiohdiadapterdevicemanager_fuzzer/audio_hdi_adapter_devicemanager_fuzzer.cpp index ad86f948726176ab40571a3b087fab283ee2375b..a56e2369b1289c99e60957842daff0e4e7bf67da 100644 --- a/test/fuzztest/audiohdiadapterdevicemanager_fuzzer/audio_hdi_adapter_devicemanager_fuzzer.cpp +++ b/test/fuzztest/audiohdiadapterdevicemanager_fuzzer/audio_hdi_adapter_devicemanager_fuzzer.cpp @@ -19,7 +19,9 @@ #include "audio_info.h" #include "audio_policy_server.h" #include "audio_policy_service.h" +#ifndef MAX_MIX_CHANNELS #include "audio_hdiadapter_info.h" +#endif #include "audio_device_info.h" #include "i_audio_device_manager.h" #include "audio_device_manager_impl.h"