1 /*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #ifndef LOG_TAG
16 #define LOG_TAG "AudioPolicyService"
17 #endif
18
19 #include "audio_policy_service.h"
20 #include <ability_manager_client.h>
21 #include "iservice_registry.h"
22 #include "parameter.h"
23 #include "audio_utils.h"
24 #include "audio_manager_listener_stub.h"
25 #include "parameters.h"
26 #include "data_share_observer_callback.h"
27 #include "device_init_callback.h"
28 #include "audio_inner_call.h"
29
30 #ifdef FEATURE_DEVICE_MANAGER
31 #endif
32 #include "audio_spatialization_service.h"
33 #include "audio_converter_parser.h"
34 #include "audio_dialog_ability_connection.h"
35
36 #include "media_monitor_manager.h"
37 #include "client_type_manager.h"
38
39 namespace OHOS {
40 namespace AudioStandard {
41 using namespace std;
42
43 static const std::string INNER_CAPTURER_SINK_LEGACY = "InnerCapturer";
44 static const std::string PIPE_PRIMARY_OUTPUT = "primary_output";
45 static const std::string PIPE_FAST_OUTPUT = "fast_output";
46 static const std::string PIPE_OFFLOAD_OUTPUT = "offload_output";
47 static const std::string PIPE_VOIP_OUTPUT = "voip_output";
48 static const std::string PIPE_PRIMARY_INPUT = "primary_input";
49 static const std::string PIPE_OFFLOAD_INPUT = "offload_input";
50 static const std::string PIPE_A2DP_OUTPUT = "a2dp_output";
51 static const std::string PIPE_FAST_A2DP_OUTPUT = "fast_a2dp_output";
52 static const std::string PIPE_USB_ARM_OUTPUT = "usb_arm_output";
53 static const std::string PIPE_USB_ARM_INPUT = "usb_arm_input";
54 static const std::string PIPE_DISTRIBUTED_OUTPUT = "distributed_output";
55 static const std::string PIPE_FAST_DISTRIBUTED_OUTPUT = "fast_distributed_output";
56 static const std::string PIPE_DISTRIBUTED_INPUT = "distributed_input";
57 static const std::string CHECK_FAST_BLOCK_PREFIX = "Is_Fast_Blocked_For_AppName#";
58 static const std::string PIPE_WAKEUP_INPUT = "wakeup_input";
59 static const int64_t CALL_IPC_COST_TIME_MS = 20000000; // 20ms
60 static const int32_t WAIT_OFFLOAD_CLOSE_TIME_S = 10; // 10s
61 static const int64_t OLD_DEVICE_UNAVALIABLE_MUTE_MS = 1000000; // 1s
62 static const int64_t OLD_DEVICE_UNAVALIABLE_EXT_MUTE_MS = 300000; // 300ms
63 static const int64_t OLD_DEVICE_UNAVALIABLE_MUTE_SLEEP_MS = 150000; // 150ms
64 static const int64_t SELECT_DEVICE_MUTE_MS = 200000; // 200ms
65 static const int64_t SELECT_OFFLOAD_DEVICE_MUTE_MS = 400000; // 400ms
66 static const int64_t NEW_DEVICE_AVALIABLE_MUTE_MS = 400000; // 400ms
67 static const int64_t NEW_DEVICE_AVALIABLE_OFFLOAD_MUTE_MS = 1000000; // 1s
68 static const int64_t SET_BT_ABS_SCENE_DELAY_MS = 120000; // 120ms
69 static const int64_t NEW_DEVICE_REMOTE_CAST_AVALIABLE_MUTE_MS = 300000; // 300ms
70 static const unsigned int BUFFER_CALC_20MS = 20;
71 static const unsigned int BUFFER_CALC_1000MS = 1000;
72 static const int64_t WAIT_LOAD_DEFAULT_DEVICE_TIME_MS = 5000; // 5s
73 static const int64_t WAIT_SET_MUTE_LATENCY_TIME_US = 80000; // 80ms
74 static const int64_t WAIT_MODEM_CALL_SET_VOLUME_TIME_US = 120000; // 120ms
75 static const int64_t WAIT_MOVE_DEVICE_MUTE_TIME_MAX_MS = 5000; // 5s
76 static const int64_t WAIT_RINGER_MODE_MUTE_RESET_TIME_MS = 500; // 500ms
77 static const int32_t INITIAL_VALUE = 1;
78 static const int32_t INVALID_APP_UID = -1;
79 static const int32_t INVALID_APP_CREATED_AUDIO_STREAM_NUM = -1;
80 static const int VOLUME_LEVEL_DEFAULT_SIZE = 3;
81
82 static const std::vector<AudioVolumeType> VOLUME_TYPE_LIST = {
83 STREAM_VOICE_CALL,
84 STREAM_RING,
85 STREAM_MUSIC,
86 STREAM_VOICE_ASSISTANT,
87 STREAM_ALARM,
88 STREAM_ACCESSIBILITY,
89 STREAM_ULTRASONIC,
90 STREAM_VOICE_CALL_ASSISTANT,
91 STREAM_ALL
92 };
93
94 static std::map<std::string, uint32_t> formatFromParserStrToEnum = {
95 {"s16le", SAMPLE_S16LE},
96 {"s24le", SAMPLE_S24LE},
97 {"s32le", SAMPLE_S32LE},
98 };
99
100 std::map<std::string, uint32_t> AudioPolicyService::formatStrToEnum = {
101 {"SAMPLE_U8", SAMPLE_U8},
102 {"SAMPLE_S16E", SAMPLE_S16LE},
103 {"SAMPLE_S24LE", SAMPLE_S24LE},
104 {"SAMPLE_S32LE", SAMPLE_S32LE},
105 {"SAMPLE_F32LE", SAMPLE_F32LE},
106 {"INVALID_WIDTH", INVALID_WIDTH},
107 };
108
109 std::map<std::string, ClassType> AudioPolicyService::classStrToEnum = {
110 {PRIMARY_CLASS, TYPE_PRIMARY},
111 {A2DP_CLASS, TYPE_A2DP},
112 {USB_CLASS, TYPE_USB},
113 {DP_CLASS, TYPE_DP},
114 {FILE_CLASS, TYPE_FILE_IO},
115 {REMOTE_CLASS, TYPE_REMOTE_AUDIO},
116 {INVALID_CLASS, TYPE_INVALID},
117 };
118
119 static std::map<std::string, ClassType> portStrToEnum = {
120 {PRIMARY_SPEAKER, TYPE_PRIMARY},
121 {PRIMARY_MIC, TYPE_PRIMARY},
122 {PRIMARY_WAKEUP_MIC, TYPE_PRIMARY},
123 {BLUETOOTH_SPEAKER, TYPE_A2DP},
124 {USB_SPEAKER, TYPE_USB},
125 {USB_MIC, TYPE_USB},
126 {DP_SINK, TYPE_DP},
127 {FILE_SINK, TYPE_FILE_IO},
128 {FILE_SOURCE, TYPE_FILE_IO},
129 {REMOTE_CLASS, TYPE_REMOTE_AUDIO},
130 };
131
132 std::map<std::string, std::string> AudioPolicyService::sinkPortStrToClassStrMap_ = {
133 {PRIMARY_SPEAKER, PRIMARY_CLASS},
134 {BLUETOOTH_SPEAKER, A2DP_CLASS},
135 {USB_SPEAKER, USB_CLASS},
136 {DP_SINK, DP_CLASS},
137 {OFFLOAD_PRIMARY_SPEAKER, OFFLOAD_CLASS},
138 };
139
140 static const std::string SETTINGS_DATA_BASE_URI =
141 "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true";
142 static const std::string SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility";
143 static const std::string SETTINGS_DATA_FIELD_KEYWORD = "KEYWORD";
144 static const std::string SETTINGS_DATA_FIELD_VALUE = "VALUE";
145 static const std::string PREDICATES_STRING = "settings.general.device_name";
146 static const std::string EARPIECE_TYPE_NAME = "DEVICE_TYPE_EARPIECE";
147 static const std::string FLAG_MMAP_STRING = "AUDIO_FLAG_MMAP";
148 static const std::string USAGE_VOIP_STRING = "AUDIO_USAGE_VOIP";
149 const uint32_t PCM_8_BIT = 8;
150 const uint32_t PCM_16_BIT = 16;
151 const uint32_t PCM_24_BIT = 24;
152 const uint32_t PCM_32_BIT = 32;
153 const int32_t DEFAULT_MAX_OUTPUT_NORMAL_INSTANCES = 128;
154 const uint32_t BT_BUFFER_ADJUSTMENT_FACTOR = 50;
155 const uint32_t ABS_VOLUME_SUPPORT_RETRY_INTERVAL_IN_MICROSECONDS = 10000;
156 const uint32_t REHANDLE_DEVICE_RETRY_INTERVAL_IN_MICROSECONDS = 30000;
157 const float RENDER_FRAME_INTERVAL_IN_SECONDS = 0.02;
158 const int32_t DUAL_TONE_RING_VOLUME = 0;
159 const uint32_t USER_NOT_SELECT_BT = 1;
160 const uint32_t USER_SELECT_BT = 2;
161 const std::string AUDIO_SERVICE_PKG = "audio_manager_service";
162 const int32_t UID_AUDIO = 1041;
163 const int MEDIA_RENDER_ID = 0;
164 const int CALL_RENDER_ID = 1;
165 const int CALL_CAPTURE_ID = 2;
166 const int RECORD_CAPTURE_ID = 3;
167 const int32_t ONE_MINUTE = 60;
168 constexpr int32_t MS_PER_S = 1000;
169 constexpr int32_t NS_PER_MS = 1000000;
170 const int32_t DATA_LINK_CONNECTING = 10;
171 const int32_t DATA_LINK_CONNECTED = 11;
172 const int32_t A2DP_PLAYING = 2;
173 const int32_t A2DP_STOPPED = 1;
174 static sptr<IStandardAudioService> g_adProxy = nullptr;
175 #ifdef BLUETOOTH_ENABLE
176 static sptr<IStandardAudioService> g_btProxy = nullptr;
177 #endif
178 static int32_t startDeviceId = 1;
179 static int32_t startMicrophoneId = 1;
180 mutex g_adProxyMutex;
181 #ifdef BLUETOOTH_ENABLE
182 const unsigned int BLUETOOTH_TIME_OUT_SECONDS = 8;
183 mutex g_btProxyMutex;
184 #endif
185 bool AudioPolicyService::isBtListenerRegistered = false;
186
ConvertToHDIAudioFormat(AudioSampleFormat sampleFormat)187 static string ConvertToHDIAudioFormat(AudioSampleFormat sampleFormat)
188 {
189 switch (sampleFormat) {
190 case SAMPLE_U8:
191 return "u8";
192 case SAMPLE_S16LE:
193 return "s16le";
194 case SAMPLE_S24LE:
195 return "s24le";
196 case SAMPLE_S32LE:
197 return "s32le";
198 default:
199 return "";
200 }
201 }
202
GetSampleFormatValue(AudioSampleFormat sampleFormat)203 static uint32_t GetSampleFormatValue(AudioSampleFormat sampleFormat)
204 {
205 switch (sampleFormat) {
206 case SAMPLE_U8:
207 return PCM_8_BIT;
208 case SAMPLE_S16LE:
209 return PCM_16_BIT;
210 case SAMPLE_S24LE:
211 return PCM_24_BIT;
212 case SAMPLE_S32LE:
213 return PCM_32_BIT;
214 default:
215 return PCM_16_BIT;
216 }
217 }
218
ParseAudioFormat(string format)219 static string ParseAudioFormat(string format)
220 {
221 if (format == "AUDIO_FORMAT_PCM_16_BIT") {
222 return "s16";
223 } else if (format == "AUDIO_FORMAT_PCM_24_BIT") {
224 return "s24";
225 } else if (format == "AUDIO_FORMAT_PCM_32_BIT") {
226 return "s32";
227 } else {
228 return "";
229 }
230 }
231
GetUsbModuleInfo(string deviceInfo,AudioModuleInfo & moduleInfo)232 static void GetUsbModuleInfo(string deviceInfo, AudioModuleInfo &moduleInfo)
233 {
234 if (moduleInfo.role == "sink") {
235 auto sinkRate_begin = deviceInfo.find("sink_rate:");
236 auto sinkRate_end = deviceInfo.find_first_of(";", sinkRate_begin);
237 moduleInfo.rate = deviceInfo.substr(sinkRate_begin + std::strlen("sink_rate:"),
238 sinkRate_end - sinkRate_begin - std::strlen("sink_rate:"));
239 auto sinkFormat_begin = deviceInfo.find("sink_format:");
240 auto sinkFormat_end = deviceInfo.find_first_of(";", sinkFormat_begin);
241 string format = deviceInfo.substr(sinkFormat_begin + std::strlen("sink_format:"),
242 sinkFormat_end - sinkFormat_begin - std::strlen("sink_format:"));
243 moduleInfo.format = ParseAudioFormat(format);
244 } else {
245 auto sourceRate_begin = deviceInfo.find("source_rate:");
246 auto sourceRate_end = deviceInfo.find_first_of(";", sourceRate_begin);
247 moduleInfo.rate = deviceInfo.substr(sourceRate_begin + std::strlen("source_rate:"),
248 sourceRate_end - sourceRate_begin - std::strlen("source_rate:"));
249 auto sourceFormat_begin = deviceInfo.find("source_format:");
250 auto sourceFormat_end = deviceInfo.find_first_of(";", sourceFormat_begin);
251 string format = deviceInfo.substr(sourceFormat_begin + std::strlen("source_format:"),
252 sourceFormat_end - sourceFormat_begin - std::strlen("source_format:"));
253 moduleInfo.format = ParseAudioFormat(format);
254 }
255 }
256
GetDPModuleInfo(AudioModuleInfo & moduleInfo,string deviceInfo)257 static void GetDPModuleInfo(AudioModuleInfo &moduleInfo, string deviceInfo)
258 {
259 if (moduleInfo.role == "sink") {
260 auto sinkRate_begin = deviceInfo.find("rate=");
261 auto sinkRate_end = deviceInfo.find_first_of(" ", sinkRate_begin);
262 moduleInfo.rate = deviceInfo.substr(sinkRate_begin + std::strlen("rate="),
263 sinkRate_end - sinkRate_begin - std::strlen("rate="));
264
265 auto sinkFormat_begin = deviceInfo.find("format=");
266 auto sinkFormat_end = deviceInfo.find_first_of(" ", sinkFormat_begin);
267 string format = deviceInfo.substr(sinkFormat_begin + std::strlen("format="),
268 sinkFormat_end - sinkFormat_begin - std::strlen("format="));
269 if (!format.empty()) moduleInfo.format = format;
270
271 auto sinkChannel_begin = deviceInfo.find("channels=");
272 auto sinkChannel_end = deviceInfo.find_first_of(" ", sinkChannel_begin);
273 string channel = deviceInfo.substr(sinkChannel_begin + std::strlen("channels="),
274 sinkChannel_end - sinkChannel_begin - std::strlen("channels="));
275 moduleInfo.channels = channel;
276
277 auto sinkBSize_begin = deviceInfo.find("buffer_size=");
278 auto sinkBSize_end = deviceInfo.find_first_of(" ", sinkBSize_begin);
279 string bufferSize = deviceInfo.substr(sinkBSize_begin + std::strlen("buffer_size="),
280 sinkBSize_end - sinkBSize_begin - std::strlen("buffer_size="));
281 moduleInfo.bufferSize = bufferSize;
282 }
283 }
284
GetCurrentTimeMS()285 static int64_t GetCurrentTimeMS()
286 {
287 timespec tm {};
288 clock_gettime(CLOCK_MONOTONIC, &tm);
289 return tm.tv_sec * MS_PER_S + (tm.tv_nsec / NS_PER_MS);
290 }
291
PcmFormatToBits(AudioSampleFormat format)292 static uint32_t PcmFormatToBits(AudioSampleFormat format)
293 {
294 switch (format) {
295 case SAMPLE_U8:
296 return 1; // 1 byte
297 case SAMPLE_S16LE:
298 return 2; // 2 byte
299 case SAMPLE_S24LE:
300 return 3; // 3 byte
301 case SAMPLE_S32LE:
302 return 4; // 4 byte
303 case SAMPLE_F32LE:
304 return 4; // 4 byte
305 default:
306 return 2; // 2 byte
307 }
308 }
309
~AudioPolicyService()310 AudioPolicyService::~AudioPolicyService()
311 {
312 AUDIO_WARNING_LOG("~AudioPolicyService()");
313 Deinit();
314 }
315
Init(void)316 bool AudioPolicyService::Init(void)
317 {
318 AUDIO_INFO_LOG("Audio policy service init enter");
319 serviceFlag_.reset();
320 audioPolicyManager_.Init();
321 audioEffectService_.EffectServiceInit();
322 audioDeviceManager_.ParseDeviceXml();
323 audioPnpServer_.init();
324 audioA2dpOffloadManager_ = std::make_shared<AudioA2dpOffloadManager>(this);
325 if (audioA2dpOffloadManager_ != nullptr) {audioA2dpOffloadManager_->Init();}
326
327 bool ret = audioPolicyConfigParser_.LoadConfiguration();
328 if (!ret) {
329 WriteServiceStartupError("Audio Policy Config Load Configuration failed");
330 isPolicyConfigParsered_ = true;
331 }
332 CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Policy Config Load Configuration failed");
333 ret = audioPolicyConfigParser_.Parse();
334 isPolicyConfigParsered_ = true;
335 isFastControlled_ = getFastControlParam();
336 if (!ret) {
337 WriteServiceStartupError("Audio Config Parse failed");
338 }
339 CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Config Parse failed");
340
341 #ifdef FEATURE_DTMF_TONE
342 ret = LoadToneDtmfConfig();
343 CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Tone Load Configuration failed");
344 #endif
345
346 int32_t status = deviceStatusListener_->RegisterDeviceStatusListener();
347 if (status != SUCCESS) {
348 WriteServiceStartupError("[Policy Service] Register for device status events failed");
349 }
350 CHECK_AND_RETURN_RET_LOG(status == SUCCESS, false, "[Policy Service] Register for device status events failed");
351
352 RegisterRemoteDevStatusCallback();
353
354 if (policyVolumeMap_ == nullptr) {
355 size_t mapSize = IPolicyProvider::GetVolumeVectorSize() * sizeof(Volume) + sizeof(bool);
356 AUDIO_INFO_LOG("InitSharedVolume create shared volume map with size %{public}zu", mapSize);
357 policyVolumeMap_ = AudioSharedMemory::CreateFormLocal(mapSize, "PolicyVolumeMap");
358 CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr,
359 false, "Get shared memory failed!");
360 volumeVector_ = reinterpret_cast<Volume *>(policyVolumeMap_->GetBase());
361 sharedAbsVolumeScene_ = reinterpret_cast<bool *>(policyVolumeMap_->GetBase()) +
362 IPolicyProvider::GetVolumeVectorSize() * sizeof(Volume);
363 }
364
365 AUDIO_INFO_LOG("Audio policy service init end");
366 CreateRecoveryThread();
367 std::string versionType = OHOS::system::GetParameter("const.logsystem.versiontype", "commercial");
368 AudioDump::GetInstance().SetVersionType(versionType);
369
370 return true;
371 }
372
GetAudioServerProxy()373 const sptr<IStandardAudioService> AudioPolicyService::GetAudioServerProxy()
374 {
375 AUDIO_DEBUG_LOG("[Policy Service] Start get audio policy service proxy.");
376 lock_guard<mutex> lock(g_adProxyMutex);
377
378 if (g_adProxy == nullptr) {
379 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
380 CHECK_AND_RETURN_RET_LOG(samgr != nullptr, nullptr, "[Policy Service] Get samgr failed.");
381
382 sptr<IRemoteObject> object = samgr->GetSystemAbility(AUDIO_DISTRIBUTED_SERVICE_ID);
383 CHECK_AND_RETURN_RET_LOG(object != nullptr, nullptr,
384 "[Policy Service] audio service remote object is NULL.");
385
386 g_adProxy = iface_cast<IStandardAudioService>(object);
387 CHECK_AND_RETURN_RET_LOG(g_adProxy != nullptr, nullptr,
388 "[Policy Service] init g_adProxy is NULL.");
389 }
390 const sptr<IStandardAudioService> gsp = g_adProxy;
391 return gsp;
392 }
393
CreateRecoveryThread()394 void AudioPolicyService::CreateRecoveryThread()
395 {
396 if (RecoveryDevicesThread_ != nullptr) {
397 RecoveryDevicesThread_->detach();
398 }
399 RecoveryDevicesThread_ = std::make_unique<std::thread>([this] { this->RecoveryPreferredDevices(); });
400 pthread_setname_np(RecoveryDevicesThread_->native_handle(), "APSRecovery");
401 }
402
RecoveryPreferredDevices()403 void AudioPolicyService::RecoveryPreferredDevices()
404 {
405 AUDIO_DEBUG_LOG("Start recovery peferred devices.");
406 int32_t tryCounter = 5;
407 // Waiting for 1000000 渭s. Ensure that the playback/recording stream is restored first
408 uint32_t firstSleepTime = 1000000;
409 // Retry interval
410 uint32_t sleepTime = 300000;
411 int32_t result = -1;
412 std::map<Media::MediaMonitor::PerferredType,
413 std::shared_ptr<Media::MediaMonitor::MonitorDeviceInfo>> preferredDevices;
414 usleep(firstSleepTime);
415 while (result != SUCCESS && tryCounter-- > 0) {
416 Media::MediaMonitor::MediaMonitorManager::GetInstance().GetAudioRouteMsg(preferredDevices);
417 if (preferredDevices.size() == 0) {
418 AUDIO_ERR_LOG("The length of preferredDevices is 0 and does not need to be set.");
419 continue;
420 }
421 for (auto iter = preferredDevices.begin(); iter != preferredDevices.end(); ++iter) {
422 result = HandleRecoveryPreferredDevices(static_cast<int32_t>(iter->first), iter->second->deviceType_,
423 iter->second->usageOrSourceType_);
424 if (result != SUCCESS) {
425 AUDIO_ERR_LOG("Handle recovery preferred devices failed"
426 ", deviceType:%{public}d, usageOrSourceType:%{public}d, tryCounter:%{public}d",
427 iter->second->deviceType_, iter->second->usageOrSourceType_, tryCounter);
428 }
429 }
430 if (result != SUCCESS) {
431 usleep(sleepTime);
432 }
433 }
434 }
435
HandleRecoveryPreferredDevices(int32_t preferredType,int32_t deviceType,int32_t usageOrSourceType)436 int32_t AudioPolicyService::HandleRecoveryPreferredDevices(int32_t preferredType, int32_t deviceType,
437 int32_t usageOrSourceType)
438 {
439 int32_t result = -1;
440 auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &desc) {
441 if (deviceType == desc->deviceType_) {
442 return true;
443 }
444 return false;
445 };
446 auto it = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
447 if (it != connectedDevices_.end()) {
448 vector<sptr<AudioDeviceDescriptor>> deviceDescriptorVector;
449 deviceDescriptorVector.push_back(*it);
450 if (preferredType == Media::MediaMonitor::MEDIA_RENDER ||
451 preferredType == Media::MediaMonitor::CALL_RENDER ||
452 preferredType == Media::MediaMonitor::RING_RENDER ||
453 preferredType == Media::MediaMonitor::TONE_RENDER) {
454 sptr<AudioRendererFilter> audioRendererFilter = new(std::nothrow) AudioRendererFilter();
455 audioRendererFilter->uid = -1;
456 audioRendererFilter->rendererInfo.streamUsage =
457 static_cast<StreamUsage>(usageOrSourceType);
458 result = SelectOutputDevice(audioRendererFilter, deviceDescriptorVector);
459 } else if (preferredType == Media::MediaMonitor::CALL_CAPTURE ||
460 preferredType == Media::MediaMonitor::RECORD_CAPTURE) {
461 sptr<AudioCapturerFilter> audioCapturerFilter = new(std::nothrow) AudioCapturerFilter();
462 audioCapturerFilter->uid = -1;
463 audioCapturerFilter->capturerInfo.sourceType =
464 static_cast<SourceType>(usageOrSourceType);
465 result = SelectInputDevice(audioCapturerFilter, deviceDescriptorVector);
466 }
467 }
468 return result;
469 }
470
InitKVStore()471 void AudioPolicyService::InitKVStore()
472 {
473 audioPolicyManager_.InitKVStore();
474 UpdateVolumeForLowLatency();
475 AudioSpatializationService::GetAudioSpatializationService().InitSpatializationState();
476 }
477
UpdateVolumeForLowLatency()478 void AudioPolicyService::UpdateVolumeForLowLatency()
479 {
480 // update volumes for low latency streams when loading volumes from the database.
481 Volume vol = {false, 1.0f, 0};
482 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
483 for (auto iter = VOLUME_TYPE_LIST.begin(); iter != VOLUME_TYPE_LIST.end(); iter++) {
484 int32_t volumeLevel = GetSystemVolumeLevel(*iter);
485 vol.volumeFloat = GetSystemVolumeInDb(*iter, volumeLevel, curOutputDeviceType);
486 SetSharedVolume(*iter, curOutputDeviceType, vol);
487 }
488 SetSharedAbsVolumeScene(IsAbsVolumeScene());
489 }
490
ConnectServiceAdapter()491 bool AudioPolicyService::ConnectServiceAdapter()
492 {
493 bool ret = audioPolicyManager_.ConnectServiceAdapter();
494 CHECK_AND_RETURN_RET_LOG(ret, false, "Error in connecting to audio service adapter");
495
496 OnServiceConnected(AudioServiceIndex::AUDIO_SERVICE_INDEX);
497
498 return true;
499 }
500
Deinit(void)501 void AudioPolicyService::Deinit(void)
502 {
503 AUDIO_WARNING_LOG("Policy service died. closing active ports");
504
505 std::unique_lock<std::mutex> ioHandleLock(ioHandlesMutex_);
506 std::for_each(IOHandles_.begin(), IOHandles_.end(), [&](std::pair<std::string, AudioIOHandle> handle) {
507 audioPolicyManager_.CloseAudioPort(handle.second);
508 });
509 audioPolicyManager_.Deinit();
510
511 IOHandles_.clear();
512 ioHandleLock.unlock();
513 #ifdef ACCESSIBILITY_ENABLE
514 accessibilityConfigListener_->UnsubscribeObserver();
515 #endif
516 deviceStatusListener_->UnRegisterDeviceStatusListener();
517 audioPnpServer_.StopPnpServer();
518
519 if (isBtListenerRegistered) {
520 UnregisterBluetoothListener();
521 }
522 volumeVector_ = nullptr;
523 sharedAbsVolumeScene_ = nullptr;
524 policyVolumeMap_ = nullptr;
525 safeVolumeExit_ = true;
526 if (calculateLoopSafeTime_ != nullptr && calculateLoopSafeTime_->joinable()) {
527 calculateLoopSafeTime_->join();
528 calculateLoopSafeTime_.reset();
529 calculateLoopSafeTime_ = nullptr;
530 }
531 if (safeVolumeDialogThrd_ != nullptr && safeVolumeDialogThrd_->joinable()) {
532 safeVolumeDialogThrd_->join();
533 safeVolumeDialogThrd_.reset();
534 safeVolumeDialogThrd_ = nullptr;
535 }
536 if (RecoveryDevicesThread_ != nullptr && RecoveryDevicesThread_->joinable()) {
537 RecoveryDevicesThread_->join();
538 RecoveryDevicesThread_.reset();
539 RecoveryDevicesThread_ = nullptr;
540 }
541
542 return;
543 }
544
SetAudioStreamRemovedCallback(AudioStreamRemovedCallback * callback)545 int32_t AudioPolicyService::SetAudioStreamRemovedCallback(AudioStreamRemovedCallback *callback)
546 {
547 return audioPolicyManager_.SetAudioStreamRemovedCallback(callback);
548 }
549
GetMaxVolumeLevel(AudioVolumeType volumeType) const550 int32_t AudioPolicyService::GetMaxVolumeLevel(AudioVolumeType volumeType) const
551 {
552 if (volumeType == STREAM_ALL) {
553 volumeType = STREAM_MUSIC;
554 }
555 return audioPolicyManager_.GetMaxVolumeLevel(volumeType);
556 }
557
GetMinVolumeLevel(AudioVolumeType volumeType) const558 int32_t AudioPolicyService::GetMinVolumeLevel(AudioVolumeType volumeType) const
559 {
560 if (volumeType == STREAM_ALL) {
561 volumeType = STREAM_MUSIC;
562 }
563 return audioPolicyManager_.GetMinVolumeLevel(volumeType);
564 }
565
SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel)566 int32_t AudioPolicyService::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel)
567 {
568 int32_t result;
569 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
570 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC &&
571 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
572 result = SetA2dpDeviceVolume(activeBTDevice_, volumeLevel, true);
573 #ifdef BLUETOOTH_ENABLE
574 if (result == SUCCESS) {
575 // set to avrcp device
576 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(activeBTDevice_, volumeLevel);
577 } else if (result == ERR_UNKNOWN) {
578 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(activeBTDevice_,
579 audioPolicyManager_.GetSafeVolumeLevel());
580 } else {
581 AUDIO_ERR_LOG("AudioPolicyService::SetSystemVolumeLevel set abs volume failed");
582 }
583 #endif
584 }
585 int32_t sVolumeLevel = SelectDealSafeVolume(streamType, volumeLevel);
586 CHECK_AND_RETURN_RET_LOG(sVolumeLevel == volumeLevel, ERROR, "safevolume did not deal");
587 result = audioPolicyManager_.SetSystemVolumeLevel(streamType, volumeLevel);
588 if (result == SUCCESS && (streamType == STREAM_VOICE_CALL || streamType == STREAM_VOICE_COMMUNICATION)) {
589 SetVoiceCallVolume(volumeLevel);
590 }
591 // todo
592 Volume vol = {false, 1.0f, 0};
593 vol.volumeFloat = GetSystemVolumeInDb(streamType, volumeLevel, curOutputDeviceType);
594 SetSharedVolume(streamType, curOutputDeviceType, vol);
595
596 return result;
597 }
598
SelectDealSafeVolume(AudioStreamType streamType,int32_t volumeLevel)599 int32_t AudioPolicyService::SelectDealSafeVolume(AudioStreamType streamType, int32_t volumeLevel)
600 {
601 int32_t sVolumeLevel = volumeLevel;
602 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
603 DeviceCategory curOutputDeviceCategory = GetCurrentOutputDeviceCategory();
604 if (sVolumeLevel > audioPolicyManager_.GetSafeVolumeLevel() &&
605 VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC) {
606 switch (curOutputDeviceType) {
607 case DEVICE_TYPE_BLUETOOTH_A2DP:
608 case DEVICE_TYPE_BLUETOOTH_SCO:
609 if (curOutputDeviceCategory != BT_SOUNDBOX &&
610 curOutputDeviceCategory != BT_CAR) {
611 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
612 }
613 break;
614 case DEVICE_TYPE_WIRED_HEADSET:
615 case DEVICE_TYPE_WIRED_HEADPHONES:
616 case DEVICE_TYPE_USB_HEADSET:
617 case DEVICE_TYPE_USB_ARM_HEADSET:
618 sVolumeLevel = DealWithSafeVolume(volumeLevel, false);
619 break;
620 default:
621 AUDIO_INFO_LOG("unsupport safe volume:%{public}d", curOutputDeviceType);
622 break;
623 }
624 }
625 return sVolumeLevel;
626 }
627
SetVoiceRingtoneMute(bool isMute)628 int32_t AudioPolicyService::SetVoiceRingtoneMute(bool isMute)
629 {
630 AUDIO_INFO_LOG("Set Voice Ringtone is %{public}d", isMute);
631 isVoiceRingtoneMute_ = isMute ? true : false;
632 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL));
633 return SUCCESS;
634 }
635
SetVoiceCallVolume(int32_t volumeLevel)636 void AudioPolicyService::SetVoiceCallVolume(int32_t volumeLevel)
637 {
638 Trace trace("AudioPolicyService::SetVoiceCallVolume" + std::to_string(volumeLevel));
639 // set voice volume by the interface from hdi.
640 CHECK_AND_RETURN_LOG(volumeLevel != 0, "SetVoiceVolume: volume of voice_call cannot be set to 0");
641 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
642 CHECK_AND_RETURN_LOG(gsp != nullptr, "SetVoiceVolume: gsp null");
643 float volumeDb = static_cast<float>(volumeLevel) /
644 static_cast<float>(audioPolicyManager_.GetMaxVolumeLevel(STREAM_VOICE_CALL));
645 volumeDb = isVoiceRingtoneMute_ ? 0 : volumeDb;
646 // VGS feature
647 if (audioPolicyManager_.IsVgsVolumeSupported()) {
648 volumeDb = 1;
649 }
650
651 std::string identity = IPCSkeleton::ResetCallingIdentity();
652 gsp->SetVoiceVolume(volumeDb);
653 IPCSkeleton::SetCallingIdentity(identity);
654 AUDIO_INFO_LOG("SetVoiceVolume: %{public}f", volumeDb);
655 }
656
SetVolumeForSwitchDevice(DeviceType deviceType,const std::string & newSinkName)657 void AudioPolicyService::SetVolumeForSwitchDevice(DeviceType deviceType, const std::string &newSinkName)
658 {
659 Trace trace("AudioPolicyService::SetVolumeForSwitchDevice:" + std::to_string(deviceType));
660 // Load volume from KvStore and set volume for each stream type
661 audioPolicyManager_.SetVolumeForSwitchDevice(deviceType);
662
663 // The volume of voice_call needs to be adjusted separately
664 if (audioScene_ == AUDIO_SCENE_PHONE_CALL) {
665 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL));
666 }
667
668 UpdateVolumeForLowLatency();
669 }
670
GetVolumeGroupType(DeviceType deviceType)671 std::string AudioPolicyService::GetVolumeGroupType(DeviceType deviceType)
672 {
673 std::string volumeGroupType = "";
674 switch (deviceType) {
675 case DEVICE_TYPE_EARPIECE:
676 case DEVICE_TYPE_SPEAKER:
677 volumeGroupType = "build-in";
678 break;
679 case DEVICE_TYPE_BLUETOOTH_A2DP:
680 case DEVICE_TYPE_BLUETOOTH_SCO:
681 volumeGroupType = "wireless";
682 break;
683 case DEVICE_TYPE_WIRED_HEADSET:
684 case DEVICE_TYPE_USB_HEADSET:
685 case DEVICE_TYPE_DP:
686 case DEVICE_TYPE_USB_ARM_HEADSET:
687 volumeGroupType = "wired";
688 break;
689 default:
690 AUDIO_ERR_LOG("GetVolumeGroupType: device %{public}d is not supported", deviceType);
691 break;
692 }
693 return volumeGroupType;
694 }
695
GetSystemVolumeLevel(AudioStreamType streamType)696 int32_t AudioPolicyService::GetSystemVolumeLevel(AudioStreamType streamType)
697 {
698 if (streamType == STREAM_RING && !IsRingerModeMute()) {
699 AUDIO_PRERELEASE_LOGW("return 0 when dual tone ring");
700 return DUAL_TONE_RING_VOLUME;
701 }
702 {
703 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_);
704 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
705 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC &&
706 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
707 auto configInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_);
708 if (configInfoPos != connectedA2dpDeviceMap_.end()
709 && configInfoPos->second.absVolumeSupport) {
710 return configInfoPos->second.mute ? 0 : configInfoPos->second.volumeLevel;
711 } else {
712 AUDIO_WARNING_LOG("Get absolute volume failed for activeBTDevice :[%{public}s]",
713 GetEncryptAddr(activeBTDevice_).c_str());
714 }
715 }
716 }
717 return audioPolicyManager_.GetSystemVolumeLevel(streamType);
718 }
719
GetSystemVolumeDb(AudioStreamType streamType) const720 float AudioPolicyService::GetSystemVolumeDb(AudioStreamType streamType) const
721 {
722 return audioPolicyManager_.GetSystemVolumeDb(streamType);
723 }
724
SetLowPowerVolume(int32_t streamId,float volume) const725 int32_t AudioPolicyService::SetLowPowerVolume(int32_t streamId, float volume) const
726 {
727 return streamCollector_.SetLowPowerVolume(streamId, volume);
728 }
729
GetLowPowerVolume(int32_t streamId) const730 float AudioPolicyService::GetLowPowerVolume(int32_t streamId) const
731 {
732 return streamCollector_.GetLowPowerVolume(streamId);
733 }
734
735
SetOffloadMode()736 void AudioPolicyService::SetOffloadMode()
737 {
738 if (!GetOffloadAvailableFromXml()) {
739 AUDIO_INFO_LOG("Offload not available, skipped");
740 return;
741 }
742
743 AUDIO_INFO_LOG("sessionId: %{public}d, PowerState: %{public}d, isAppBack: %{public}d",
744 *offloadSessionID_, static_cast<int32_t>(currentPowerState_), currentOffloadSessionIsBackground_);
745
746 streamCollector_.SetOffloadMode(*offloadSessionID_, static_cast<int32_t>(currentPowerState_),
747 currentOffloadSessionIsBackground_);
748 }
749
ResetOffloadMode(int32_t sessionId)750 void AudioPolicyService::ResetOffloadMode(int32_t sessionId)
751 {
752 AUDIO_DEBUG_LOG("Doing reset offload mode!");
753
754 if (!CheckActiveOutputDeviceSupportOffload()) {
755 AUDIO_DEBUG_LOG("Resetting offload not available on this output device! Release.");
756 OffloadStreamReleaseCheck(*offloadSessionID_);
757 return;
758 }
759
760 OffloadStreamSetCheck(sessionId);
761 }
762
OffloadStreamSetCheck(uint32_t sessionId)763 void AudioPolicyService::OffloadStreamSetCheck(uint32_t sessionId)
764 {
765 AudioPipeType pipeType = PIPE_TYPE_OFFLOAD;
766 int32_t ret = ActivateAudioConcurrency(pipeType);
767 if (ret != SUCCESS) {
768 return;
769 }
770 AudioDeviceDescriptor deviceInfo(AudioDeviceDescriptor::DEVICE_INFO);
771 std::string curOutputNetworkId = GetCurrentOutputDeviceNetworkId();
772 std::string curOutputMacAddr = GetCurrentOutputDeviceMacAddr();
773 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
774 ret = streamCollector_.GetRendererDeviceInfo(sessionId, deviceInfo);
775 if (ret != SUCCESS || curOutputNetworkId != LOCAL_NETWORK_ID ||
776 curOutputDeviceType == DEVICE_TYPE_REMOTE_CAST ||
777 deviceInfo.deviceType_ != curOutputDeviceType ||
778 deviceInfo.networkId_ != curOutputNetworkId ||
779 deviceInfo.macAddress_ != curOutputMacAddr) {
780 AUDIO_INFO_LOG("sessionId[%{public}d] not fetch device, Offload Skipped", sessionId);
781 return;
782 }
783
784 AudioStreamType streamType = GetStreamType(sessionId);
785 if (!CheckStreamOffloadMode(sessionId, streamType)) {
786 return;
787 }
788
789 auto CallingUid = IPCSkeleton::GetCallingUid();
790 AUDIO_INFO_LOG("sessionId[%{public}d] CallingUid[%{public}d] StreamType[%{public}d] "
791 "Getting offload stream", sessionId, CallingUid, streamType);
792 std::lock_guard<std::mutex> lock(offloadMutex_);
793
794 if (!offloadSessionID_.has_value()) {
795 offloadSessionID_ = sessionId;
796 audioPolicyManager_.SetOffloadSessionId(sessionId);
797
798 AUDIO_DEBUG_LOG("sessionId[%{public}d] try get offload stream", sessionId);
799 if (MoveToNewPipeInner(sessionId, PIPE_TYPE_OFFLOAD) != SUCCESS) {
800 AUDIO_ERR_LOG("sessionId[%{public}d] CallingUid[%{public}d] StreamType[%{public}d] "
801 "failed to offload stream", sessionId, CallingUid, streamType);
802 offloadSessionID_.reset();
803 audioPolicyManager_.ResetOffloadSessionId();
804 return;
805 }
806 SetOffloadMode();
807 } else {
808 if (sessionId == *(offloadSessionID_)) {
809 AUDIO_DEBUG_LOG("sessionId[%{public}d] is already get offload stream", sessionId);
810 } else {
811 AUDIO_DEBUG_LOG("sessionId[%{public}d] no get offload, current offload sessionId[%{public}d]",
812 sessionId, *(offloadSessionID_));
813 }
814 }
815
816 return;
817 }
818
OffloadStreamReleaseCheck(uint32_t sessionId)819 void AudioPolicyService::OffloadStreamReleaseCheck(uint32_t sessionId)
820 {
821 if (!GetOffloadAvailableFromXml()) {
822 AUDIO_INFO_LOG("Offload not available, skipped for release");
823 return;
824 }
825
826 std::lock_guard<std::mutex> lock(offloadMutex_);
827
828 if (((*offloadSessionID_) == sessionId) && offloadSessionID_.has_value()) {
829 AUDIO_DEBUG_LOG("Doing unset offload mode!");
830 streamCollector_.UnsetOffloadMode(*offloadSessionID_);
831 AudioPipeType normalPipe = PIPE_TYPE_NORMAL_OUT;
832 MoveToNewPipe(sessionId, normalPipe);
833 streamCollector_.UpdateRendererPipeInfo(sessionId, normalPipe);
834 DynamicUnloadModule(PIPE_TYPE_OFFLOAD);
835 offloadSessionID_.reset();
836 audioPolicyManager_.ResetOffloadSessionId();
837 AUDIO_DEBUG_LOG("sessionId[%{public}d] release offload stream", sessionId);
838 } else {
839 if (offloadSessionID_.has_value()) {
840 AUDIO_DEBUG_LOG("sessionId[%{public}d] stopping stream not get offload, current offload [%{public}d]",
841 sessionId, *offloadSessionID_);
842 } else {
843 AUDIO_DEBUG_LOG("sessionId[%{public}d] stopping stream not get offload, current offload stream is None",
844 sessionId);
845 }
846 }
847 return;
848 }
849
RemoteOffloadStreamRelease(uint32_t sessionId)850 void AudioPolicyService::RemoteOffloadStreamRelease(uint32_t sessionId)
851 {
852 std::lock_guard<std::mutex> lock(offloadMutex_);
853 if (offloadSessionID_.has_value() && ((*offloadSessionID_) == sessionId)) {
854 AUDIO_DEBUG_LOG("Doing unset offload mode!");
855 streamCollector_.UnsetOffloadMode(*offloadSessionID_);
856 AudioPipeType normalPipe = PIPE_TYPE_UNKNOWN;
857 MoveToNewPipe(sessionId, normalPipe);
858 streamCollector_.UpdateRendererPipeInfo(sessionId, normalPipe);
859 DynamicUnloadModule(PIPE_TYPE_OFFLOAD);
860 offloadSessionID_.reset();
861 audioPolicyManager_.ResetOffloadSessionId();
862 AUDIO_DEBUG_LOG("sessionId[%{public}d] release offload stream", sessionId);
863 }
864 }
865
CheckActiveOutputDeviceSupportOffload()866 bool AudioPolicyService::CheckActiveOutputDeviceSupportOffload()
867 {
868 DeviceType dev = GetCurrentOutputDeviceType();
869 if (GetCurrentOutputDeviceNetworkId() != LOCAL_NETWORK_ID || dev == DEVICE_TYPE_REMOTE_CAST) {
870 return false;
871 }
872
873 return dev == DEVICE_TYPE_SPEAKER || (dev == DEVICE_TYPE_BLUETOOTH_A2DP && a2dpOffloadFlag_ == A2DP_OFFLOAD) ||
874 dev == DEVICE_TYPE_USB_HEADSET;
875 }
876
SetOffloadAvailableFromXML(AudioModuleInfo & moduleInfo)877 void AudioPolicyService::SetOffloadAvailableFromXML(AudioModuleInfo &moduleInfo)
878 {
879 if (moduleInfo.name == "Speaker") {
880 for (const auto &portInfo : moduleInfo.ports) {
881 if ((portInfo.adapterName == "primary") && (portInfo.offloadEnable == "1")) {
882 isOffloadAvailable_ = true;
883 }
884 }
885 }
886 }
887
GetOffloadAvailableFromXml() const888 bool AudioPolicyService::GetOffloadAvailableFromXml() const
889 {
890 return isOffloadAvailable_;
891 }
892
HandlePowerStateChanged(PowerMgr::PowerState state)893 void AudioPolicyService::HandlePowerStateChanged(PowerMgr::PowerState state)
894 {
895 if (currentPowerState_ == state) {
896 return;
897 }
898 currentPowerState_ = state;
899 if (!CheckActiveOutputDeviceSupportOffload()) {
900 return;
901 }
902 if (offloadSessionID_.has_value()) {
903 AUDIO_DEBUG_LOG("SetOffloadMode! Offload power is state = %{public}d", state);
904 SetOffloadMode();
905 }
906 }
907
GetSingleStreamVolume(int32_t streamId) const908 float AudioPolicyService::GetSingleStreamVolume(int32_t streamId) const
909 {
910 return streamCollector_.GetSingleStreamVolume(streamId);
911 }
912
SetStreamMute(AudioStreamType streamType,bool mute,const StreamUsage & streamUsage)913 int32_t AudioPolicyService::SetStreamMute(AudioStreamType streamType, bool mute, const StreamUsage &streamUsage)
914 {
915 int32_t result = SUCCESS;
916 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
917 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC &&
918 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
919 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_);
920 auto configInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_);
921 if (configInfoPos == connectedA2dpDeviceMap_.end() || !configInfoPos->second.absVolumeSupport) {
922 AUDIO_WARNING_LOG("Set failed for macAddress:[%{public}s]", GetEncryptAddr(activeBTDevice_).c_str());
923 } else {
924 configInfoPos->second.mute = mute;
925 audioPolicyManager_.SetAbsVolumeMute(mute);
926 #ifdef BLUETOOTH_ENABLE
927 // set to avrcp device
928 if (mute) {
929 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(activeBTDevice_, 0);
930 } else {
931 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(activeBTDevice_,
932 configInfoPos->second.volumeLevel);
933 }
934 #endif
935 }
936 }
937 result = audioPolicyManager_.SetStreamMute(streamType, mute, streamUsage);
938
939 Volume vol = {false, 1.0f, 0};
940 vol.isMute = mute;
941 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevel(streamType));
942 vol.volumeFloat = GetSystemVolumeInDb(streamType, vol.volumeInt, curOutputDeviceType);
943 SetSharedVolume(streamType, curOutputDeviceType, vol);
944
945 return result;
946 }
947
SetSourceOutputStreamMute(int32_t uid,bool setMute) const948 int32_t AudioPolicyService::SetSourceOutputStreamMute(int32_t uid, bool setMute) const
949 {
950 int32_t status = audioPolicyManager_.SetSourceOutputStreamMute(uid, setMute);
951 if (status > 0) {
952 streamCollector_.UpdateCapturerInfoMuteStatus(uid, setMute);
953 }
954 return status;
955 }
956
GetStreamMute(AudioStreamType streamType)957 bool AudioPolicyService::GetStreamMute(AudioStreamType streamType)
958 {
959 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
960 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC &&
961 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
962 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_);
963 auto configInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_);
964 if (configInfoPos == connectedA2dpDeviceMap_.end() || !configInfoPos->second.absVolumeSupport) {
965 AUDIO_WARNING_LOG("Get failed for macAddress:[%{public}s]", GetEncryptAddr(activeBTDevice_).c_str());
966 } else {
967 return configInfoPos->second.mute;
968 }
969 }
970 return audioPolicyManager_.GetStreamMute(streamType);
971 }
972
PrintSinkInput(SinkInput sinkInput)973 inline std::string PrintSinkInput(SinkInput sinkInput)
974 {
975 std::stringstream value;
976 value << "streamId:[" << sinkInput.streamId << "] ";
977 value << "streamType:[" << sinkInput.streamType << "] ";
978 value << "uid:[" << sinkInput.uid << "] ";
979 value << "pid:[" << sinkInput.pid << "] ";
980 value << "statusMark:[" << sinkInput.statusMark << "] ";
981 value << "sinkName:[" << sinkInput.sinkName << "] ";
982 value << "startTime:[" << sinkInput.startTime << "]";
983 return value.str();
984 }
985
PrintSourceOutput(SourceOutput sourceOutput)986 inline std::string PrintSourceOutput(SourceOutput sourceOutput)
987 {
988 std::stringstream value;
989 value << "streamId:[" << sourceOutput.streamId << "] ";
990 value << "streamType:[" << sourceOutput.streamType << "] ";
991 value << "uid:[" << sourceOutput.uid << "] ";
992 value << "pid:[" << sourceOutput.pid << "] ";
993 value << "statusMark:[" << sourceOutput.statusMark << "] ";
994 value << "deviceSourceId:[" << sourceOutput.deviceSourceId << "] ";
995 value << "startTime:[" << sourceOutput.startTime << "]";
996 return value.str();
997 }
998
GetRemoteModuleName(std::string networkId,DeviceRole role)999 inline std::string GetRemoteModuleName(std::string networkId, DeviceRole role)
1000 {
1001 return networkId + (role == DeviceRole::OUTPUT_DEVICE ? "_out" : "_in");
1002 }
1003
GetSelectedDeviceInfo(int32_t uid,int32_t pid,AudioStreamType streamType)1004 std::string AudioPolicyService::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType)
1005 {
1006 (void)streamType;
1007
1008 std::lock_guard<std::mutex> lock(routerMapMutex_);
1009 if (!routerMap_.count(uid)) {
1010 AUDIO_INFO_LOG("GetSelectedDeviceInfo no such uid[%{public}d]", uid);
1011 return "";
1012 }
1013 std::string selectedDevice = "";
1014 if (routerMap_[uid].second == pid) {
1015 selectedDevice = routerMap_[uid].first;
1016 } else if (routerMap_[uid].second == G_UNKNOWN_PID) {
1017 routerMap_[uid].second = pid;
1018 selectedDevice = routerMap_[uid].first;
1019 } else {
1020 AUDIO_INFO_LOG("GetSelectedDeviceInfo: uid[%{public}d] changed pid, get local as defalut", uid);
1021 routerMap_.erase(uid);
1022 selectedDevice = LOCAL_NETWORK_ID;
1023 }
1024
1025 if (LOCAL_NETWORK_ID == selectedDevice) {
1026 AUDIO_INFO_LOG("GetSelectedDeviceInfo: uid[%{public}d]-->local.", uid);
1027 return "";
1028 }
1029 // check if connected.
1030 bool isConnected = false;
1031 for (auto device : connectedDevices_) {
1032 if (GetRemoteModuleName(device->networkId_, device->deviceRole_) == selectedDevice) {
1033 isConnected = true;
1034 break;
1035 }
1036 }
1037
1038 if (isConnected) {
1039 AUDIO_INFO_LOG("GetSelectedDeviceInfo result[%{public}s]", selectedDevice.c_str());
1040 return selectedDevice;
1041 } else {
1042 routerMap_.erase(uid);
1043 AUDIO_INFO_LOG("GetSelectedDeviceInfo device already disconnected.");
1044 return "";
1045 }
1046 }
1047
NotifyRemoteRenderState(std::string networkId,std::string condition,std::string value)1048 void AudioPolicyService::NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value)
1049 {
1050 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
1051
1052 AUDIO_INFO_LOG("device<%{public}s> condition:%{public}s value:%{public}s",
1053 GetEncryptStr(networkId).c_str(), condition.c_str(), value.c_str());
1054
1055 vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
1056 vector<SinkInput> targetSinkInputs = {};
1057 for (auto sinkInput : sinkInputs) {
1058 if (sinkInput.sinkName == networkId) {
1059 targetSinkInputs.push_back(sinkInput);
1060 }
1061 }
1062 AUDIO_DEBUG_LOG("move [%{public}zu] of all [%{public}zu]sink-inputs to local.",
1063 targetSinkInputs.size(), sinkInputs.size());
1064 sptr<AudioDeviceDescriptor> localDevice = new(std::nothrow) AudioDeviceDescriptor();
1065 CHECK_AND_RETURN_LOG(localDevice != nullptr, "Device error: null device.");
1066 localDevice->networkId_ = LOCAL_NETWORK_ID;
1067 localDevice->deviceRole_ = DeviceRole::OUTPUT_DEVICE;
1068 localDevice->deviceType_ = DeviceType::DEVICE_TYPE_SPEAKER;
1069
1070 int32_t ret;
1071 AudioDeviceDescriptor curOutputDeviceDesc = GetCurrentOutputDevice();
1072 if (localDevice->deviceType_ != curOutputDeviceDesc.deviceType_) {
1073 AUDIO_WARNING_LOG("device[%{public}d] not active, use device[%{public}d] instead.",
1074 static_cast<int32_t>(localDevice->deviceType_), static_cast<int32_t>(curOutputDeviceDesc.deviceType_));
1075 ret = MoveToLocalOutputDevice(targetSinkInputs, new AudioDeviceDescriptor(curOutputDeviceDesc));
1076 } else {
1077 ret = MoveToLocalOutputDevice(targetSinkInputs, localDevice);
1078 }
1079 CHECK_AND_RETURN_LOG((ret == SUCCESS), "MoveToLocalOutputDevice failed!");
1080
1081 // Suspend device, notify audio stream manager that device has been changed.
1082 ret = audioPolicyManager_.SuspendAudioDevice(networkId, true);
1083 CHECK_AND_RETURN_LOG((ret == SUCCESS), "SuspendAudioDevice failed!");
1084
1085 std::vector<sptr<AudioDeviceDescriptor>> desc = {};
1086 desc.push_back(localDevice);
1087 UpdateTrackerDeviceChange(desc);
1088 OnPreferredOutputDeviceUpdated(curOutputDeviceDesc);
1089 AUDIO_DEBUG_LOG("NotifyRemoteRenderState success");
1090 }
1091
IsArmUsbDevice(const AudioDeviceDescriptor & desc)1092 bool AudioPolicyService::IsArmUsbDevice(const AudioDeviceDescriptor &desc)
1093 {
1094 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
1095
1096 return audioDeviceManager_.IsArmUsbDevice(desc);
1097 }
1098
IsDeviceConnected(sptr<AudioDeviceDescriptor> & audioDeviceDescriptors) const1099 bool AudioPolicyService::IsDeviceConnected(sptr<AudioDeviceDescriptor> &audioDeviceDescriptors) const
1100 {
1101 return audioDeviceManager_.IsDeviceConnected(audioDeviceDescriptors);
1102 }
1103
DeviceParamsCheck(DeviceRole targetRole,std::vector<sptr<AudioDeviceDescriptor>> & audioDeviceDescriptors) const1104 int32_t AudioPolicyService::DeviceParamsCheck(DeviceRole targetRole,
1105 std::vector<sptr<AudioDeviceDescriptor>> &audioDeviceDescriptors) const
1106 {
1107 size_t targetSize = audioDeviceDescriptors.size();
1108 CHECK_AND_RETURN_RET_LOG(targetSize == 1, ERR_INVALID_OPERATION,
1109 "Device error: size[%{public}zu]", targetSize);
1110
1111 bool isDeviceTypeCorrect = false;
1112 if (targetRole == DeviceRole::OUTPUT_DEVICE) {
1113 isDeviceTypeCorrect = IsOutputDevice(audioDeviceDescriptors[0]->deviceType_) &&
1114 IsDeviceConnected(audioDeviceDescriptors[0]);
1115 } else if (targetRole == DeviceRole::INPUT_DEVICE) {
1116 isDeviceTypeCorrect = IsInputDevice(audioDeviceDescriptors[0]->deviceType_) &&
1117 IsDeviceConnected(audioDeviceDescriptors[0]);
1118 }
1119
1120 CHECK_AND_RETURN_RET_LOG(audioDeviceDescriptors[0]->deviceRole_ == targetRole && isDeviceTypeCorrect,
1121 ERR_INVALID_OPERATION, "Device error: size[%{public}zu] deviceRole[%{public}d] isDeviceCorrect[%{public}d]",
1122 targetSize, static_cast<int32_t>(audioDeviceDescriptors[0]->deviceRole_), isDeviceTypeCorrect);
1123 return SUCCESS;
1124 }
1125
NotifyUserSelectionEventToBt(sptr<AudioDeviceDescriptor> audioDeviceDescriptor)1126 void AudioPolicyService::NotifyUserSelectionEventToBt(sptr<AudioDeviceDescriptor> audioDeviceDescriptor)
1127 {
1128 Trace trace("AudioPolicyService::NotifyUserSelectionEventToBt");
1129 if (audioDeviceDescriptor == nullptr) {
1130 return;
1131 }
1132 #ifdef BLUETOOTH_ENABLE
1133 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
1134 if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_SCO ||
1135 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1136 Bluetooth::SendUserSelectionEvent(curOutputDeviceType,
1137 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT);
1138 if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
1139 Bluetooth::AudioHfpManager::DisconnectSco();
1140 }
1141 }
1142 if (audioDeviceDescriptor->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO ||
1143 audioDeviceDescriptor->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
1144 Bluetooth::SendUserSelectionEvent(audioDeviceDescriptor->deviceType_,
1145 audioDeviceDescriptor->macAddress_, USER_SELECT_BT);
1146 }
1147 #endif
1148 }
1149
SetRenderDeviceForUsage(StreamUsage streamUsage,sptr<AudioDeviceDescriptor> desc)1150 int32_t AudioPolicyService::SetRenderDeviceForUsage(StreamUsage streamUsage, sptr<AudioDeviceDescriptor> desc)
1151 {
1152 auto isPresent = [&desc] (const unique_ptr<AudioDeviceDescriptor> &device) {
1153 return (desc->deviceType_ == device->deviceType_) &&
1154 (desc->macAddress_ == device->macAddress_) &&
1155 (desc->networkId_ == device->networkId_);
1156 };
1157 int32_t tempId = desc->deviceId_;
1158 if (streamUsage == STREAM_USAGE_VOICE_COMMUNICATION || streamUsage == STREAM_USAGE_VOICE_MODEM_COMMUNICATION ||
1159 streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) {
1160 std::vector<unique_ptr<AudioDeviceDescriptor>> devices = GetAvailableDevicesInner(CALL_OUTPUT_DEVICES);
1161 auto itr = std::find_if(devices.begin(), devices.end(), isPresent);
1162 CHECK_AND_RETURN_RET_LOG(itr != devices.end(), ERR_INVALID_OPERATION,
1163 "device not available type:%{public}d macAddress:%{public}s id:%{public}d networkId:%{public}s",
1164 desc->deviceType_, GetEncryptAddr(desc->macAddress_).c_str(),
1165 tempId, GetEncryptStr(desc->networkId_).c_str());
1166 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor(**itr));
1167 return SUCCESS;
1168 } else {
1169 std::vector<unique_ptr<AudioDeviceDescriptor>> devices = GetAvailableDevicesInner(MEDIA_OUTPUT_DEVICES);
1170 auto itr = std::find_if(devices.begin(), devices.end(), isPresent);
1171 CHECK_AND_RETURN_RET_LOG(itr != devices.end(), ERR_INVALID_OPERATION,
1172 "device not available type:%{public}d macAddress:%{public}s id:%{public}d networkId:%{public}s",
1173 desc->deviceType_, GetEncryptAddr(desc->macAddress_).c_str(),
1174 tempId, GetEncryptStr(desc->networkId_).c_str());
1175 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor(**itr));
1176 return SUCCESS;
1177 }
1178 }
1179
ConnectVirtualDevice(sptr<AudioDeviceDescriptor> & selectedDesc)1180 int32_t AudioPolicyService::ConnectVirtualDevice(sptr<AudioDeviceDescriptor> &selectedDesc)
1181 {
1182 int32_t ret = Bluetooth::AudioA2dpManager::Connect(selectedDesc->macAddress_);
1183 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "A2dp connect failed");
1184 ret = Bluetooth::AudioHfpManager::Connect(selectedDesc->macAddress_);
1185 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Hfp connect failed");
1186 AUDIO_INFO_LOG("Connect virtual device[%{public}s]", GetEncryptAddr(selectedDesc->macAddress_).c_str());
1187 return SUCCESS;
1188 }
1189
SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<sptr<AudioDeviceDescriptor>> selectedDesc)1190 int32_t AudioPolicyService::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
1191 std::vector<sptr<AudioDeviceDescriptor>> selectedDesc)
1192 {
1193 Trace trace("AudioPolicyService::SelectOutputDevice");
1194 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
1195
1196 AUDIO_WARNING_LOG("uid[%{public}d] type[%{public}d] mac[%{public}s] streamUsage[%{public}d] pid[%{public}d]",
1197 audioRendererFilter->uid, selectedDesc[0]->deviceType_, GetEncryptAddr(selectedDesc[0]->macAddress_).c_str(),
1198 audioRendererFilter->rendererInfo.streamUsage, IPCSkeleton::GetCallingPid());
1199
1200 CHECK_AND_RETURN_RET_LOG((selectedDesc[0]->deviceRole_ == DeviceRole::OUTPUT_DEVICE) &&
1201 (selectedDesc.size() == 1), ERR_INVALID_OPERATION, "DeviceCheck no success");
1202 if (audioRendererFilter->rendererInfo.rendererFlags == STREAM_FLAG_FAST) {
1203 int32_t res = SetRenderDeviceForUsage(audioRendererFilter->rendererInfo.streamUsage, selectedDesc[0]);
1204 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, res, "SetRenderDeviceForUsage fail");
1205 SelectFastOutputDevice(audioRendererFilter, selectedDesc[0]);
1206 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
1207 return SUCCESS;
1208 }
1209 bool isVirtualDevice = false;
1210 if (selectedDesc[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP ||
1211 selectedDesc[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
1212 selectedDesc[0]->isEnable_ = true;
1213 audioDeviceManager_.UpdateDevicesListInfo(selectedDesc[0], ENABLE_UPDATE);
1214 isVirtualDevice = audioDeviceManager_.IsVirtualConnectedDevice(selectedDesc[0]);
1215 if (isVirtualDevice == true) {
1216 selectedDesc[0]->connectState_ = VIRTUAL_CONNECTED;
1217 }
1218 }
1219 if (selectedDesc[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
1220 ClearScoDeviceSuspendState(selectedDesc[0]->macAddress_);
1221 }
1222 StreamUsage strUsage = audioRendererFilter->rendererInfo.streamUsage;
1223 int32_t res = SetRenderDeviceForUsage(strUsage, selectedDesc[0]);
1224 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, res, "SetRenderDeviceForUsage fail");
1225
1226 // If the selected device is virtual device, connect it.
1227 if (isVirtualDevice) {
1228 int32_t ret = ConnectVirtualDevice(selectedDesc[0]);
1229 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Connect device [%{public}s] failed",
1230 GetEncryptStr(selectedDesc[0]->macAddress_).c_str());
1231 return SUCCESS;
1232 }
1233
1234 NotifyUserSelectionEventToBt(selectedDesc[0]);
1235 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
1236 FetchDevice(false);
1237 if ((selectedDesc[0]->deviceType_ != DEVICE_TYPE_BLUETOOTH_A2DP) ||
1238 (selectedDesc[0]->networkId_ != LOCAL_NETWORK_ID)) {
1239 UpdateOffloadWhenActiveDeviceSwitchFromA2dp();
1240 } else {
1241 UpdateA2dpOffloadFlagForAllStream(selectedDesc[0]->deviceType_);
1242 }
1243 OnPreferredOutputDeviceUpdated(GetCurrentOutputDevice());
1244 WriteSelectOutputSysEvents(selectedDesc, strUsage);
1245 return SUCCESS;
1246 }
1247
WriteSelectOutputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> & selectedDesc,StreamUsage strUsage)1248 void AudioPolicyService::WriteSelectOutputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &selectedDesc,
1249 StreamUsage strUsage)
1250 {
1251 auto uid = IPCSkeleton::GetCallingUid();
1252 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
1253 Media::MediaMonitor::AUDIO, Media::MediaMonitor::SET_FORCE_USE_AUDIO_DEVICE,
1254 Media::MediaMonitor::BEHAVIOR_EVENT);
1255 AudioDeviceDescriptor curOutputDeviceDesc = GetCurrentOutputDevice();
1256 bean->Add("CLIENT_UID", static_cast<int32_t>(uid));
1257 bean->Add("DEVICE_TYPE", curOutputDeviceDesc.deviceType_);
1258 bean->Add("STREAM_TYPE", strUsage);
1259 bean->Add("BT_TYPE", curOutputDeviceDesc.deviceCategory_);
1260 bean->Add("DEVICE_NAME", curOutputDeviceDesc.deviceName_);
1261 bean->Add("ADDRESS", curOutputDeviceDesc.macAddress_);
1262 bean->Add("IS_PLAYBACK", 1);
1263 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
1264 }
1265
SelectFastOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,sptr<AudioDeviceDescriptor> deviceDescriptor)1266 int32_t AudioPolicyService::SelectFastOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
1267 sptr<AudioDeviceDescriptor> deviceDescriptor)
1268 {
1269 AUDIO_INFO_LOG("Start for uid[%{public}d] device[%{public}s]", audioRendererFilter->uid,
1270 GetEncryptStr(deviceDescriptor->networkId_).c_str());
1271 // note: check if stream is already running
1272 // if is running, call moveProcessToEndpoint.
1273
1274 // otherwises, keep router info in the map
1275 std::lock_guard<std::mutex> lock(routerMapMutex_);
1276 fastRouterMap_[audioRendererFilter->uid] = std::make_pair(deviceDescriptor->networkId_, OUTPUT_DEVICE);
1277 return SUCCESS;
1278 }
1279
FilterSinkInputs(int32_t sessionId)1280 std::vector<SinkInput> AudioPolicyService::FilterSinkInputs(int32_t sessionId)
1281 {
1282 // find sink-input id with audioRendererFilter
1283 std::vector<SinkInput> targetSinkInputs = {};
1284 std::vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
1285
1286 for (size_t i = 0; i < sinkInputs.size(); i++) {
1287 CHECK_AND_CONTINUE_LOG(sinkInputs[i].uid != dAudioClientUid,
1288 "Find sink-input with daudio[%{public}d]", sinkInputs[i].pid);
1289 CHECK_AND_CONTINUE_LOG(sinkInputs[i].streamType != STREAM_DEFAULT,
1290 "Sink-input[%{public}zu] of effect sink, don't move", i);
1291 AUDIO_DEBUG_LOG("sinkinput[%{public}zu]:%{public}s", i, PrintSinkInput(sinkInputs[i]).c_str());
1292 if (sessionId == sinkInputs[i].streamId) {
1293 targetSinkInputs.push_back(sinkInputs[i]);
1294 }
1295 }
1296 return targetSinkInputs;
1297 }
1298
FilterSourceOutputs(int32_t sessionId)1299 std::vector<SourceOutput> AudioPolicyService::FilterSourceOutputs(int32_t sessionId)
1300 {
1301 std::vector<SourceOutput> targetSourceOutputs = {};
1302 std::vector<SourceOutput> sourceOutputs;
1303 {
1304 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
1305 if (std::any_of(IOHandles_.cbegin(), IOHandles_.cend(), [](const auto &pair) {
1306 return std::find(SourceNames.cbegin(), SourceNames.cend(), pair.first) != SourceNames.cend();
1307 })) {
1308 sourceOutputs = audioPolicyManager_.GetAllSourceOutputs();
1309 }
1310 }
1311
1312 for (size_t i = 0; i < sourceOutputs.size(); i++) {
1313 AUDIO_DEBUG_LOG("sourceOutput[%{public}zu]:%{public}s", i, PrintSourceOutput(sourceOutputs[i]).c_str());
1314 if (sessionId == sourceOutputs[i].streamId) {
1315 targetSourceOutputs.push_back(sourceOutputs[i]);
1316 }
1317 }
1318 return targetSourceOutputs;
1319 }
1320
FilterSinkInputs(sptr<AudioRendererFilter> audioRendererFilter,bool moveAll)1321 std::vector<SinkInput> AudioPolicyService::FilterSinkInputs(sptr<AudioRendererFilter> audioRendererFilter,
1322 bool moveAll)
1323 {
1324 int32_t targetUid = audioRendererFilter->uid;
1325 AudioStreamType targetStreamType = audioRendererFilter->streamType;
1326 // find sink-input id with audioRendererFilter
1327 std::vector<SinkInput> targetSinkInputs = {};
1328 std::vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
1329
1330 for (size_t i = 0; i < sinkInputs.size(); i++) {
1331 CHECK_AND_CONTINUE_LOG(sinkInputs[i].uid != dAudioClientUid,
1332 "Find sink-input with daudio[%{public}d]", sinkInputs[i].pid);
1333 CHECK_AND_CONTINUE_LOG(sinkInputs[i].streamType != STREAM_DEFAULT,
1334 "Sink-input[%{public}zu] of effect sink, don't move", i);
1335 AUDIO_DEBUG_LOG("sinkinput[%{public}zu]:%{public}s", i, PrintSinkInput(sinkInputs[i]).c_str());
1336 if (moveAll || (targetUid == sinkInputs[i].uid && targetStreamType == sinkInputs[i].streamType)) {
1337 targetSinkInputs.push_back(sinkInputs[i]);
1338 }
1339 }
1340 return targetSinkInputs;
1341 }
1342
RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter,sptr<AudioDeviceDescriptor> deviceDescriptor)1343 int32_t AudioPolicyService::RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter,
1344 sptr<AudioDeviceDescriptor> deviceDescriptor)
1345 {
1346 AUDIO_INFO_LOG("Start for uid[%{public}d] device[%{public}s]", audioRendererFilter->uid,
1347 GetEncryptStr(deviceDescriptor->networkId_).c_str());
1348 if (deviceDescriptor->networkId_ == LOCAL_NETWORK_ID) {
1349 std::lock_guard<std::mutex> lock(routerMapMutex_);
1350 routerMap_[audioRendererFilter->uid] = std::pair(LOCAL_NETWORK_ID, G_UNKNOWN_PID);
1351 return SUCCESS;
1352 }
1353 // remote device.
1354 std::string networkId = deviceDescriptor->networkId_;
1355 DeviceRole deviceRole = deviceDescriptor->deviceRole_;
1356
1357 std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
1358 CHECK_AND_RETURN_RET_LOG(IOHandles_.count(moduleName), ERR_INVALID_PARAM,
1359 "Device error: no such device:%{public}s", networkId.c_str());
1360 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
1361 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
1362 std::string identity = IPCSkeleton::ResetCallingIdentity();
1363 int32_t ret = gsp->CheckRemoteDeviceState(networkId, deviceRole, true);
1364 IPCSkeleton::SetCallingIdentity(identity);
1365 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!");
1366
1367 std::lock_guard<std::mutex> lock(routerMapMutex_);
1368 routerMap_[audioRendererFilter->uid] = std::pair(moduleName, G_UNKNOWN_PID);
1369 return SUCCESS;
1370 }
1371
MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,sptr<AudioDeviceDescriptor> localDeviceDescriptor)1372 int32_t AudioPolicyService::MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,
1373 sptr<AudioDeviceDescriptor> localDeviceDescriptor)
1374 {
1375 AUDIO_INFO_LOG("MoveToLocalOutputDevice for [%{public}zu] sink-inputs", sinkInputIds.size());
1376 // check
1377 CHECK_AND_RETURN_RET_LOG(LOCAL_NETWORK_ID == localDeviceDescriptor->networkId_,
1378 ERR_INVALID_OPERATION, "MoveToLocalOutputDevice failed: not a local device.");
1379
1380 // start move.
1381 uint32_t sinkId = -1; // invalid sink id, use sink name instead.
1382 for (size_t i = 0; i < sinkInputIds.size(); i++) {
1383 AudioPipeType pipeType = PIPE_TYPE_UNKNOWN;
1384 streamCollector_.GetPipeType(sinkInputIds[i].streamId, pipeType);
1385 std::string sinkName = GetSinkPortName(localDeviceDescriptor->deviceType_, pipeType);
1386 if (sinkName == BLUETOOTH_SPEAKER) {
1387 std::string activePort = BLUETOOTH_SPEAKER;
1388 audioPolicyManager_.SuspendAudioDevice(activePort, false);
1389 }
1390 AUDIO_INFO_LOG("move for session [%{public}d], portName %{public}s pipeType %{public}d",
1391 sinkInputIds[i].streamId, sinkName.c_str(), pipeType);
1392 int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, sinkName);
1393 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR,
1394 "move [%{public}d] to local failed", sinkInputIds[i].streamId);
1395 std::lock_guard<std::mutex> lock(routerMapMutex_);
1396 routerMap_[sinkInputIds[i].uid] = std::pair(LOCAL_NETWORK_ID, sinkInputIds[i].pid);
1397 }
1398
1399 isCurrentRemoteRenderer = false;
1400 return SUCCESS;
1401 }
1402
OpenRemoteAudioDevice(std::string networkId,DeviceRole deviceRole,DeviceType deviceType,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)1403 int32_t AudioPolicyService::OpenRemoteAudioDevice(std::string networkId, DeviceRole deviceRole, DeviceType deviceType,
1404 sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
1405 {
1406 // open the test device. We should open it when device is online.
1407 std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
1408 AudioModuleInfo remoteDeviceInfo = ConstructRemoteAudioModuleInfo(networkId, deviceRole, deviceType);
1409 OpenPortAndInsertIOHandle(moduleName, remoteDeviceInfo);
1410
1411 // If device already in list, remove it else do not modify the list.
1412 auto isPresent = [&deviceType, &networkId] (const sptr<AudioDeviceDescriptor> &descriptor) {
1413 return descriptor->deviceType_ == deviceType && descriptor->networkId_ == networkId;
1414 };
1415
1416 connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent),
1417 connectedDevices_.end());
1418 UpdateDisplayName(remoteDeviceDescriptor);
1419 connectedDevices_.insert(connectedDevices_.begin(), remoteDeviceDescriptor);
1420 AddMicrophoneDescriptor(remoteDeviceDescriptor);
1421 return SUCCESS;
1422 }
1423
MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)1424 int32_t AudioPolicyService::MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,
1425 sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
1426 {
1427 AUDIO_INFO_LOG("MoveToRemoteOutputDevice for [%{public}zu] sink-inputs", sinkInputIds.size());
1428
1429 std::string networkId = remoteDeviceDescriptor->networkId_;
1430 DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_;
1431 DeviceType deviceType = remoteDeviceDescriptor->deviceType_;
1432
1433 // check: networkid
1434 CHECK_AND_RETURN_RET_LOG(networkId != LOCAL_NETWORK_ID, ERR_INVALID_OPERATION,
1435 "MoveToRemoteOutputDevice failed: not a remote device.");
1436
1437 uint32_t sinkId = -1; // invalid sink id, use sink name instead.
1438 std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
1439 if (IOHandles_.count(moduleName)) {
1440 IOHandles_[moduleName]; // mIOHandle is module id, not equal to sink id.
1441 } else {
1442 AUDIO_ERR_LOG("no such device.");
1443 if (!isOpenRemoteDevice) {
1444 return ERR_INVALID_PARAM;
1445 } else {
1446 return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor);
1447 }
1448 }
1449
1450 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
1451 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
1452 std::string identity = IPCSkeleton::ResetCallingIdentity();
1453 int32_t res = gsp->CheckRemoteDeviceState(networkId, deviceRole, true);
1454 IPCSkeleton::SetCallingIdentity(identity);
1455 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!");
1456
1457 // start move.
1458 for (size_t i = 0; i < sinkInputIds.size(); i++) {
1459 int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, moduleName);
1460 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "move [%{public}d] failed", sinkInputIds[i].streamId);
1461 std::lock_guard<std::mutex> lock(routerMapMutex_);
1462 routerMap_[sinkInputIds[i].uid] = std::pair(moduleName, sinkInputIds[i].pid);
1463 }
1464
1465 if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) {
1466 AUDIO_WARNING_LOG("Not defult type[%{public}d] on device:[%{public}s]",
1467 deviceType, GetEncryptStr(networkId).c_str());
1468 }
1469 isCurrentRemoteRenderer = true;
1470 return SUCCESS;
1471 }
1472
SelectFastInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,sptr<AudioDeviceDescriptor> deviceDescriptor)1473 int32_t AudioPolicyService::SelectFastInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
1474 sptr<AudioDeviceDescriptor> deviceDescriptor)
1475 {
1476 // note: check if stream is already running
1477 // if is running, call moveProcessToEndpoint.
1478
1479 // otherwises, keep router info in the map
1480 std::lock_guard<std::mutex> lock(routerMapMutex_);
1481 fastRouterMap_[audioCapturerFilter->uid] = std::make_pair(deviceDescriptor->networkId_, INPUT_DEVICE);
1482 AUDIO_INFO_LOG("Success for uid[%{public}d] device[%{public}s]", audioCapturerFilter->uid,
1483 GetEncryptStr(deviceDescriptor->networkId_).c_str());
1484 return SUCCESS;
1485 }
1486
SetCaptureDeviceForUsage(AudioScene scene,SourceType srcType,sptr<AudioDeviceDescriptor> desc)1487 void AudioPolicyService::SetCaptureDeviceForUsage(AudioScene scene, SourceType srcType,
1488 sptr<AudioDeviceDescriptor> desc)
1489 {
1490 AUDIO_INFO_LOG("Scene: %{public}d, srcType: %{public}d", scene, srcType);
1491 if (scene == AUDIO_SCENE_PHONE_CALL || scene == AUDIO_SCENE_PHONE_CHAT ||
1492 srcType == SOURCE_TYPE_VOICE_COMMUNICATION) {
1493 SetPreferredDevice(AUDIO_CALL_CAPTURE, desc);
1494 } else {
1495 SetPreferredDevice(AUDIO_RECORD_CAPTURE, desc);
1496 }
1497 }
1498
SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<sptr<AudioDeviceDescriptor>> selectedDesc)1499 int32_t AudioPolicyService::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
1500 std::vector<sptr<AudioDeviceDescriptor>> selectedDesc)
1501 {
1502 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
1503
1504 AUDIO_WARNING_LOG("uid[%{public}d] type[%{public}d] mac[%{public}s] pid[%{public}d]",
1505 audioCapturerFilter->uid, selectedDesc[0]->deviceType_,
1506 GetEncryptAddr(selectedDesc[0]->macAddress_).c_str(), IPCSkeleton::GetCallingPid());
1507 // check size == 1 && input device
1508 int32_t res = DeviceParamsCheck(DeviceRole::INPUT_DEVICE, selectedDesc);
1509 CHECK_AND_RETURN_RET(res == SUCCESS, res);
1510
1511 SourceType srcType = audioCapturerFilter->capturerInfo.sourceType;
1512
1513 if (audioCapturerFilter->capturerInfo.capturerFlags == STREAM_FLAG_FAST && selectedDesc.size() == 1) {
1514 SetCaptureDeviceForUsage(GetAudioScene(true), srcType, selectedDesc[0]);
1515 SelectFastInputDevice(audioCapturerFilter, selectedDesc[0]);
1516 FetchDevice(false);
1517 return SUCCESS;
1518 }
1519
1520 AudioScene scene = GetAudioScene(true);
1521 if (scene == AUDIO_SCENE_PHONE_CALL || scene == AUDIO_SCENE_PHONE_CHAT ||
1522 srcType == SOURCE_TYPE_VOICE_COMMUNICATION) {
1523 SetPreferredDevice(AUDIO_CALL_CAPTURE, selectedDesc[0]);
1524 } else {
1525 SetPreferredDevice(AUDIO_RECORD_CAPTURE, selectedDesc[0]);
1526 }
1527 FetchDevice(false);
1528
1529 WriteSelectInputSysEvents(selectedDesc, srcType, scene);
1530
1531 return SUCCESS;
1532 }
1533
WriteSelectInputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> & selectedDesc,SourceType srcType,AudioScene scene)1534 void AudioPolicyService::WriteSelectInputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &selectedDesc,
1535 SourceType srcType, AudioScene scene)
1536 {
1537 auto uid = IPCSkeleton::GetCallingUid();
1538 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
1539 Media::MediaMonitor::AUDIO, Media::MediaMonitor::SET_FORCE_USE_AUDIO_DEVICE,
1540 Media::MediaMonitor::BEHAVIOR_EVENT);
1541 bean->Add("CLIENT_UID", static_cast<int32_t>(uid));
1542 bean->Add("DEVICE_TYPE", selectedDesc[0]->deviceType_);
1543 bean->Add("STREAM_TYPE", srcType);
1544 bean->Add("BT_TYPE", selectedDesc[0]->deviceCategory_);
1545 bean->Add("DEVICE_NAME", selectedDesc[0]->deviceName_);
1546 bean->Add("ADDRESS", selectedDesc[0]->macAddress_);
1547 bean->Add("AUDIO_SCENE", scene);
1548 bean->Add("IS_PLAYBACK", 0);
1549 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
1550 }
1551
MoveToLocalInputDevice(std::vector<SourceOutput> sourceOutputs,sptr<AudioDeviceDescriptor> localDeviceDescriptor)1552 int32_t AudioPolicyService::MoveToLocalInputDevice(std::vector<SourceOutput> sourceOutputs,
1553 sptr<AudioDeviceDescriptor> localDeviceDescriptor)
1554 {
1555 AUDIO_DEBUG_LOG("MoveToLocalInputDevice start");
1556 // check
1557 CHECK_AND_RETURN_RET_LOG(LOCAL_NETWORK_ID == localDeviceDescriptor->networkId_, ERR_INVALID_OPERATION,
1558 "MoveToLocalInputDevice failed: not a local device.");
1559 // start move.
1560 uint32_t sourceId = -1; // invalid source id, use source name instead.
1561 std::string sourceName = GetSourcePortName(localDeviceDescriptor->deviceType_);
1562 for (size_t i = 0; i < sourceOutputs.size(); i++) {
1563 int32_t ret = audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputs[i].paStreamId,
1564 sourceId, sourceName);
1565 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR,
1566 "move [%{public}d] to local failed", sourceOutputs[i].paStreamId);
1567 }
1568
1569 return SUCCESS;
1570 }
1571
MoveToRemoteInputDevice(std::vector<SourceOutput> sourceOutputs,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)1572 int32_t AudioPolicyService::MoveToRemoteInputDevice(std::vector<SourceOutput> sourceOutputs,
1573 sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
1574 {
1575 AUDIO_INFO_LOG("MoveToRemoteInputDevice start");
1576
1577 std::string networkId = remoteDeviceDescriptor->networkId_;
1578 DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_;
1579 DeviceType deviceType = remoteDeviceDescriptor->deviceType_;
1580
1581 // check: networkid
1582 CHECK_AND_RETURN_RET_LOG(networkId != LOCAL_NETWORK_ID, ERR_INVALID_OPERATION,
1583 "MoveToRemoteInputDevice failed: not a remote device.");
1584
1585 uint32_t sourceId = -1; // invalid sink id, use sink name instead.
1586 std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
1587
1588 std::unique_lock<std::mutex> ioHandleLock(ioHandlesMutex_);
1589 if (IOHandles_.count(moduleName)) {
1590 IOHandles_[moduleName]; // mIOHandle is module id, not equal to sink id.
1591 ioHandleLock.unlock();
1592 } else {
1593 ioHandleLock.unlock();
1594 AUDIO_ERR_LOG("no such device.");
1595 if (!isOpenRemoteDevice) {
1596 return ERR_INVALID_PARAM;
1597 } else {
1598 return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor);
1599 }
1600 }
1601
1602 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
1603 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
1604 std::string identity = IPCSkeleton::ResetCallingIdentity();
1605 int32_t res = gsp->CheckRemoteDeviceState(networkId, deviceRole, true);
1606 IPCSkeleton::SetCallingIdentity(identity);
1607 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!");
1608
1609 // start move.
1610 for (size_t i = 0; i < sourceOutputs.size(); i++) {
1611 int32_t ret = audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputs[i].paStreamId,
1612 sourceId, moduleName);
1613 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR,
1614 "move [%{public}d] failed", sourceOutputs[i].paStreamId);
1615 }
1616
1617 if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) {
1618 AUDIO_DEBUG_LOG("Not defult type[%{public}d] on device:[%{public}s]",
1619 deviceType, GetEncryptStr(networkId).c_str());
1620 }
1621 return SUCCESS;
1622 }
1623
IsStreamActive(AudioStreamType streamType) const1624 bool AudioPolicyService::IsStreamActive(AudioStreamType streamType) const
1625 {
1626 CHECK_AND_RETURN_RET(streamType != STREAM_VOICE_CALL || audioScene_ != AUDIO_SCENE_PHONE_CALL, true);
1627
1628 return streamCollector_.IsStreamActive(streamType);
1629 }
1630
ConfigDistributedRoutingRole(const sptr<AudioDeviceDescriptor> descriptor,CastType type)1631 void AudioPolicyService::ConfigDistributedRoutingRole(const sptr<AudioDeviceDescriptor> descriptor, CastType type)
1632 {
1633 sptr<AudioDeviceDescriptor> intermediateDescriptor = new AudioDeviceDescriptor(descriptor);
1634 StoreDistributedRoutingRoleInfo(intermediateDescriptor, type);
1635 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
1636 FetchDevice(false);
1637 }
1638
StoreDistributedRoutingRoleInfo(const sptr<AudioDeviceDescriptor> descriptor,CastType type)1639 void AudioPolicyService::StoreDistributedRoutingRoleInfo(const sptr<AudioDeviceDescriptor> descriptor, CastType type)
1640 {
1641 distributedRoutingInfo_.descriptor = descriptor;
1642 distributedRoutingInfo_.type = type;
1643 }
1644
GetDistributedRoutingRoleInfo()1645 DistributedRoutingInfo AudioPolicyService::GetDistributedRoutingRoleInfo()
1646 {
1647 return distributedRoutingInfo_;
1648 }
1649
GetSinkPortName(InternalDeviceType deviceType,AudioPipeType pipeType)1650 std::string AudioPolicyService::GetSinkPortName(InternalDeviceType deviceType, AudioPipeType pipeType)
1651 {
1652 std::string portName = PORT_NONE;
1653 switch (deviceType) {
1654 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
1655 // BTH tells us that a2dpoffload is OK
1656 if (a2dpOffloadFlag_ == A2DP_OFFLOAD) {
1657 portName = PRIMARY_SPEAKER;
1658 if (pipeType == PIPE_TYPE_OFFLOAD) {
1659 portName = OFFLOAD_PRIMARY_SPEAKER;
1660 } else if (pipeType == PIPE_TYPE_MULTICHANNEL) {
1661 portName = MCH_PRIMARY_SPEAKER;
1662 }
1663 } else {
1664 portName = BLUETOOTH_SPEAKER;
1665 }
1666 break;
1667 case InternalDeviceType::DEVICE_TYPE_EARPIECE:
1668 case InternalDeviceType::DEVICE_TYPE_SPEAKER:
1669 case InternalDeviceType::DEVICE_TYPE_WIRED_HEADSET:
1670 case InternalDeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
1671 case InternalDeviceType::DEVICE_TYPE_USB_HEADSET:
1672 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
1673 if (pipeType == PIPE_TYPE_OFFLOAD) {
1674 portName = OFFLOAD_PRIMARY_SPEAKER;
1675 } else if (pipeType == PIPE_TYPE_MULTICHANNEL) {
1676 portName = MCH_PRIMARY_SPEAKER;
1677 } else {
1678 portName = PRIMARY_SPEAKER;
1679 }
1680 break;
1681 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET:
1682 portName = USB_SPEAKER;
1683 break;
1684 case InternalDeviceType::DEVICE_TYPE_DP:
1685 portName = DP_SINK;
1686 break;
1687 case InternalDeviceType::DEVICE_TYPE_FILE_SINK:
1688 portName = FILE_SINK;
1689 break;
1690 case InternalDeviceType::DEVICE_TYPE_REMOTE_CAST:
1691 portName = REMOTE_CAST_INNER_CAPTURER_SINK_NAME;
1692 break;
1693 default:
1694 portName = PORT_NONE;
1695 break;
1696 }
1697
1698 return portName;
1699 }
1700
GetSourcePortName(InternalDeviceType deviceType)1701 std::string AudioPolicyService::GetSourcePortName(InternalDeviceType deviceType)
1702 {
1703 std::string portName = PORT_NONE;
1704 switch (deviceType) {
1705 case InternalDeviceType::DEVICE_TYPE_MIC:
1706 case InternalDeviceType::DEVICE_TYPE_USB_HEADSET:
1707 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
1708 portName = PRIMARY_MIC;
1709 break;
1710 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET:
1711 portName = USB_MIC;
1712 break;
1713 case InternalDeviceType::DEVICE_TYPE_WAKEUP:
1714 portName = PRIMARY_WAKEUP;
1715 break;
1716 case InternalDeviceType::DEVICE_TYPE_FILE_SOURCE:
1717 portName = FILE_SOURCE;
1718 break;
1719 default:
1720 portName = PORT_NONE;
1721 break;
1722 }
1723
1724 return portName;
1725 }
1726
1727 // private method
ConstructRemoteAudioModuleInfo(std::string networkId,DeviceRole deviceRole,DeviceType deviceType)1728 AudioModuleInfo AudioPolicyService::ConstructRemoteAudioModuleInfo(std::string networkId, DeviceRole deviceRole,
1729 DeviceType deviceType)
1730 {
1731 AudioModuleInfo audioModuleInfo = {};
1732 if (deviceRole == DeviceRole::OUTPUT_DEVICE) {
1733 audioModuleInfo.lib = "libmodule-hdi-sink.z.so";
1734 audioModuleInfo.format = "s16le"; // 16bit little endian
1735 audioModuleInfo.fixedLatency = "1"; // here we need to set latency fixed for a fixed buffer size.
1736 audioModuleInfo.renderInIdleState = "1";
1737 } else if (deviceRole == DeviceRole::INPUT_DEVICE) {
1738 audioModuleInfo.lib = "libmodule-hdi-source.z.so";
1739 audioModuleInfo.format = "s16le"; // we assume it is bigger endian
1740 } else {
1741 AUDIO_WARNING_LOG("Invalid flag provided %{public}d", static_cast<int32_t>(deviceType));
1742 }
1743
1744 // used as "sink_name" in hdi_sink.c, hope we could use name to find target sink.
1745 audioModuleInfo.name = GetRemoteModuleName(networkId, deviceRole);
1746 audioModuleInfo.networkId = networkId;
1747
1748 std::stringstream typeValue;
1749 typeValue << static_cast<int32_t>(deviceType);
1750 audioModuleInfo.deviceType = typeValue.str();
1751
1752 audioModuleInfo.adapterName = "remote";
1753 audioModuleInfo.className = "remote"; // used in renderer_sink_adapter.c
1754 audioModuleInfo.fileName = "remote_dump_file";
1755
1756 audioModuleInfo.channels = "2";
1757 audioModuleInfo.rate = "48000";
1758 audioModuleInfo.bufferSize = "3840";
1759
1760 return audioModuleInfo;
1761 }
1762
MoveToOutputDevice(uint32_t sessionId,std::string portName)1763 int32_t AudioPolicyService::MoveToOutputDevice(uint32_t sessionId, std::string portName)
1764 {
1765 std::vector<SinkInput> sinkInputIds = FilterSinkInputs(sessionId);
1766
1767 if (portName == BLUETOOTH_SPEAKER) {
1768 std::string activePort = BLUETOOTH_SPEAKER;
1769 audioPolicyManager_.SuspendAudioDevice(activePort, false);
1770 }
1771 AUDIO_INFO_LOG("move for session [%{public}d], portName %{public}s", sessionId, portName.c_str());
1772 // start move.
1773 uint32_t sinkId = -1; // invalid sink id, use sink name instead.
1774 for (size_t i = 0; i < sinkInputIds.size(); i++) {
1775 int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, portName);
1776 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR,
1777 "move [%{public}d] to local failed", sinkInputIds[i].streamId);
1778 std::lock_guard<std::mutex> lock(routerMapMutex_);
1779 routerMap_[sinkInputIds[i].uid] = std::pair(LOCAL_NETWORK_ID, sinkInputIds[i].pid);
1780 }
1781 return SUCCESS;
1782 }
1783
1784 // private method
FillWakeupStreamPropInfo(const AudioStreamInfo & streamInfo,PipeInfo * pipeInfo,AudioModuleInfo & audioModuleInfo)1785 bool AudioPolicyService::FillWakeupStreamPropInfo(const AudioStreamInfo &streamInfo, PipeInfo *pipeInfo,
1786 AudioModuleInfo &audioModuleInfo)
1787 {
1788 if (pipeInfo == nullptr) {
1789 AUDIO_ERR_LOG("wakeup pipe info is nullptr");
1790 return false;
1791 }
1792
1793 if (pipeInfo->streamPropInfos_.size() == 0) {
1794 AUDIO_ERR_LOG("no stream prop info");
1795 return false;
1796 }
1797
1798 auto targetIt = pipeInfo->streamPropInfos_.begin();
1799 for (auto it = pipeInfo->streamPropInfos_.begin(); it != pipeInfo->streamPropInfos_.end(); ++it) {
1800 if (it -> channelLayout_ == static_cast<uint32_t>(streamInfo.channels)) {
1801 AUDIO_INFO_LOG("find target pipe info");
1802 targetIt = it;
1803 break;
1804 }
1805 }
1806
1807 audioModuleInfo.format = targetIt->format_;
1808 audioModuleInfo.channels = std::to_string(targetIt->channelLayout_);
1809 audioModuleInfo.rate = std::to_string(targetIt->sampleRate_);
1810 audioModuleInfo.bufferSize = std::to_string(targetIt->bufferSize_);
1811
1812 AUDIO_INFO_LOG("stream prop info, format:%{public}s, channels:%{public}s, rate:%{public}s, buffer size:%{public}s",
1813 audioModuleInfo.format.c_str(), audioModuleInfo.channels.c_str(),
1814 audioModuleInfo.rate.c_str(), audioModuleInfo.bufferSize.c_str());
1815 return true;
1816 }
1817
ConstructWakeupAudioModuleInfo(const AudioStreamInfo & streamInfo,AudioModuleInfo & audioModuleInfo)1818 bool AudioPolicyService::ConstructWakeupAudioModuleInfo(const AudioStreamInfo &streamInfo,
1819 AudioModuleInfo &audioModuleInfo)
1820 {
1821 if (!isAdapterInfoMap_.load()) {
1822 return false;
1823 }
1824 auto it = adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[std::string(PRIMARY_WAKEUP)]));
1825 if (it == adapterInfoMap_.end()) {
1826 AUDIO_ERR_LOG("can not find adapter info");
1827 return false;
1828 }
1829
1830 auto pipeInfo = it->second.GetPipeByName(PIPE_WAKEUP_INPUT);
1831 if (pipeInfo == nullptr) {
1832 AUDIO_ERR_LOG("wakeup pipe info is nullptr");
1833 return false;
1834 }
1835
1836 if (!FillWakeupStreamPropInfo(streamInfo, pipeInfo, audioModuleInfo)) {
1837 AUDIO_ERR_LOG("failed to fill pipe stream prop info");
1838 return false;
1839 }
1840
1841 audioModuleInfo.adapterName = it->second.adapterName_;
1842 audioModuleInfo.name = pipeInfo->moduleName_;
1843 audioModuleInfo.lib = pipeInfo->lib_;
1844 audioModuleInfo.networkId = "LocalDevice";
1845 audioModuleInfo.className = "primary";
1846 audioModuleInfo.fileName = "";
1847 audioModuleInfo.OpenMicSpeaker = "1";
1848 audioModuleInfo.sourceType = std::to_string(SourceType::SOURCE_TYPE_WAKEUP);
1849
1850 AUDIO_INFO_LOG("wakeup auido module info, adapter name:%{public}s, name:%{public}s, lib:%{public}s",
1851 audioModuleInfo.adapterName.c_str(), audioModuleInfo.name.c_str(), audioModuleInfo.lib.c_str());
1852 return true;
1853 }
1854
OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor & deviceDescriptor)1855 void AudioPolicyService::OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor& deviceDescriptor)
1856 {
1857 Trace trace("AudioPolicyService::OnPreferredOutputDeviceUpdated:" + std::to_string(deviceDescriptor.deviceType_));
1858 AUDIO_INFO_LOG("OnPreferredOutputDeviceUpdated start");
1859
1860 if (audioPolicyServerHandler_ != nullptr) {
1861 audioPolicyServerHandler_->SendPreferredOutputDeviceUpdated();
1862 }
1863 spatialDeviceMap_.insert(make_pair(deviceDescriptor.macAddress_, deviceDescriptor.deviceType_));
1864
1865 if (deviceDescriptor.macAddress_ !=
1866 AudioSpatializationService::GetAudioSpatializationService().GetCurrentDeviceAddress()) {
1867 UpdateEffectBtOffloadSupported(false);
1868 }
1869 UpdateEffectDefaultSink(deviceDescriptor.deviceType_);
1870 AudioSpatializationService::GetAudioSpatializationService().UpdateCurrentDevice(deviceDescriptor.macAddress_);
1871 }
1872
OnPreferredInputDeviceUpdated(DeviceType deviceType,std::string networkId)1873 void AudioPolicyService::OnPreferredInputDeviceUpdated(DeviceType deviceType, std::string networkId)
1874 {
1875 AUDIO_INFO_LOG("OnPreferredInputDeviceUpdated start");
1876
1877 if (audioPolicyServerHandler_ != nullptr) {
1878 audioPolicyServerHandler_->SendPreferredInputDeviceUpdated();
1879 }
1880 }
1881
OnPreferredDeviceUpdated(const AudioDeviceDescriptor & activeOutputDevice,DeviceType activeInputDevice)1882 void AudioPolicyService::OnPreferredDeviceUpdated(const AudioDeviceDescriptor& activeOutputDevice,
1883 DeviceType activeInputDevice)
1884 {
1885 OnPreferredOutputDeviceUpdated(activeOutputDevice);
1886 OnPreferredInputDeviceUpdated(activeInputDevice, LOCAL_NETWORK_ID);
1887 }
1888
SetWakeUpAudioCapturer(InternalAudioCapturerOptions options)1889 int32_t AudioPolicyService::SetWakeUpAudioCapturer(InternalAudioCapturerOptions options)
1890 {
1891 AUDIO_INFO_LOG("set wakeup audio capturer start");
1892 AudioModuleInfo moduleInfo = {};
1893 if (!ConstructWakeupAudioModuleInfo(options.streamInfo, moduleInfo)) {
1894 AUDIO_ERR_LOG("failed to construct wakeup audio module info");
1895 return ERROR;
1896 }
1897 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
1898
1899 AUDIO_DEBUG_LOG("set wakeup audio capturer end");
1900 return SUCCESS;
1901 }
1902
SetWakeUpAudioCapturerFromAudioServer(const AudioProcessConfig & config)1903 int32_t AudioPolicyService::SetWakeUpAudioCapturerFromAudioServer(const AudioProcessConfig &config)
1904 {
1905 InternalAudioCapturerOptions capturerOptions;
1906 capturerOptions.streamInfo = config.streamInfo;
1907 return SetWakeUpAudioCapturer(capturerOptions);
1908 }
1909
NotifyCapturerAdded(AudioCapturerInfo capturerInfo,AudioStreamInfo streamInfo,uint32_t sessionId)1910 int32_t AudioPolicyService::NotifyCapturerAdded(AudioCapturerInfo capturerInfo, AudioStreamInfo streamInfo,
1911 uint32_t sessionId)
1912 {
1913 int32_t error = SUCCESS;
1914 audioPolicyServerHandler_->SendCapturerCreateEvent(capturerInfo, streamInfo, sessionId, true, error);
1915 return error;
1916 }
1917
NotifyWakeUpCapturerRemoved()1918 int32_t AudioPolicyService::NotifyWakeUpCapturerRemoved()
1919 {
1920 audioPolicyServerHandler_->SendWakeupCloseEvent(false);
1921 return SUCCESS;
1922 }
1923
IsAbsVolumeSupported()1924 bool AudioPolicyService::IsAbsVolumeSupported()
1925 {
1926 return IsAbsVolumeScene();
1927 }
1928
CloseWakeUpAudioCapturer()1929 int32_t AudioPolicyService::CloseWakeUpAudioCapturer()
1930 {
1931 AUDIO_INFO_LOG("close wakeup audio capturer start");
1932 std::lock_guard<std::mutex> lck(ioHandlesMutex_);
1933 auto ioHandleIter = IOHandles_.find(std::string(PRIMARY_WAKEUP));
1934 if (ioHandleIter == IOHandles_.end()) {
1935 AUDIO_ERR_LOG("close wakeup audio capturer failed");
1936 return ERROR;
1937 }
1938
1939 auto ioHandle = ioHandleIter->second;
1940 IOHandles_.erase(ioHandleIter);
1941 audioPolicyManager_.CloseAudioPort(ioHandle);
1942 return SUCCESS;
1943 }
1944
GetDevices(DeviceFlag deviceFlag)1945 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDevices(DeviceFlag deviceFlag)
1946 {
1947 AUDIO_DEBUG_LOG("GetDevices start");
1948 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
1949 return GetDevicesInner(deviceFlag);
1950 }
1951
GetDevicesInner(DeviceFlag deviceFlag)1952 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDevicesInner(DeviceFlag deviceFlag)
1953 {
1954 std::vector<sptr<AudioDeviceDescriptor>> deviceList = {};
1955
1956 CHECK_AND_RETURN_RET_LOG(deviceFlag >= DeviceFlag::OUTPUT_DEVICES_FLAG &&
1957 deviceFlag <= DeviceFlag::ALL_L_D_DEVICES_FLAG,
1958 deviceList, "Invalid flag provided %{public}d", deviceFlag);
1959
1960 CHECK_AND_RETURN_RET(deviceFlag != DeviceFlag::ALL_L_D_DEVICES_FLAG, connectedDevices_);
1961
1962 for (auto device : connectedDevices_) {
1963 if (device == nullptr) {
1964 continue;
1965 }
1966 bool filterAllLocal = deviceFlag == DeviceFlag::ALL_DEVICES_FLAG && device->networkId_ == LOCAL_NETWORK_ID;
1967 bool filterLocalOutput = deviceFlag == DeviceFlag::OUTPUT_DEVICES_FLAG
1968 && device->networkId_ == LOCAL_NETWORK_ID
1969 && device->deviceRole_ == DeviceRole::OUTPUT_DEVICE;
1970 bool filterLocalInput = deviceFlag == DeviceFlag::INPUT_DEVICES_FLAG
1971 && device->networkId_ == LOCAL_NETWORK_ID
1972 && device->deviceRole_ == DeviceRole::INPUT_DEVICE;
1973
1974 bool filterAllRemote = deviceFlag == DeviceFlag::ALL_DISTRIBUTED_DEVICES_FLAG
1975 && device->networkId_ != LOCAL_NETWORK_ID;
1976 bool filterRemoteOutput = deviceFlag == DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG
1977 && (device->networkId_ != LOCAL_NETWORK_ID || device->deviceType_ == DEVICE_TYPE_REMOTE_CAST)
1978 && device->deviceRole_ == DeviceRole::OUTPUT_DEVICE;
1979 bool filterRemoteInput = deviceFlag == DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG
1980 && device->networkId_ != LOCAL_NETWORK_ID
1981 && device->deviceRole_ == DeviceRole::INPUT_DEVICE;
1982
1983 if (filterAllLocal || filterLocalOutput || filterLocalInput || filterAllRemote || filterRemoteOutput
1984 || filterRemoteInput) {
1985 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*device);
1986 deviceList.push_back(devDesc);
1987 }
1988 }
1989
1990 AUDIO_DEBUG_LOG("GetDevices list size = [%{public}zu]", deviceList.size());
1991 return deviceList;
1992 }
1993
GetPreferredOutputDeviceDescriptors(AudioRendererInfo & rendererInfo,std::string networkId)1994 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredOutputDeviceDescriptors(
1995 AudioRendererInfo &rendererInfo, std::string networkId)
1996 {
1997 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
1998 return GetPreferredOutputDeviceDescInner(rendererInfo, networkId);
1999 }
2000
GetPreferredInputDeviceDescriptors(AudioCapturerInfo & captureInfo,std::string networkId)2001 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredInputDeviceDescriptors(
2002 AudioCapturerInfo &captureInfo, std::string networkId)
2003 {
2004 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
2005 return GetPreferredInputDeviceDescInner(captureInfo, networkId);
2006 }
2007
GetPreferredOutputDeviceDescInner(AudioRendererInfo & rendererInfo,std::string networkId)2008 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredOutputDeviceDescInner(
2009 AudioRendererInfo &rendererInfo, std::string networkId)
2010 {
2011 std::vector<sptr<AudioDeviceDescriptor>> deviceList = {};
2012 if (rendererInfo.streamUsage <= STREAM_USAGE_UNKNOWN ||
2013 rendererInfo.streamUsage > STREAM_USAGE_MAX) {
2014 AUDIO_WARNING_LOG("Invalid usage[%{public}d], return current device.", rendererInfo.streamUsage);
2015 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(GetCurrentOutputDevice());
2016 deviceList.push_back(devDesc);
2017 return deviceList;
2018 }
2019 if (networkId == LOCAL_NETWORK_ID) {
2020 vector<std::unique_ptr<AudioDeviceDescriptor>> descs =
2021 audioRouterCenter_.FetchOutputDevices(rendererInfo.streamUsage, -1);
2022 for (size_t i = 0; i < descs.size(); i++) {
2023 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*descs[i]);
2024 AUDIO_PRERELEASE_LOGI("streamUsage %{public}d fetch desc[%{public}zu]-device:%{public}d",
2025 rendererInfo.streamUsage, i, descs[i]->deviceType_);
2026 deviceList.push_back(devDesc);
2027 }
2028 } else {
2029 vector<unique_ptr<AudioDeviceDescriptor>> descs = audioDeviceManager_.GetRemoteRenderDevices();
2030 for (auto &desc : descs) {
2031 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc);
2032 deviceList.push_back(devDesc);
2033 }
2034 }
2035
2036 return deviceList;
2037 }
2038
SetCurrenInputDevice(const AudioDeviceDescriptor & desc)2039 void AudioPolicyService::SetCurrenInputDevice(const AudioDeviceDescriptor &desc)
2040 {
2041 std::lock_guard<std::mutex> lock(curInputDevice_);
2042 currentActiveInputDevice_ = AudioDeviceDescriptor(desc);
2043 }
2044
GetCurrentInputDevice()2045 AudioDeviceDescriptor AudioPolicyService::GetCurrentInputDevice()
2046 {
2047 std::lock_guard<std::mutex> lock(curInputDevice_);
2048 return currentActiveInputDevice_;
2049 }
2050
2051
GetCurrentInputDeviceType()2052 DeviceType AudioPolicyService::GetCurrentInputDeviceType()
2053 {
2054 std::lock_guard<std::mutex> lock(curInputDevice_);
2055 return currentActiveInputDevice_.deviceType_;
2056 }
2057
SetCurrentInputDeviceType(DeviceType deviceType)2058 void AudioPolicyService::SetCurrentInputDeviceType(DeviceType deviceType)
2059 {
2060 std::lock_guard<std::mutex> lock(curInputDevice_);
2061 currentActiveInputDevice_.deviceType_ = deviceType;
2062 }
2063
SetCurrentOutputDevice(const AudioDeviceDescriptor & desc)2064 void AudioPolicyService::SetCurrentOutputDevice(const AudioDeviceDescriptor &desc)
2065 {
2066 std::lock_guard<std::mutex> lock(curOutputDevice_);
2067 currentActiveDevice_ = AudioDeviceDescriptor(desc);
2068 }
2069
SetCurrentOutputDeviceType(DeviceType deviceType)2070 void AudioPolicyService::SetCurrentOutputDeviceType(DeviceType deviceType)
2071 {
2072 std::lock_guard<std::mutex> lock(curOutputDevice_);
2073 currentActiveDevice_.deviceType_ = deviceType;
2074 }
2075
GetCurrentOutputDevice()2076 AudioDeviceDescriptor AudioPolicyService::GetCurrentOutputDevice()
2077 {
2078 std::lock_guard<std::mutex> lock(curOutputDevice_);
2079 return currentActiveDevice_;
2080 }
2081
GetCurrentOutputDeviceType()2082 DeviceType AudioPolicyService::GetCurrentOutputDeviceType()
2083 {
2084 std::lock_guard<std::mutex> lock(curOutputDevice_);
2085 return currentActiveDevice_.deviceType_;
2086 }
2087
GetCurrentOutputDeviceCategory()2088 DeviceCategory AudioPolicyService::GetCurrentOutputDeviceCategory()
2089 {
2090 std::lock_guard<std::mutex> lock(curOutputDevice_);
2091 return currentActiveDevice_.deviceCategory_;
2092 }
2093
GetCurrentOutputDeviceNetworkId()2094 std::string AudioPolicyService::GetCurrentOutputDeviceNetworkId()
2095 {
2096 std::lock_guard<std::mutex> lock(curOutputDevice_);
2097 return currentActiveDevice_.networkId_;
2098 }
2099
GetCurrentOutputDeviceMacAddr()2100 std::string AudioPolicyService::GetCurrentOutputDeviceMacAddr()
2101 {
2102 std::lock_guard<std::mutex> lock(curOutputDevice_);
2103 return currentActiveDevice_.macAddress_;
2104 }
2105
GetPreferredInputDeviceDescInner(AudioCapturerInfo & captureInfo,std::string networkId)2106 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredInputDeviceDescInner(
2107 AudioCapturerInfo &captureInfo, std::string networkId)
2108 {
2109 std::vector<sptr<AudioDeviceDescriptor>> deviceList = {};
2110 if (captureInfo.sourceType <= SOURCE_TYPE_INVALID ||
2111 captureInfo.sourceType > SOURCE_TYPE_MAX) {
2112 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(GetCurrentInputDevice());
2113 deviceList.push_back(devDesc);
2114 return deviceList;
2115 }
2116
2117 if (captureInfo.sourceType == SOURCE_TYPE_WAKEUP) {
2118 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(DEVICE_TYPE_MIC, INPUT_DEVICE);
2119 devDesc->networkId_ = LOCAL_NETWORK_ID;
2120 deviceList.push_back(devDesc);
2121 return deviceList;
2122 }
2123
2124 if (networkId == LOCAL_NETWORK_ID) {
2125 unique_ptr<AudioDeviceDescriptor> desc = audioRouterCenter_.FetchInputDevice(captureInfo.sourceType, -1);
2126 if (desc->deviceType_ == DEVICE_TYPE_NONE && (captureInfo.sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE ||
2127 captureInfo.sourceType == SOURCE_TYPE_REMOTE_CAST)) {
2128 desc->deviceType_ = DEVICE_TYPE_INVALID;
2129 desc->deviceRole_ = INPUT_DEVICE;
2130 }
2131 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc);
2132 deviceList.push_back(devDesc);
2133 } else {
2134 vector<unique_ptr<AudioDeviceDescriptor>> descs = audioDeviceManager_.GetRemoteCaptureDevices();
2135 for (auto &desc : descs) {
2136 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc);
2137 deviceList.push_back(devDesc);
2138 }
2139 }
2140
2141 return deviceList;
2142 }
2143
SetClientCallbacksEnable(const CallbackChange & callbackchange,const bool & enable)2144 int32_t AudioPolicyService::SetClientCallbacksEnable(const CallbackChange &callbackchange, const bool &enable)
2145 {
2146 if (audioPolicyServerHandler_ != nullptr) {
2147 return audioPolicyServerHandler_->SetClientCallbacksEnable(callbackchange, enable);
2148 } else {
2149 AUDIO_ERR_LOG("audioPolicyServerHandler_ is nullptr");
2150 return AUDIO_ERR;
2151 }
2152 }
2153
UpdateActiveDeviceRoute(InternalDeviceType deviceType,DeviceFlag deviceFlag)2154 void AudioPolicyService::UpdateActiveDeviceRoute(InternalDeviceType deviceType, DeviceFlag deviceFlag)
2155 {
2156 Trace trace("AudioPolicyService::UpdateActiveDeviceRoute DeviceType:" + std::to_string(deviceType));
2157 AUDIO_INFO_LOG("Active route with type[%{public}d]", deviceType);
2158 std::vector<std::pair<InternalDeviceType, DeviceFlag>> activeDevices;
2159 activeDevices.push_back(make_pair(deviceType, deviceFlag));
2160 UpdateActiveDevicesRoute(activeDevices);
2161 }
2162
UpdateActiveDevicesRoute(std::vector<std::pair<InternalDeviceType,DeviceFlag>> & activeDevices)2163 void AudioPolicyService::UpdateActiveDevicesRoute(std::vector<std::pair<InternalDeviceType, DeviceFlag>>
2164 &activeDevices)
2165 {
2166 CHECK_AND_RETURN_LOG(!activeDevices.empty(), "activeDevices is empty.");
2167 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2168 CHECK_AND_RETURN_LOG(gsp != nullptr, "UpdateActiveDevicesRoute, Audio Server Proxy is null");
2169 auto ret = SUCCESS;
2170
2171 std::string deviceTypesInfo = "";
2172 for (size_t i = 0; i < activeDevices.size(); i++) {
2173 deviceTypesInfo = deviceTypesInfo + " " + std::to_string(activeDevices[i].first);
2174 AUDIO_INFO_LOG("update active devices, device type info:[%{public}s]",
2175 std::to_string(activeDevices[i].first).c_str());
2176 }
2177
2178 Trace trace("AudioPolicyService::UpdateActiveDevicesRoute DeviceTypes:" + deviceTypesInfo);
2179 std::string identity = IPCSkeleton::ResetCallingIdentity();
2180 ret = gsp->UpdateActiveDevicesRoute(activeDevices, a2dpOffloadFlag_);
2181 IPCSkeleton::SetCallingIdentity(identity);
2182 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the route for %{public}s", deviceTypesInfo.c_str());
2183 }
2184
UpdateDualToneState(const bool & enable,const int32_t & sessionId)2185 void AudioPolicyService::UpdateDualToneState(const bool &enable, const int32_t &sessionId)
2186 {
2187 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2188 CHECK_AND_RETURN_LOG(gsp != nullptr, "UpdateDualToneState, Audio Server Proxy is null");
2189 AUDIO_INFO_LOG("update dual tone state, enable:%{public}d, sessionId:%{public}d", enable, sessionId);
2190 enableDualHalToneState_ = enable;
2191 if (enableDualHalToneState_) {
2192 enableDualHalToneSessionId_ = sessionId;
2193 }
2194 auto ret = SUCCESS;
2195 Trace trace("AudioPolicyService::UpdateDualToneState sessionId:" + std::to_string(sessionId));
2196 std::string identity = IPCSkeleton::ResetCallingIdentity();
2197 ret = gsp->UpdateDualToneState(enable, sessionId);
2198 IPCSkeleton::SetCallingIdentity(identity);
2199 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the dual tone state for sessionId:%{public}d", sessionId);
2200 }
2201
GetSinkName(const AudioDeviceDescriptor & desc,int32_t sessionId)2202 std::string AudioPolicyService::GetSinkName(const AudioDeviceDescriptor &desc, int32_t sessionId)
2203 {
2204 if (desc.networkId_ == LOCAL_NETWORK_ID) {
2205 AudioPipeType pipeType = PIPE_TYPE_UNKNOWN;
2206 streamCollector_.GetPipeType(sessionId, pipeType);
2207 return GetSinkPortName(desc.deviceType_, pipeType);
2208 } else {
2209 return GetRemoteModuleName(desc.networkId_, desc.deviceRole_);
2210 }
2211 }
2212
SetVoiceCallMuteForSwitchDevice()2213 void AudioPolicyService::SetVoiceCallMuteForSwitchDevice()
2214 {
2215 Trace trace("SetVoiceMuteForSwitchDevice");
2216 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2217 CHECK_AND_RETURN_LOG(gsp != nullptr, "SetVoiceMuteForSwitchDevice, Audio Server Proxy is null");
2218 std::string identity = IPCSkeleton::ResetCallingIdentity();
2219 gsp->SetVoiceVolume(0);
2220 IPCSkeleton::SetCallingIdentity(identity);
2221
2222 AUDIO_INFO_LOG("%{public}" PRId64" us for modem call update route", WAIT_MODEM_CALL_SET_VOLUME_TIME_US);
2223 usleep(WAIT_MODEM_CALL_SET_VOLUME_TIME_US);
2224 // Unmute in SetVolumeForSwitchDevice after update route.
2225 }
2226
MuteSinkPortForSwtichDevice(unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & outputDevices,const AudioStreamDeviceChangeReasonExt reason)2227 void AudioPolicyService::MuteSinkPortForSwtichDevice(unique_ptr<AudioRendererChangeInfo>& rendererChangeInfo,
2228 vector<std::unique_ptr<AudioDeviceDescriptor>>& outputDevices, const AudioStreamDeviceChangeReasonExt reason)
2229 {
2230 Trace trace("AudioPolicyService::MuteSinkPortForSwtichDevice");
2231 if (outputDevices.size() != 1) {
2232 // mute primary when play music and ring
2233 if (IsStreamActive(STREAM_MUSIC)) {
2234 MuteSinkPort(PRIMARY_SPEAKER, SET_BT_ABS_SCENE_DELAY_MS, true);
2235 }
2236 return;
2237 }
2238 if (outputDevices.front()->IsSameDeviceDesc(rendererChangeInfo->outputDeviceInfo)) return;
2239
2240 moveDeviceFinished_ = false;
2241
2242 if (audioScene_ == AUDIO_SCENE_PHONE_CALL) {
2243 return SetVoiceCallMuteForSwitchDevice();
2244 }
2245
2246 std::string oldSinkName = GetSinkName(rendererChangeInfo->outputDeviceInfo, rendererChangeInfo->sessionId);
2247 std::string newSinkName = GetSinkName(*outputDevices.front(), rendererChangeInfo->sessionId);
2248 AUDIO_INFO_LOG("mute sink old:[%{public}s] new:[%{public}s]", oldSinkName.c_str(), newSinkName.c_str());
2249 MuteSinkPort(oldSinkName, newSinkName, reason);
2250 }
2251
MoveToNewOutputDevice(unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & outputDevices,const AudioStreamDeviceChangeReasonExt reason)2252 void AudioPolicyService::MoveToNewOutputDevice(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
2253 vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices, const AudioStreamDeviceChangeReasonExt reason)
2254 {
2255 Trace trace("AudioPolicyService::MoveToNewOutputDevice");
2256 std::vector<SinkInput> targetSinkInputs = FilterSinkInputs(rendererChangeInfo->sessionId);
2257
2258 bool needTriggerCallback = true;
2259 if (outputDevices.front()->IsSameDeviceDesc(rendererChangeInfo->outputDeviceInfo)) {
2260 needTriggerCallback = false;
2261 }
2262
2263 AUDIO_WARNING_LOG("move session %{public}d [%{public}d][%{public}s]-->[%{public}d][%{public}s], reason %{public}d",
2264 rendererChangeInfo->sessionId, rendererChangeInfo->outputDeviceInfo.deviceType_,
2265 GetEncryptAddr(rendererChangeInfo->outputDeviceInfo.macAddress_).c_str(),
2266 outputDevices.front()->deviceType_, GetEncryptAddr(outputDevices.front()->macAddress_).c_str(),
2267 static_cast<int>(reason));
2268
2269 DeviceType oldDevice = rendererChangeInfo->outputDeviceInfo.deviceType_;
2270
2271 UpdateDeviceInfo(rendererChangeInfo->outputDeviceInfo,
2272 new AudioDeviceDescriptor(*outputDevices.front()), true, true);
2273
2274 if (needTriggerCallback) {
2275 audioPolicyServerHandler_->SendRendererDeviceChangeEvent(rendererChangeInfo->callerPid,
2276 rendererChangeInfo->sessionId, rendererChangeInfo->outputDeviceInfo, reason);
2277 }
2278
2279 UpdateEffectDefaultSink(outputDevices.front()->deviceType_);
2280 // MoveSinkInputByIndexOrName
2281 auto ret = (outputDevices.front()->networkId_ == LOCAL_NETWORK_ID)
2282 ? MoveToLocalOutputDevice(targetSinkInputs, new AudioDeviceDescriptor(*outputDevices.front()))
2283 : MoveToRemoteOutputDevice(targetSinkInputs, new AudioDeviceDescriptor(*outputDevices.front()));
2284 if (ret != SUCCESS) {
2285 UpdateEffectDefaultSink(oldDevice);
2286 AUDIO_ERR_LOG("Move sink input %{public}d to device %{public}d failed!",
2287 rendererChangeInfo->sessionId, outputDevices.front()->deviceType_);
2288 std::unique_lock<std::mutex> lock(moveDeviceMutex_);
2289 moveDeviceFinished_ = true;
2290 moveDeviceCV_.notify_all();
2291 return;
2292 }
2293
2294 if (isUpdateRouteSupported_ && outputDevices.front()->networkId_ == LOCAL_NETWORK_ID &&
2295 !reason.isSetAudioScene()) {
2296 UpdateRoute(rendererChangeInfo, outputDevices);
2297 }
2298
2299 std::string newSinkName = GetSinkName(*outputDevices.front(), rendererChangeInfo->sessionId);
2300 SetVolumeForSwitchDevice(outputDevices.front()->deviceType_, newSinkName);
2301
2302 streamCollector_.UpdateRendererDeviceInfo(rendererChangeInfo->clientUID, rendererChangeInfo->sessionId,
2303 rendererChangeInfo->outputDeviceInfo);
2304 ResetOffloadAndMchMode(rendererChangeInfo, outputDevices);
2305 std::unique_lock<std::mutex> lock(moveDeviceMutex_);
2306 moveDeviceFinished_ = true;
2307 moveDeviceCV_.notify_all();
2308 }
2309
MoveToNewInputDevice(unique_ptr<AudioCapturerChangeInfo> & capturerChangeInfo,unique_ptr<AudioDeviceDescriptor> & inputDevice)2310 void AudioPolicyService::MoveToNewInputDevice(unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo,
2311 unique_ptr<AudioDeviceDescriptor> &inputDevice)
2312 {
2313 std::vector<SourceOutput> targetSourceOutputs = FilterSourceOutputs(capturerChangeInfo->sessionId);
2314
2315 // MoveSourceOuputByIndexName
2316 auto ret = (inputDevice->networkId_ == LOCAL_NETWORK_ID)
2317 ? MoveToLocalInputDevice(targetSourceOutputs, new AudioDeviceDescriptor(*inputDevice))
2318 : MoveToRemoteInputDevice(targetSourceOutputs, new AudioDeviceDescriptor(*inputDevice));
2319 CHECK_AND_RETURN_LOG((ret == SUCCESS), "Move source output %{public}d to device %{public}d failed!",
2320 capturerChangeInfo->sessionId, inputDevice->deviceType_);
2321 AUDIO_WARNING_LOG("move session %{public}d [%{public}d][%{public}s]-->[%{public}d][%{public}s]",
2322 capturerChangeInfo->sessionId, capturerChangeInfo->inputDeviceInfo.deviceType_,
2323 GetEncryptAddr(capturerChangeInfo->inputDeviceInfo.macAddress_).c_str(),
2324 inputDevice->deviceType_, GetEncryptAddr(inputDevice->macAddress_).c_str());
2325
2326 if (isUpdateRouteSupported_ && inputDevice->networkId_ == LOCAL_NETWORK_ID) {
2327 UpdateActiveDeviceRoute(inputDevice->deviceType_, DeviceFlag::INPUT_DEVICES_FLAG);
2328 }
2329 UpdateDeviceInfo(capturerChangeInfo->inputDeviceInfo, new AudioDeviceDescriptor(*inputDevice), true, true);
2330 streamCollector_.UpdateCapturerDeviceInfo(capturerChangeInfo->clientUID, capturerChangeInfo->sessionId,
2331 capturerChangeInfo->inputDeviceInfo);
2332 }
2333
FetchOutputDeviceWhenNoRunningStream()2334 void AudioPolicyService::FetchOutputDeviceWhenNoRunningStream()
2335 {
2336 AUDIO_PRERELEASE_LOGI("In");
2337 vector<std::unique_ptr<AudioDeviceDescriptor>> descs =
2338 audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_MEDIA, -1);
2339 CHECK_AND_RETURN_LOG(!descs.empty(), "descs is empty");
2340 AudioDeviceDescriptor tmpOutputDeviceDesc = GetCurrentOutputDevice();
2341 if (descs.front()->deviceType_ == DEVICE_TYPE_NONE || IsSameDevice(descs.front(), tmpOutputDeviceDesc)) {
2342 AUDIO_DEBUG_LOG("output device is not change");
2343 return;
2344 }
2345 SetCurrentOutputDevice(*descs.front());
2346 AUDIO_DEBUG_LOG("currentActiveDevice update %{public}d", GetCurrentOutputDeviceType());
2347 SetVolumeForSwitchDevice(descs.front()->deviceType_);
2348 if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
2349 SwitchActiveA2dpDevice(new AudioDeviceDescriptor(*descs.front()));
2350 }
2351 OnPreferredOutputDeviceUpdated(GetCurrentOutputDevice());
2352 }
2353
FetchInputDeviceWhenNoRunningStream()2354 void AudioPolicyService::FetchInputDeviceWhenNoRunningStream()
2355 {
2356 AUDIO_PRERELEASE_LOGI("In");
2357 unique_ptr<AudioDeviceDescriptor> desc;
2358 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice();
2359 if (tempDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO &&
2360 (Bluetooth::AudioHfpManager::GetScoCategory() == Bluetooth::ScoCategory::SCO_RECOGNITION ||
2361 Bluetooth::AudioHfpManager::GetRecognitionStatus() == Bluetooth::RecognitionStatus::RECOGNITION_CONNECTING)) {
2362 desc = audioRouterCenter_.FetchInputDevice(SOURCE_TYPE_VOICE_RECOGNITION, -1);
2363 } else {
2364 desc = audioRouterCenter_.FetchInputDevice(SOURCE_TYPE_MIC, -1);
2365 }
2366
2367 if (desc->deviceType_ == DEVICE_TYPE_NONE || IsSameDevice(desc, tempDesc)) {
2368 AUDIO_DEBUG_LOG("input device is not change");
2369 return;
2370 }
2371 SetCurrenInputDevice(*desc);
2372 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP || desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
2373 activeBTDevice_ = desc->macAddress_;
2374 }
2375 DeviceType deviceType = GetCurrentInputDeviceType();
2376 AUDIO_DEBUG_LOG("currentActiveInputDevice update %{public}d", deviceType);
2377 OnPreferredInputDeviceUpdated(deviceType, ""); // networkId is not used
2378 }
2379
ActivateA2dpDevice(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioRendererChangeInfo>> & rendererChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2380 int32_t AudioPolicyService::ActivateA2dpDevice(unique_ptr<AudioDeviceDescriptor> &desc,
2381 vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos, const AudioStreamDeviceChangeReasonExt reason)
2382 {
2383 Trace trace("AudioPolicyService::ActivateA2dpDevice");
2384 sptr<AudioDeviceDescriptor> deviceDesc = new AudioDeviceDescriptor(*desc);
2385 int32_t ret = SwitchActiveA2dpDevice(deviceDesc);
2386 if (ret != SUCCESS) {
2387 AUDIO_ERR_LOG("Active A2DP device failed, retrigger fetch output device");
2388 deviceDesc->exceptionFlag_ = true;
2389 audioDeviceManager_.UpdateDevicesListInfo(deviceDesc, EXCEPTION_FLAG_UPDATE);
2390 {
2391 std::unique_lock<std::mutex> lock(moveDeviceMutex_);
2392 moveDeviceFinished_ = true;
2393 moveDeviceCV_.notify_all();
2394 }
2395 FetchOutputDevice(rendererChangeInfos, reason);
2396 return ERROR;
2397 }
2398 return SUCCESS;
2399 }
2400
HandleScoOutputDeviceFetched(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioRendererChangeInfo>> & rendererChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2401 int32_t AudioPolicyService::HandleScoOutputDeviceFetched(unique_ptr<AudioDeviceDescriptor> &desc,
2402 vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
2403 const AudioStreamDeviceChangeReasonExt reason)
2404 {
2405 Trace trace("AudioPolicyService::HandleScoOutputDeviceFetched");
2406 #ifdef BLUETOOTH_ENABLE
2407 int32_t ret = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_);
2408 if (ret != SUCCESS) {
2409 AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch output device.");
2410 desc->exceptionFlag_ = true;
2411 audioDeviceManager_.UpdateDevicesListInfo(new AudioDeviceDescriptor(*desc), EXCEPTION_FLAG_UPDATE);
2412 FetchOutputDevice(rendererChangeInfos, reason);
2413 return ERROR;
2414 }
2415 if (desc->connectState_ == DEACTIVE_CONNECTED || lastAudioScene_ != audioScene_) {
2416 Bluetooth::AudioHfpManager::ConnectScoWithAudioScene(audioScene_);
2417 return SUCCESS;
2418 }
2419 #endif
2420 return SUCCESS;
2421 }
2422
IsRendererStreamRunning(unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo)2423 bool AudioPolicyService::IsRendererStreamRunning(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo)
2424 {
2425 StreamUsage usage = rendererChangeInfo->rendererInfo.streamUsage;
2426 RendererState rendererState = rendererChangeInfo->rendererState;
2427 if ((usage == STREAM_USAGE_VOICE_MODEM_COMMUNICATION && audioScene_ != AUDIO_SCENE_PHONE_CALL) ||
2428 (usage != STREAM_USAGE_VOICE_MODEM_COMMUNICATION &&
2429 (rendererState != RENDERER_RUNNING && !rendererChangeInfo->prerunningState))) {
2430 return false;
2431 }
2432 return true;
2433 }
2434
NeedRehandleA2DPDevice(unique_ptr<AudioDeviceDescriptor> & desc)2435 bool AudioPolicyService::NeedRehandleA2DPDevice(unique_ptr<AudioDeviceDescriptor> &desc)
2436 {
2437 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
2438 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP && IOHandles_.find(BLUETOOTH_SPEAKER) == IOHandles_.end()) {
2439 AUDIO_WARNING_LOG("A2DP module is not loaded, need rehandle");
2440 return true;
2441 }
2442 return false;
2443 }
2444
MuteSinkPort(const std::string & portName,int32_t duration,bool isSync)2445 void AudioPolicyService::MuteSinkPort(const std::string &portName, int32_t duration, bool isSync)
2446 {
2447 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2448 CHECK_AND_RETURN_LOG(gsp != nullptr, "MuteSinkPort, Audio Server Proxy is null");
2449
2450 std::string identity = IPCSkeleton::ResetCallingIdentity();
2451 if (sinkPortStrToClassStrMap_.count(portName) > 0) {
2452 // Mute by render sink. (primary、a2dp、usb、dp、offload)
2453 gsp->SetSinkMuteForSwitchDevice(sinkPortStrToClassStrMap_.at(portName), duration, true);
2454 } else {
2455 // Mute by pa.
2456 audioPolicyManager_.SetSinkMute(portName, true, isSync);
2457 }
2458 IPCSkeleton::SetCallingIdentity(identity);
2459 usleep(WAIT_SET_MUTE_LATENCY_TIME_US); // sleep fix data cache pop.
2460
2461 // Muted and then unmute.
2462 thread switchThread(&AudioPolicyService::UnmutePortAfterMuteDuration, this, duration, portName, DEVICE_TYPE_NONE);
2463 switchThread.detach();
2464 }
2465
MuteSinkPort(const std::string & oldSinkName,const std::string & newSinkName,AudioStreamDeviceChangeReasonExt reason)2466 void AudioPolicyService::MuteSinkPort(const std::string &oldSinkName, const std::string &newSinkName,
2467 AudioStreamDeviceChangeReasonExt reason)
2468 {
2469 auto ringermode = GetRingerMode();
2470 if (reason.isOverride() || reason.isSetDefaultOutputDevice()) {
2471 int64_t muteTime = SELECT_DEVICE_MUTE_MS;
2472 if (newSinkName == OFFLOAD_PRIMARY_SPEAKER || oldSinkName == OFFLOAD_PRIMARY_SPEAKER) {
2473 muteTime = SELECT_OFFLOAD_DEVICE_MUTE_MS;
2474 }
2475 MutePrimaryOrOffloadSink(oldSinkName, muteTime);
2476 MuteSinkPort(newSinkName, SELECT_DEVICE_MUTE_MS, true);
2477 MuteSinkPort(oldSinkName, muteTime, true);
2478 } else if (reason == AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE) {
2479 int64_t muteTime = NEW_DEVICE_AVALIABLE_MUTE_MS;
2480 if (newSinkName == OFFLOAD_PRIMARY_SPEAKER || oldSinkName == OFFLOAD_PRIMARY_SPEAKER) {
2481 muteTime = NEW_DEVICE_AVALIABLE_OFFLOAD_MUTE_MS;
2482 }
2483 MuteSinkPort(newSinkName, NEW_DEVICE_AVALIABLE_MUTE_MS, true);
2484 MuteSinkPort(oldSinkName, muteTime, true);
2485 } else if (reason.IsOldDeviceUnavaliable() && ((audioScene_ == AUDIO_SCENE_DEFAULT) ||
2486 ((audioScene_ == AUDIO_SCENE_RINGING || audioScene_ == AUDIO_SCENE_VOICE_RINGING) &&
2487 ringermode != RINGER_MODE_NORMAL))) {
2488 MuteSinkPort(newSinkName, OLD_DEVICE_UNAVALIABLE_MUTE_MS, true);
2489 usleep(OLD_DEVICE_UNAVALIABLE_MUTE_SLEEP_MS); // sleep fix data cache pop.
2490 } else if (reason.IsOldDeviceUnavaliableExt() && ((audioScene_ == AUDIO_SCENE_DEFAULT) ||
2491 ((audioScene_ == AUDIO_SCENE_RINGING || audioScene_ == AUDIO_SCENE_VOICE_RINGING) &&
2492 ringermode != RINGER_MODE_NORMAL))) {
2493 MuteSinkPort(newSinkName, OLD_DEVICE_UNAVALIABLE_EXT_MUTE_MS, true);
2494 usleep(OLD_DEVICE_UNAVALIABLE_MUTE_SLEEP_MS); // sleep fix data cache pop.
2495 } else if (reason == AudioStreamDeviceChangeReason::UNKNOWN &&
2496 oldSinkName == REMOTE_CAST_INNER_CAPTURER_SINK_NAME) {
2497 // remote cast -> earpiece 300ms fix sound leak
2498 MuteSinkPort(newSinkName, NEW_DEVICE_REMOTE_CAST_AVALIABLE_MUTE_MS, true);
2499 }
2500 }
2501
MutePrimaryOrOffloadSink(const std::string & sinkName,int64_t muteTime)2502 void AudioPolicyService::MutePrimaryOrOffloadSink(const std::string &sinkName, int64_t muteTime)
2503 {
2504 // fix pop when switching devices during multiple concurrent streams
2505 if (sinkName == OFFLOAD_PRIMARY_SPEAKER) {
2506 MuteSinkPort(PRIMARY_SPEAKER, muteTime, true);
2507 } else if (sinkName == PRIMARY_SPEAKER) {
2508 MuteSinkPort(OFFLOAD_PRIMARY_SPEAKER, muteTime, true);
2509 }
2510 }
2511
MuteDefaultSinkPort()2512 void AudioPolicyService::MuteDefaultSinkPort()
2513 {
2514 AudioDeviceDescriptor currentDeviceDescriptor = GetCurrentOutputDevice();
2515 if (currentDeviceDescriptor.networkId_ != LOCAL_NETWORK_ID ||
2516 (currentDeviceDescriptor.networkId_ == LOCAL_NETWORK_ID &&
2517 GetSinkPortName(currentDeviceDescriptor.deviceType_) != PRIMARY_SPEAKER)) {
2518 // PA may move the sink to default when unloading module.
2519 MuteSinkPort(PRIMARY_SPEAKER, OLD_DEVICE_UNAVALIABLE_MUTE_MS, true);
2520 }
2521 }
2522
HandleDeviceChangeForFetchOutputDevice(unique_ptr<AudioDeviceDescriptor> & desc,unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo)2523 int32_t AudioPolicyService::HandleDeviceChangeForFetchOutputDevice(unique_ptr<AudioDeviceDescriptor> &desc,
2524 unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo)
2525 {
2526 if (desc->deviceType_ == DEVICE_TYPE_NONE || (IsSameDevice(desc, rendererChangeInfo->outputDeviceInfo) &&
2527 !NeedRehandleA2DPDevice(desc) && desc->connectState_ != DEACTIVE_CONNECTED &&
2528 lastAudioScene_ == audioScene_ && !shouldUpdateDeviceDueToDualTone_)) {
2529 AUDIO_WARNING_LOG("stream %{public}d device not change, no need move device", rendererChangeInfo->sessionId);
2530 AudioDeviceDescriptor tmpOutputDeviceDesc = GetCurrentOutputDevice();
2531 if (!IsSameDevice(desc, tmpOutputDeviceDesc)) {
2532 SetCurrentOutputDevice(*desc);
2533 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
2534 SetVolumeForSwitchDevice(curOutputDeviceType);
2535 UpdateActiveDeviceRoute(curOutputDeviceType, DeviceFlag::OUTPUT_DEVICES_FLAG);
2536 OnPreferredOutputDeviceUpdated(GetCurrentOutputDevice());
2537 }
2538 return ERR_NEED_NOT_SWITCH_DEVICE;
2539 }
2540 return SUCCESS;
2541 }
2542
UpdateDevice(unique_ptr<AudioDeviceDescriptor> & desc,const AudioStreamDeviceChangeReasonExt reason,const std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo)2543 bool AudioPolicyService::UpdateDevice(unique_ptr<AudioDeviceDescriptor> &desc,
2544 const AudioStreamDeviceChangeReasonExt reason, const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo)
2545 {
2546 bool isUpdate = false;
2547 AudioDeviceDescriptor tmpOutputDeviceDesc = GetCurrentOutputDevice();
2548 if (!IsSameDevice(desc, tmpOutputDeviceDesc)) {
2549 WriteOutputRouteChangeEvent(desc, reason);
2550 SetCurrentOutputDevice(*desc);
2551 AUDIO_DEBUG_LOG("currentActiveDevice update %{public}d", GetCurrentOutputDeviceType());
2552 isUpdate = true;
2553 }
2554 return isUpdate;
2555 }
2556
FetchOutputDevice(vector<unique_ptr<AudioRendererChangeInfo>> & rendererChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2557 void AudioPolicyService::FetchOutputDevice(vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
2558 const AudioStreamDeviceChangeReasonExt reason)
2559 {
2560 Trace trace("AudioPolicyService::FetchOutputDevice");
2561 AUDIO_PRERELEASE_LOGI("Start for %{public}zu stream, connected %{public}s",
2562 rendererChangeInfos.size(), audioDeviceManager_.GetConnDevicesStr().c_str());
2563 bool needUpdateActiveDevice = true;
2564 bool isUpdateActiveDevice = false;
2565 int32_t runningStreamCount = 0;
2566 bool hasDirectChangeDevice = false;
2567 for (auto &rendererChangeInfo : rendererChangeInfos) {
2568 if (!IsRendererStreamRunning(rendererChangeInfo) || (audioScene_ == AUDIO_SCENE_DEFAULT &&
2569 audioRouterCenter_.isCallRenderRouter(rendererChangeInfo->rendererInfo.streamUsage))) {
2570 AUDIO_WARNING_LOG("stream %{public}d not running, no need fetch device", rendererChangeInfo->sessionId);
2571 continue;
2572 }
2573 runningStreamCount++;
2574 vector<std::unique_ptr<AudioDeviceDescriptor>> descs =
2575 audioRouterCenter_.FetchOutputDevices(rendererChangeInfo->rendererInfo.streamUsage,
2576 rendererChangeInfo->clientUID);
2577 if (HandleDeviceChangeForFetchOutputDevice(descs.front(), rendererChangeInfo) == ERR_NEED_NOT_SWITCH_DEVICE &&
2578 !Util::IsRingerOrAlarmerStreamUsage(rendererChangeInfo->rendererInfo.streamUsage)) {
2579 continue;
2580 }
2581 MuteSinkPortForSwtichDevice(rendererChangeInfo, descs, reason);
2582 std::string encryptMacAddr = GetEncryptAddr(descs.front()->macAddress_);
2583 if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
2584 if (IsFastFromA2dpToA2dp(descs.front(), rendererChangeInfo, reason)) { continue; }
2585 int32_t ret = ActivateA2dpDeviceWhenDescEnabled(descs.front(), rendererChangeInfos, reason);
2586 CHECK_AND_RETURN_LOG(ret == SUCCESS, "activate a2dp [%{public}s] failed", encryptMacAddr.c_str());
2587 } else if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
2588 int32_t ret = HandleScoOutputDeviceFetched(descs.front(), rendererChangeInfos, reason);
2589 CHECK_AND_RETURN_LOG(ret == SUCCESS, "sco [%{public}s] is not connected yet", encryptMacAddr.c_str());
2590 }
2591 if (needUpdateActiveDevice) {
2592 isUpdateActiveDevice = UpdateDevice(descs.front(), reason, rendererChangeInfo);
2593 needUpdateActiveDevice = false;
2594 }
2595 if (!hasDirectChangeDevice && isUpdateActiveDevice && NotifyRecreateDirectStream(rendererChangeInfo, reason)) {
2596 hasDirectChangeDevice = true;
2597 }
2598 NotifyRecreateRendererStream(descs.front(), rendererChangeInfo, reason);
2599 MoveToNewOutputDevice(rendererChangeInfo, descs, reason);
2600 }
2601 if (isUpdateActiveDevice) {
2602 OnPreferredOutputDeviceUpdated(GetCurrentOutputDevice());
2603 }
2604 if (runningStreamCount == 0) {
2605 FetchOutputDeviceWhenNoRunningStream();
2606 }
2607 }
2608
ActivateA2dpDeviceWhenDescEnabled(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioRendererChangeInfo>> & rendererChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2609 int32_t AudioPolicyService::ActivateA2dpDeviceWhenDescEnabled(unique_ptr<AudioDeviceDescriptor> &desc,
2610 vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos, const AudioStreamDeviceChangeReasonExt reason)
2611 {
2612 if (desc->isEnable_) {
2613 AUDIO_INFO_LOG("descs front is enabled");
2614 return ActivateA2dpDevice(desc, rendererChangeInfos, reason);
2615 }
2616 return SUCCESS;
2617 }
2618
IsFastFromA2dpToA2dp(const std::unique_ptr<AudioDeviceDescriptor> & desc,const std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,const AudioStreamDeviceChangeReasonExt reason)2619 bool AudioPolicyService::IsFastFromA2dpToA2dp(const std::unique_ptr<AudioDeviceDescriptor> &desc,
2620 const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, const AudioStreamDeviceChangeReasonExt reason)
2621 {
2622 if (rendererChangeInfo->outputDeviceInfo.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
2623 rendererChangeInfo->rendererInfo.originalFlag == AUDIO_FLAG_MMAP &&
2624 rendererChangeInfo->outputDeviceInfo.deviceId_ != desc->deviceId_) {
2625 TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, rendererChangeInfo->sessionId,
2626 AUDIO_FLAG_MMAP, reason);
2627 AUDIO_INFO_LOG("Switch fast stream from a2dp to a2dp");
2628 return true;
2629 }
2630 return false;
2631 }
2632
NotifyRecreateRendererStream(std::unique_ptr<AudioDeviceDescriptor> & desc,const std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,const AudioStreamDeviceChangeReasonExt reason)2633 bool AudioPolicyService::NotifyRecreateRendererStream(std::unique_ptr<AudioDeviceDescriptor> &desc,
2634 const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, const AudioStreamDeviceChangeReasonExt reason)
2635 {
2636 AUDIO_INFO_LOG("New device type: %{public}d, current rendererFlag: %{public}d, origianl flag: %{public}d",
2637 desc->deviceType_, rendererChangeInfo->rendererInfo.rendererFlags,
2638 rendererChangeInfo->rendererInfo.originalFlag);
2639 CHECK_AND_RETURN_RET_LOG(rendererChangeInfo->outputDeviceInfo.deviceType_ != DEVICE_TYPE_INVALID &&
2640 desc->deviceType_ != DEVICE_TYPE_INVALID, false, "isUpdateActiveDevice is false");
2641 CHECK_AND_RETURN_RET_LOG(rendererChangeInfo->rendererInfo.originalFlag != AUDIO_FLAG_NORMAL &&
2642 rendererChangeInfo->rendererInfo.originalFlag != AUDIO_FLAG_FORCED_NORMAL, false, "original flag is normal");
2643 // Switch between old and new stream as they have different hals
2644 std::string oldDevicePortName = GetSinkPortName(rendererChangeInfo->outputDeviceInfo.deviceType_);
2645 bool isOldDeviceLocal = rendererChangeInfo->outputDeviceInfo.networkId_ == "" ||
2646 rendererChangeInfo->outputDeviceInfo.networkId_ == LOCAL_NETWORK_ID;
2647 bool isNewDeviceLocal = desc->networkId_ == "" || desc->networkId_ == LOCAL_NETWORK_ID;
2648 if ((strcmp(oldDevicePortName.c_str(), GetSinkPortName(desc->deviceType_).c_str())) ||
2649 (isOldDeviceLocal ^ isNewDeviceLocal)) {
2650 int32_t streamClass = GetPreferredOutputStreamTypeInner(rendererChangeInfo->rendererInfo.streamUsage,
2651 desc->deviceType_, rendererChangeInfo->rendererInfo.originalFlag, desc->networkId_,
2652 rendererChangeInfo->rendererInfo.samplingRate);
2653 TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid,
2654 rendererChangeInfo->sessionId, streamClass, reason);
2655 return true;
2656 }
2657 return false;
2658 }
2659
NotifyRecreateDirectStream(std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,const AudioStreamDeviceChangeReasonExt reason)2660 bool AudioPolicyService::NotifyRecreateDirectStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
2661 const AudioStreamDeviceChangeReasonExt reason)
2662 {
2663 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
2664 AUDIO_INFO_LOG("current pipe type is:%{public}d", rendererChangeInfo->rendererInfo.pipeType);
2665 if (!IsDirectSupportedDevice(curOutputDeviceType) &&
2666 rendererChangeInfo->rendererInfo.pipeType == PIPE_TYPE_DIRECT_MUSIC) {
2667 if (rendererChangeInfo->outputDeviceInfo.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
2668 AUDIO_INFO_LOG("old device is arm usb");
2669 return false;
2670 }
2671 AUDIO_DEBUG_LOG("direct stream changed to normal.");
2672 TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, rendererChangeInfo->sessionId,
2673 AUDIO_FLAG_DIRECT, reason);
2674 return true;
2675 } else if (IsDirectSupportedDevice(curOutputDeviceType) &&
2676 rendererChangeInfo->rendererInfo.pipeType != PIPE_TYPE_DIRECT_MUSIC) {
2677 AudioRendererInfo info = rendererChangeInfo->rendererInfo;
2678 if (info.streamUsage == STREAM_USAGE_MUSIC && info.rendererFlags == AUDIO_FLAG_NORMAL &&
2679 info.samplingRate >= SAMPLE_RATE_48000 && info.format >= SAMPLE_S24LE) {
2680 AUDIO_DEBUG_LOG("stream change to direct.");
2681 TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, rendererChangeInfo->sessionId,
2682 AUDIO_FLAG_DIRECT, reason);
2683 return true;
2684 }
2685 }
2686 return false;
2687 }
2688
IsDirectSupportedDevice(DeviceType deviceType)2689 bool AudioPolicyService::IsDirectSupportedDevice(DeviceType deviceType)
2690 {
2691 return deviceType == DEVICE_TYPE_WIRED_HEADSET || deviceType == DEVICE_TYPE_USB_HEADSET;
2692 }
2693
TriggerRecreateRendererStreamCallback(int32_t callerPid,int32_t sessionId,int32_t streamFlag,const AudioStreamDeviceChangeReasonExt reason)2694 void AudioPolicyService::TriggerRecreateRendererStreamCallback(int32_t callerPid, int32_t sessionId, int32_t streamFlag,
2695 const AudioStreamDeviceChangeReasonExt reason)
2696 {
2697 Trace trace("AudioPolicyService::TriggerRecreateRendererStreamCallback");
2698 AUDIO_INFO_LOG("Trigger recreate renderer stream, pid: %{public}d, sessionId: %{public}d, flag: %{public}d",
2699 callerPid, sessionId, streamFlag);
2700 if (audioPolicyServerHandler_ != nullptr) {
2701 audioPolicyServerHandler_->SendRecreateRendererStreamEvent(callerPid, sessionId, streamFlag, reason);
2702 } else {
2703 AUDIO_WARNING_LOG("No audio policy server handler");
2704 }
2705 }
2706
WriteOutputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> & desc,const AudioStreamDeviceChangeReason reason)2707 void AudioPolicyService::WriteOutputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> &desc,
2708 const AudioStreamDeviceChangeReason reason)
2709 {
2710 int64_t timeStamp = GetCurrentTimeMS();
2711 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
2712 Media::MediaMonitor::AUDIO, Media::MediaMonitor::AUDIO_ROUTE_CHANGE,
2713 Media::MediaMonitor::BEHAVIOR_EVENT);
2714 bean->Add("REASON", static_cast<int32_t>(reason));
2715 bean->Add("TIMESTAMP", static_cast<uint64_t>(timeStamp));
2716 bean->Add("DEVICE_TYPE_BEFORE_CHANGE", currentActiveDevice_.deviceType_);
2717 bean->Add("DEVICE_TYPE_AFTER_CHANGE", desc->deviceType_);
2718 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
2719 }
2720
FetchStreamForA2dpMchStream(std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & descs)2721 void AudioPolicyService::FetchStreamForA2dpMchStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
2722 vector<std::unique_ptr<AudioDeviceDescriptor>> &descs)
2723 {
2724 if (CheckStreamMultichannelMode(rendererChangeInfo->sessionId)) {
2725 JudgeIfLoadMchModule();
2726 UpdateActiveDeviceRoute(DEVICE_TYPE_BLUETOOTH_A2DP, DeviceFlag::OUTPUT_DEVICES_FLAG);
2727 std::string portName = GetSinkPortName(descs.front()->deviceType_, PIPE_TYPE_MULTICHANNEL);
2728 int32_t ret = MoveToOutputDevice(rendererChangeInfo->sessionId, portName);
2729 if (ret == SUCCESS) {
2730 streamCollector_.UpdateRendererPipeInfo(rendererChangeInfo->sessionId, PIPE_TYPE_MULTICHANNEL);
2731 }
2732 } else {
2733 AudioPipeType pipeType = PIPE_TYPE_UNKNOWN;
2734 streamCollector_.GetPipeType(rendererChangeInfo->sessionId, pipeType);
2735 if (pipeType == PIPE_TYPE_MULTICHANNEL) {
2736 std::string currentActivePort = MCH_PRIMARY_SPEAKER;
2737 auto ioHandleIter = IOHandles_.find(currentActivePort);
2738 CHECK_AND_RETURN_LOG(ioHandleIter != IOHandles_.end(), "Can not find port MCH_PRIMARY_SPEAKER in io map");
2739 AudioIOHandle activateDeviceIOHandle = ioHandleIter->second;
2740 audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
2741 audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle);
2742 IOHandles_.erase(currentActivePort);
2743 streamCollector_.UpdateRendererPipeInfo(rendererChangeInfo->sessionId, PIPE_TYPE_NORMAL_OUT);
2744 }
2745 ResetOffloadMode(rendererChangeInfo->sessionId);
2746 MoveToNewOutputDevice(rendererChangeInfo, descs);
2747 }
2748 }
2749
FetchStreamForA2dpOffload(const bool & requireReset)2750 void AudioPolicyService::FetchStreamForA2dpOffload(const bool &requireReset)
2751 {
2752 vector<unique_ptr<AudioRendererChangeInfo>> rendererChangeInfos;
2753 streamCollector_.GetCurrentRendererChangeInfos(rendererChangeInfos);
2754 AUDIO_INFO_LOG("FetchStreamForA2dpOffload start for %{public}zu stream", rendererChangeInfos.size());
2755 for (auto &rendererChangeInfo : rendererChangeInfos) {
2756 if (!IsRendererStreamRunning(rendererChangeInfo)) {
2757 continue;
2758 }
2759 vector<std::unique_ptr<AudioDeviceDescriptor>> descs =
2760 audioRouterCenter_.FetchOutputDevices(rendererChangeInfo->rendererInfo.streamUsage,
2761 rendererChangeInfo->clientUID);
2762
2763 if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
2764 if (requireReset) {
2765 int32_t ret = ActivateA2dpDevice(descs.front(), rendererChangeInfos);
2766 CHECK_AND_RETURN_LOG(ret == SUCCESS, "activate a2dp [%{public}s] failed",
2767 GetEncryptAddr(descs.front()->macAddress_).c_str());
2768 }
2769 if (rendererChangeInfo->rendererInfo.rendererFlags == AUDIO_FLAG_MMAP) {
2770 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2771 CHECK_AND_RETURN_LOG(gsp != nullptr, "Service proxy unavailable");
2772 std::string identity = IPCSkeleton::ResetCallingIdentity();
2773 gsp->ResetAudioEndpoint();
2774 IPCSkeleton::SetCallingIdentity(identity);
2775 }
2776 FetchStreamForA2dpMchStream(rendererChangeInfo, descs);
2777 }
2778 }
2779 }
2780
IsSameDevice(unique_ptr<AudioDeviceDescriptor> & desc,AudioDeviceDescriptor & deviceInfo)2781 bool AudioPolicyService::IsSameDevice(unique_ptr<AudioDeviceDescriptor> &desc, AudioDeviceDescriptor &deviceInfo)
2782 {
2783 if (desc->networkId_ == deviceInfo.networkId_ && desc->deviceType_ == deviceInfo.deviceType_ &&
2784 desc->macAddress_ == deviceInfo.macAddress_ && desc->connectState_ == deviceInfo.connectState_) {
2785 if (deviceInfo.IsAudioDeviceDescriptor()) {
2786 return true;
2787 }
2788 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
2789 // switch to A2dp
2790 ((deviceInfo.a2dpOffloadFlag_ == A2DP_OFFLOAD && a2dpOffloadFlag_ != A2DP_OFFLOAD) ||
2791 // switch to A2dp offload
2792 (deviceInfo.a2dpOffloadFlag_ != A2DP_OFFLOAD && a2dpOffloadFlag_ == A2DP_OFFLOAD))) {
2793 return false;
2794 }
2795 return true;
2796 } else {
2797 return false;
2798 }
2799 }
2800
IsSameDevice(unique_ptr<AudioDeviceDescriptor> & desc,const AudioDeviceDescriptor & deviceDesc)2801 bool AudioPolicyService::IsSameDevice(unique_ptr<AudioDeviceDescriptor> &desc, const AudioDeviceDescriptor &deviceDesc)
2802 {
2803 if (desc->networkId_ == deviceDesc.networkId_ && desc->deviceType_ == deviceDesc.deviceType_ &&
2804 desc->macAddress_ == deviceDesc.macAddress_ && desc->connectState_ == deviceDesc.connectState_) {
2805 return true;
2806 } else {
2807 return false;
2808 }
2809 }
2810
HandleScoInputDeviceFetched(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioCapturerChangeInfo>> & capturerChangeInfos)2811 int32_t AudioPolicyService::HandleScoInputDeviceFetched(unique_ptr<AudioDeviceDescriptor> &desc,
2812 vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos)
2813 {
2814 #ifdef BLUETOOTH_ENABLE
2815 int32_t ret = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_);
2816 if (ret != SUCCESS) {
2817 AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch input device");
2818 desc->exceptionFlag_ = true;
2819 audioDeviceManager_.UpdateDevicesListInfo(new AudioDeviceDescriptor(*desc), EXCEPTION_FLAG_UPDATE);
2820 FetchInputDevice(capturerChangeInfos);
2821 return ERROR;
2822 }
2823 if (desc->connectState_ == DEACTIVE_CONNECTED || lastAudioScene_ != audioScene_) {
2824 Bluetooth::AudioHfpManager::ConnectScoWithAudioScene(audioScene_);
2825 return SUCCESS;
2826 }
2827 #endif
2828 return SUCCESS;
2829 }
2830
FetchInputDevice(vector<unique_ptr<AudioCapturerChangeInfo>> & capturerChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2831 void AudioPolicyService::FetchInputDevice(vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos,
2832 const AudioStreamDeviceChangeReasonExt reason)
2833 {
2834 Trace trace("AudioPolicyService::FetchInputDevice");
2835 AUDIO_INFO_LOG("Start for %{public}zu stream, connected %{public}s",
2836 capturerChangeInfos.size(), audioDeviceManager_.GetConnDevicesStr().c_str());
2837 bool needUpdateActiveDevice = true;
2838 bool isUpdateActiveDevice = false;
2839 int32_t runningStreamCount = 0;
2840 for (auto &capturerChangeInfo : capturerChangeInfos) {
2841 SourceType sourceType = capturerChangeInfo->capturerInfo.sourceType;
2842 if ((sourceType == SOURCE_TYPE_VIRTUAL_CAPTURE && audioScene_ != AUDIO_SCENE_PHONE_CALL) ||
2843 (sourceType != SOURCE_TYPE_VIRTUAL_CAPTURE && capturerChangeInfo->capturerState != CAPTURER_RUNNING)) {
2844 AUDIO_WARNING_LOG("stream %{public}d not running, no need fetch device", capturerChangeInfo->sessionId);
2845 continue;
2846 }
2847 runningStreamCount++;
2848 unique_ptr<AudioDeviceDescriptor> desc = audioRouterCenter_.FetchInputDevice(sourceType,
2849 capturerChangeInfo->clientUID);
2850 AudioDeviceDescriptor inputDeviceInfo = capturerChangeInfo->inputDeviceInfo;
2851 if (HandleDeviceChangeForFetchInputDevice(desc, capturerChangeInfo) == ERR_NEED_NOT_SWITCH_DEVICE) {
2852 continue;
2853 }
2854 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
2855 BluetoothScoFetch(desc, capturerChangeInfos, sourceType);
2856 }
2857 if (needUpdateActiveDevice) {
2858 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice();
2859 if (!IsSameDevice(desc, tempDesc)) {
2860 WriteInputRouteChangeEvent(desc, reason);
2861 SetCurrenInputDevice(*desc);
2862 AUDIO_DEBUG_LOG("currentActiveInputDevice update %{public}d", GetCurrentInputDeviceType());
2863 isUpdateActiveDevice = true;
2864 }
2865 needUpdateActiveDevice = false;
2866 }
2867 if (NotifyRecreateCapturerStream(isUpdateActiveDevice, capturerChangeInfo, reason)) {
2868 continue;
2869 }
2870 // move sourceoutput to target device
2871 MoveToNewInputDevice(capturerChangeInfo, desc);
2872 AddAudioCapturerMicrophoneDescriptor(capturerChangeInfo->sessionId, desc->deviceType_);
2873 }
2874 if (isUpdateActiveDevice) {
2875 OnPreferredInputDeviceUpdated(GetCurrentInputDeviceType(), ""); // networkId is not used.
2876 }
2877 if (runningStreamCount == 0) {
2878 FetchInputDeviceWhenNoRunningStream();
2879 }
2880 }
2881
HandleDeviceChangeForFetchInputDevice(unique_ptr<AudioDeviceDescriptor> & desc,unique_ptr<AudioCapturerChangeInfo> & capturerChangeInfo)2882 int32_t AudioPolicyService::HandleDeviceChangeForFetchInputDevice(unique_ptr<AudioDeviceDescriptor> &desc,
2883 unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo)
2884 {
2885 if (desc->deviceType_ == DEVICE_TYPE_NONE ||
2886 (IsSameDevice(desc, capturerChangeInfo->inputDeviceInfo) && desc->connectState_ != DEACTIVE_CONNECTED)) {
2887 AUDIO_WARNING_LOG("stream %{public}d device not change, no need move device", capturerChangeInfo->sessionId);
2888 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice();
2889 if (!IsSameDevice(desc, tempDesc) && IsSameDevice(desc, capturerChangeInfo->inputDeviceInfo)) {
2890 SetCurrenInputDevice(*desc);
2891 OnPreferredInputDeviceUpdated(GetCurrentInputDeviceType(), ""); // networkId is not used
2892 UpdateActiveDeviceRoute(GetCurrentInputDeviceType(), DeviceFlag::INPUT_DEVICES_FLAG);
2893 }
2894 return ERR_NEED_NOT_SWITCH_DEVICE;
2895 }
2896 return SUCCESS;
2897 }
2898
BluetoothScoFetch(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioCapturerChangeInfo>> & capturerChangeInfos,SourceType sourceType)2899 void AudioPolicyService::BluetoothScoFetch(unique_ptr<AudioDeviceDescriptor> &desc,
2900 vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos, SourceType sourceType)
2901 {
2902 int32_t ret;
2903 if (sourceType == SOURCE_TYPE_VOICE_RECOGNITION) {
2904 int32_t activeRet = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_);
2905 if (activeRet != SUCCESS) {
2906 AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch input device");
2907 desc->exceptionFlag_ = true;
2908 audioDeviceManager_.UpdateDevicesListInfo(new AudioDeviceDescriptor(*desc), EXCEPTION_FLAG_UPDATE);
2909 FetchInputDevice(capturerChangeInfos);
2910 }
2911 ret = ScoInputDeviceFetchedForRecongnition(true, desc->macAddress_, desc->connectState_);
2912 } else {
2913 ret = HandleScoInputDeviceFetched(desc, capturerChangeInfos);
2914 }
2915 if (ret != SUCCESS) {
2916 AUDIO_ERR_LOG("sco [%{public}s] is not connected yet", GetEncryptAddr(desc->macAddress_).c_str());
2917 }
2918 }
2919
BluetoothScoDisconectForRecongnition()2920 void AudioPolicyService::BluetoothScoDisconectForRecongnition()
2921 {
2922 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice();
2923 AUDIO_INFO_LOG("Recongnition scoCategory: %{public}d, deviceType: %{public}d, scoState: %{public}d",
2924 Bluetooth::AudioHfpManager::GetScoCategory(), tempDesc.deviceType_,
2925 audioDeviceManager_.GetScoState());
2926 if (tempDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
2927 int32_t ret = ScoInputDeviceFetchedForRecongnition(false, tempDesc.macAddress_, tempDesc.connectState_);
2928 CHECK_AND_RETURN_LOG(ret == SUCCESS, "sco [%{public}s] disconnected failed",
2929 GetEncryptAddr(tempDesc.macAddress_).c_str());
2930 }
2931 }
2932
NotifyRecreateCapturerStream(bool isUpdateActiveDevice,const std::unique_ptr<AudioCapturerChangeInfo> & capturerChangeInfo,const AudioStreamDeviceChangeReasonExt reason)2933 bool AudioPolicyService::NotifyRecreateCapturerStream(bool isUpdateActiveDevice,
2934 const std::unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo,
2935 const AudioStreamDeviceChangeReasonExt reason)
2936 {
2937 AUDIO_INFO_LOG("Is update active device: %{public}d, current capturerFlag: %{public}d, origianl flag: %{public}d",
2938 isUpdateActiveDevice, capturerChangeInfo->capturerInfo.capturerFlags,
2939 capturerChangeInfo->capturerInfo.originalFlag);
2940 CHECK_AND_RETURN_RET_LOG(isUpdateActiveDevice, false, "isUpdateActiveDevice is false");
2941 CHECK_AND_RETURN_RET_LOG(capturerChangeInfo->capturerInfo.originalFlag == AUDIO_FLAG_MMAP, false,
2942 "original flag is false");
2943 // Switch between old and new stream as they have different hals
2944 std::string oldDevicePortName = GetSourcePortName(capturerChangeInfo->inputDeviceInfo.deviceType_);
2945 if ((strcmp(oldDevicePortName.c_str(), GetSourcePortName(currentActiveDevice_.deviceType_).c_str())) ||
2946 ((capturerChangeInfo->inputDeviceInfo.networkId_ == LOCAL_NETWORK_ID) ^
2947 (currentActiveDevice_.networkId_ == LOCAL_NETWORK_ID))) {
2948 int32_t streamClass = GetPreferredInputStreamTypeInner(capturerChangeInfo->capturerInfo.sourceType,
2949 currentActiveDevice_.deviceType_, capturerChangeInfo->capturerInfo.originalFlag,
2950 GetCurrentInputDevice().networkId_, capturerChangeInfo->capturerInfo.samplingRate);
2951 TriggerRecreateCapturerStreamCallback(capturerChangeInfo->callerPid,
2952 capturerChangeInfo->sessionId, streamClass, reason);
2953 return true;
2954 }
2955 return false;
2956 }
2957
TriggerRecreateCapturerStreamCallback(int32_t callerPid,int32_t sessionId,int32_t streamFlag,const AudioStreamDeviceChangeReasonExt reason)2958 void AudioPolicyService::TriggerRecreateCapturerStreamCallback(int32_t callerPid, int32_t sessionId, int32_t streamFlag,
2959 const AudioStreamDeviceChangeReasonExt reason)
2960 {
2961 Trace trace("AudioPolicyService::TriggerRecreateCapturerStreamCallback");
2962 AUDIO_WARNING_LOG("Trigger recreate capturer stream, pid: %{public}d, sessionId: %{public}d, flag: %{public}d",
2963 callerPid, sessionId, streamFlag);
2964 if (audioPolicyServerHandler_ != nullptr) {
2965 audioPolicyServerHandler_->SendRecreateCapturerStreamEvent(callerPid, sessionId, streamFlag, reason);
2966 } else {
2967 AUDIO_WARNING_LOG("No audio policy server handler");
2968 }
2969 }
2970
WriteInputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> & desc,const AudioStreamDeviceChangeReason reason)2971 void AudioPolicyService::WriteInputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> &desc,
2972 const AudioStreamDeviceChangeReason reason)
2973 {
2974 int64_t timeStamp = GetCurrentTimeMS();
2975 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
2976 Media::MediaMonitor::AUDIO, Media::MediaMonitor::AUDIO_ROUTE_CHANGE,
2977 Media::MediaMonitor::BEHAVIOR_EVENT);
2978 bean->Add("REASON", static_cast<int32_t>(reason));
2979 bean->Add("TIMESTAMP", static_cast<uint64_t>(timeStamp));
2980 bean->Add("DEVICE_TYPE_BEFORE_CHANGE", GetCurrentInputDeviceType());
2981 bean->Add("DEVICE_TYPE_AFTER_CHANGE", desc->deviceType_);
2982 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
2983 }
2984
FetchDevice(bool isOutputDevice,const AudioStreamDeviceChangeReasonExt reason)2985 void AudioPolicyService::FetchDevice(bool isOutputDevice, const AudioStreamDeviceChangeReasonExt reason)
2986 {
2987 Trace trace("AudioPolicyService::FetchDevice reason:" + std::to_string(static_cast<int>(reason)));
2988 AUDIO_DEBUG_LOG("FetchDevice start");
2989
2990 if (isOutputDevice) {
2991 vector<unique_ptr<AudioRendererChangeInfo>> rendererChangeInfos;
2992 streamCollector_.GetCurrentRendererChangeInfos(rendererChangeInfos);
2993 FetchOutputDevice(rendererChangeInfos, reason);
2994 } else {
2995 vector<unique_ptr<AudioCapturerChangeInfo>> capturerChangeInfos;
2996 streamCollector_.GetCurrentCapturerChangeInfos(capturerChangeInfos);
2997 FetchInputDevice(capturerChangeInfos, reason);
2998 }
2999 }
3000
SetMicrophoneMute(bool isMute)3001 int32_t AudioPolicyService::SetMicrophoneMute(bool isMute)
3002 {
3003 AUDIO_DEBUG_LOG("SetMicrophoneMute state[%{public}d]", isMute);
3004 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3005 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
3006 std::string identity = IPCSkeleton::ResetCallingIdentity();
3007 int32_t ret = gsp->SetMicrophoneMute(isMute | isMicrophoneMutePersistent_);
3008 IPCSkeleton::SetCallingIdentity(identity);
3009 if (ret == SUCCESS) {
3010 isMicrophoneMuteTemporary_ = isMute;
3011 streamCollector_.UpdateCapturerInfoMuteStatus(0, isMicrophoneMuteTemporary_ | isMicrophoneMutePersistent_);
3012 }
3013 return ret;
3014 }
3015
SetMicrophoneMutePersistent(const bool isMute)3016 int32_t AudioPolicyService::SetMicrophoneMutePersistent(const bool isMute)
3017 {
3018 AUDIO_DEBUG_LOG("state[%{public}d]", isMute);
3019 isMicrophoneMutePersistent_ = isMute;
3020 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3021 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
3022 std::string identity = IPCSkeleton::ResetCallingIdentity();
3023 int32_t ret = gsp->SetMicrophoneMute(isMicrophoneMuteTemporary_ | isMicrophoneMutePersistent_);
3024 IPCSkeleton::SetCallingIdentity(identity);
3025 if (ret == SUCCESS) {
3026 AUDIO_INFO_LOG("UpdateCapturerInfoMuteStatus when set mic mute state persistent.");
3027 streamCollector_.UpdateCapturerInfoMuteStatus(0, isMicrophoneMuteTemporary_|isMicrophoneMutePersistent_);
3028 }
3029 ret = audioPolicyManager_.SetPersistMicMuteState(isMicrophoneMutePersistent_);
3030 if (ret != SUCCESS) {
3031 AUDIO_ERR_LOG("Failed to save the persistent microphone mute status in setting database.");
3032 return ERROR;
3033 }
3034 return ret;
3035 }
3036
GetPersistentMicMuteState()3037 bool AudioPolicyService::GetPersistentMicMuteState()
3038 {
3039 return isMicrophoneMutePersistent_;
3040 }
3041
InitPersistentMicrophoneMuteState(bool & isMute)3042 int32_t AudioPolicyService::InitPersistentMicrophoneMuteState(bool &isMute)
3043 {
3044 int32_t ret = audioPolicyManager_.GetPersistMicMuteState(isMute);
3045 if (ret != SUCCESS) {
3046 AUDIO_ERR_LOG("GetPersistMicMuteState failed.");
3047 return ret;
3048 }
3049 // Ensure persistent mic mute state takes effect when first startup
3050 isMicrophoneMutePersistent_ = isMute;
3051 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3052 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
3053 std::string identity = IPCSkeleton::ResetCallingIdentity();
3054 ret = gsp->SetMicrophoneMute(isMicrophoneMutePersistent_);
3055 IPCSkeleton::SetCallingIdentity(identity);
3056 if (ret == SUCCESS) {
3057 AUDIO_INFO_LOG("UpdateCapturerInfoMuteStatus when audio service restart.");
3058 streamCollector_.UpdateCapturerInfoMuteStatus(0, isMicrophoneMutePersistent_);
3059 }
3060 return ret;
3061 }
3062
IsMicrophoneMute()3063 bool AudioPolicyService::IsMicrophoneMute()
3064 {
3065 return isMicrophoneMuteTemporary_ | isMicrophoneMutePersistent_;
3066 }
3067
SetSystemSoundUri(const std::string & key,const std::string & uri)3068 int32_t AudioPolicyService::SetSystemSoundUri(const std::string &key, const std::string &uri)
3069 {
3070 return audioPolicyManager_.SetSystemSoundUri(key, uri);
3071 }
3072
GetSystemSoundUri(const std::string & key)3073 std::string AudioPolicyService::GetSystemSoundUri(const std::string &key)
3074 {
3075 return audioPolicyManager_.GetSystemSoundUri(key);
3076 }
3077
SwitchActiveA2dpDevice(const sptr<AudioDeviceDescriptor> & deviceDescriptor)3078 int32_t AudioPolicyService::SwitchActiveA2dpDevice(const sptr<AudioDeviceDescriptor> &deviceDescriptor)
3079 {
3080 auto iter = connectedA2dpDeviceMap_.find(deviceDescriptor->macAddress_);
3081 CHECK_AND_RETURN_RET_LOG(iter != connectedA2dpDeviceMap_.end(), ERR_INVALID_PARAM,
3082 "SelectNewDevice: the target A2DP device doesn't exist.");
3083 int32_t result = ERROR;
3084 #ifdef BLUETOOTH_ENABLE
3085 AUDIO_INFO_LOG("a2dp device name [%{public}s]", (deviceDescriptor->deviceName_).c_str());
3086 std::string lastActiveA2dpDevice = activeBTDevice_;
3087 activeBTDevice_ = deviceDescriptor->macAddress_;
3088 DeviceType lastDevice = audioPolicyManager_.GetActiveDevice();
3089 audioPolicyManager_.SetActiveDevice(DEVICE_TYPE_BLUETOOTH_A2DP);
3090
3091 {
3092 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
3093 if (Bluetooth::AudioA2dpManager::GetActiveA2dpDevice() == deviceDescriptor->macAddress_ &&
3094 IOHandles_.find(BLUETOOTH_SPEAKER) != IOHandles_.end()) {
3095 AUDIO_WARNING_LOG("a2dp device [%{public}s] is already active",
3096 GetEncryptAddr(deviceDescriptor->macAddress_).c_str());
3097 return SUCCESS;
3098 }
3099 }
3100
3101 result = Bluetooth::AudioA2dpManager::SetActiveA2dpDevice(deviceDescriptor->macAddress_);
3102 if (result != SUCCESS) {
3103 activeBTDevice_ = lastActiveA2dpDevice;
3104 audioPolicyManager_.SetActiveDevice(lastDevice);
3105 AUDIO_ERR_LOG("Active [%{public}s] failed, using original [%{public}s] device",
3106 GetEncryptAddr(activeBTDevice_).c_str(), GetEncryptAddr(lastActiveA2dpDevice).c_str());
3107 return result;
3108 }
3109
3110 result = LoadA2dpModule();
3111 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "LoadA2dpModule failed %{public}d", result);
3112 #endif
3113 return result;
3114 }
3115
UnloadA2dpModule()3116 void AudioPolicyService::UnloadA2dpModule()
3117 {
3118 MuteDefaultSinkPort();
3119 ClosePortAndEraseIOHandle(BLUETOOTH_SPEAKER);
3120 }
3121
LoadA2dpModule()3122 int32_t AudioPolicyService::LoadA2dpModule()
3123 {
3124 std::list<AudioModuleInfo> moduleInfoList;
3125 {
3126 auto primaryModulesPos = deviceClassInfo_.find(ClassType::TYPE_A2DP);
3127 CHECK_AND_RETURN_RET_LOG(primaryModulesPos != deviceClassInfo_.end(), ERR_OPERATION_FAILED,
3128 "A2dp module is not exist in the configuration file");
3129 moduleInfoList = primaryModulesPos->second;
3130 }
3131 for (auto &moduleInfo : moduleInfoList) {
3132 AudioStreamInfo audioStreamInfo = {};
3133 GetActiveDeviceStreamInfo(DEVICE_TYPE_BLUETOOTH_A2DP, audioStreamInfo);
3134
3135 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
3136 if (IOHandles_.find(moduleInfo.name) == IOHandles_.end()) {
3137 // a2dp device connects for the first time
3138 AUDIO_DEBUG_LOG("Load a2dp module [%{public}s]", moduleInfo.name.c_str());
3139 uint32_t bufferSize = (audioStreamInfo.samplingRate * GetSampleFormatValue(audioStreamInfo.format) *
3140 audioStreamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR);
3141 AUDIO_INFO_LOG("a2dp rate: %{public}d, format: %{public}d, channel: %{public}d",
3142 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
3143 moduleInfo.channels = to_string(audioStreamInfo.channels);
3144 moduleInfo.rate = to_string(audioStreamInfo.samplingRate);
3145 moduleInfo.format = ConvertToHDIAudioFormat(audioStreamInfo.format);
3146 moduleInfo.bufferSize = to_string(bufferSize);
3147 moduleInfo.renderInIdleState = "1";
3148 moduleInfo.sinkLatency = "0";
3149
3150 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
3151 CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
3152 "LoadA2dpModule: OpenAudioPort failed %{public}d", ioHandle);
3153 IOHandles_[moduleInfo.name] = ioHandle;
3154 } else {
3155 // At least one a2dp device is already connected. A new a2dp device is connecting.
3156 // Need to reload a2dp module when switching to a2dp device.
3157 int32_t result = ReloadA2dpAudioPort(moduleInfo, audioStreamInfo);
3158 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "ReloadA2dpAudioPort failed %{public}d", result);
3159 }
3160 }
3161
3162 return SUCCESS;
3163 }
3164
ReloadA2dpAudioPort(AudioModuleInfo & moduleInfo,const AudioStreamInfo & audioStreamInfo)3165 int32_t AudioPolicyService::ReloadA2dpAudioPort(AudioModuleInfo &moduleInfo, const AudioStreamInfo& audioStreamInfo)
3166 {
3167 AUDIO_INFO_LOG("switch device from a2dp to another a2dp, reload a2dp module");
3168 MuteDefaultSinkPort();
3169
3170 // Firstly, unload the existing a2dp sink.
3171 AudioIOHandle activateDeviceIOHandle = IOHandles_[BLUETOOTH_SPEAKER];
3172 int32_t result = audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle);
3173 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result,
3174 "ReloadA2dpAudioPort: CloseAudioPort failed %{public}d", result);
3175
3176 // Load a2dp sink module again with the configuration of active a2dp device.
3177 uint32_t bufferSize = (audioStreamInfo.samplingRate * GetSampleFormatValue(audioStreamInfo.format) *
3178 audioStreamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR);
3179 AUDIO_DEBUG_LOG("ReloadA2dpAudioPort: a2dp rate: %{public}d, format: %{public}d, channel: %{public}d",
3180 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
3181 moduleInfo.channels = to_string(audioStreamInfo.channels);
3182 moduleInfo.rate = to_string(audioStreamInfo.samplingRate);
3183 moduleInfo.format = ConvertToHDIAudioFormat(audioStreamInfo.format);
3184 moduleInfo.bufferSize = to_string(bufferSize);
3185 moduleInfo.renderInIdleState = "1";
3186 moduleInfo.sinkLatency = "0";
3187 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
3188 CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
3189 "ReloadA2dpAudioPort: OpenAudioPort failed %{public}d", ioHandle);
3190 IOHandles_[moduleInfo.name] = ioHandle;
3191 return SUCCESS;
3192 }
3193
LoadUsbModule(string deviceInfo,DeviceRole deviceRole)3194 int32_t AudioPolicyService::LoadUsbModule(string deviceInfo, DeviceRole deviceRole)
3195 {
3196 std::list<AudioModuleInfo> moduleInfoList;
3197 {
3198 auto usbModulesPos = deviceClassInfo_.find(ClassType::TYPE_USB);
3199 if (usbModulesPos == deviceClassInfo_.end()) {
3200 return ERR_OPERATION_FAILED;
3201 }
3202 moduleInfoList = usbModulesPos->second;
3203 }
3204 for (auto &moduleInfo : moduleInfoList) {
3205 DeviceRole configRole = moduleInfo.role == "sink" ? OUTPUT_DEVICE : INPUT_DEVICE;
3206 AUDIO_INFO_LOG("[module_load]::load module[%{public}s], load role[%{public}d] config role[%{public}d]",
3207 moduleInfo.name.c_str(), deviceRole, configRole);
3208 if (configRole != deviceRole) {continue;}
3209 GetUsbModuleInfo(deviceInfo, moduleInfo);
3210 int32_t ret = OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
3211 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret,
3212 "Load usb %{public}s failed %{public}d", moduleInfo.role.c_str(), ret);
3213 }
3214
3215 return SUCCESS;
3216 }
3217
LoadDpModule(string deviceInfo)3218 int32_t AudioPolicyService::LoadDpModule(string deviceInfo)
3219 {
3220 AUDIO_INFO_LOG("LoadDpModule");
3221 std::list<AudioModuleInfo> moduleInfoList;
3222 {
3223 auto usbModulesPos = deviceClassInfo_.find(ClassType::TYPE_DP);
3224 if (usbModulesPos == deviceClassInfo_.end()) {
3225 return ERR_OPERATION_FAILED;
3226 }
3227 moduleInfoList = usbModulesPos->second;
3228 }
3229 for (auto &moduleInfo : moduleInfoList) {
3230 AUDIO_INFO_LOG("[module_load]::load module[%{public}s]", moduleInfo.name.c_str());
3231 if (IOHandles_.find(moduleInfo.name) == IOHandles_.end()) {
3232 GetDPModuleInfo(moduleInfo, deviceInfo);
3233 return OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
3234 }
3235 }
3236
3237 return SUCCESS;
3238 }
3239
LoadDefaultUsbModule(DeviceRole deviceRole)3240 int32_t AudioPolicyService::LoadDefaultUsbModule(DeviceRole deviceRole)
3241 {
3242 AUDIO_INFO_LOG("LoadDefaultUsbModule");
3243
3244 std::list<AudioModuleInfo> moduleInfoList;
3245 {
3246 auto usbModulesPos = deviceClassInfo_.find(ClassType::TYPE_USB);
3247 if (usbModulesPos == deviceClassInfo_.end()) {
3248 return ERR_OPERATION_FAILED;
3249 }
3250 moduleInfoList = usbModulesPos->second;
3251 }
3252 for (auto &moduleInfo : moduleInfoList) {
3253 DeviceRole configRole = moduleInfo.role == "sink" ? OUTPUT_DEVICE : INPUT_DEVICE;
3254 AUDIO_INFO_LOG("[module_load]::load default module[%{public}s], load role[%{public}d] config role[%{public}d]",
3255 moduleInfo.name.c_str(), deviceRole, configRole);
3256 if (configRole != deviceRole) {continue;}
3257 int32_t ret = OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
3258 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret,
3259 "Load usb %{public}s failed %{public}d", moduleInfo.role.c_str(), ret);
3260 }
3261
3262 return SUCCESS;
3263 }
3264
HandleActiveDevice(DeviceType deviceType)3265 int32_t AudioPolicyService::HandleActiveDevice(DeviceType deviceType)
3266 {
3267 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
3268 if (GetVolumeGroupType(curOutputDeviceType) != GetVolumeGroupType(deviceType)) {
3269 SetVolumeForSwitchDevice(deviceType);
3270 }
3271 if (isUpdateRouteSupported_) {
3272 UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG);
3273 }
3274 std::string sinkPortName = GetSinkPortName(deviceType);
3275 std::string sourcePortName = GetSourcePortName(deviceType);
3276 if (sinkPortName == PORT_NONE && sourcePortName == PORT_NONE) {
3277 AUDIO_ERR_LOG("HandleActiveDevice failed for sinkPortName and sourcePortName are none");
3278 return ERR_OPERATION_FAILED;
3279 }
3280 if (sinkPortName != PORT_NONE) {
3281 GetSinkIOHandle(deviceType);
3282 audioPolicyManager_.SuspendAudioDevice(sinkPortName, false);
3283 }
3284 if (sourcePortName != PORT_NONE) {
3285 GetSourceIOHandle(deviceType);
3286 audioPolicyManager_.SuspendAudioDevice(sourcePortName, false);
3287 }
3288 UpdateInputDeviceInfo(deviceType);
3289
3290 return SUCCESS;
3291 }
3292
HandleArmUsbDevice(DeviceType deviceType,DeviceRole deviceRole,const std::string & address)3293 int32_t AudioPolicyService::HandleArmUsbDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address)
3294 {
3295 Trace trace("AudioPolicyService::HandleArmUsbDevice");
3296
3297 if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) {
3298 string deviceInfo = "";
3299 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3300 if (gsp != nullptr) {
3301 std::string identity = IPCSkeleton::ResetCallingIdentity();
3302 deviceInfo = gsp->GetAudioParameter(LOCAL_NETWORK_ID, USB_DEVICE, address);
3303 IPCSkeleton::SetCallingIdentity(identity);
3304 AUDIO_INFO_LOG("device info from usb hal is %{public}s", deviceInfo.c_str());
3305 }
3306 int32_t ret;
3307 if (!deviceInfo.empty()) {
3308 ret = LoadUsbModule(deviceInfo, deviceRole);
3309 } else {
3310 ret = LoadDefaultUsbModule(deviceRole);
3311 }
3312 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "load usb role[%{public}d] module failed", deviceRole);
3313
3314 std::string activePort = GetSinkPortName(DEVICE_TYPE_USB_ARM_HEADSET);
3315 AUDIO_DEBUG_LOG("port %{public}s, active arm usb device", activePort.c_str());
3316 } else if (GetCurrentOutputDeviceType() == DEVICE_TYPE_USB_HEADSET) {
3317 std::string activePort = GetSinkPortName(DEVICE_TYPE_USB_ARM_HEADSET);
3318 audioPolicyManager_.SuspendAudioDevice(activePort, true);
3319 }
3320
3321 return SUCCESS;
3322 }
3323
RehandlePnpDevice(DeviceType deviceType,DeviceRole deviceRole,const std::string & address)3324 int32_t AudioPolicyService::RehandlePnpDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address)
3325 {
3326 Trace trace("AudioPolicyService::RehandlePnpDevice");
3327
3328 // Maximum number of attempts, preventing situations where hal has not yet finished coming online.
3329 int32_t maxRetries = 3;
3330 int32_t retryCount = 0;
3331 int32_t ret = ERROR;
3332 bool isConnected = true;
3333 while (retryCount < maxRetries) {
3334 retryCount++;
3335 AUDIO_INFO_LOG("rehandle device[%{public}d], retry count[%{public}d]", deviceType, retryCount);
3336
3337 ret = HandleSpecialDeviceType(deviceType, isConnected, address);
3338 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Rehandle special device type failed");
3339 if (deviceType == DEVICE_TYPE_USB_HEADSET) {
3340 AUDIO_INFO_LOG("Hifi device, don't load module");
3341 hasArmUsbDevice_ = false;
3342 return ret;
3343 }
3344 if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) {
3345 if (HandleArmUsbDevice(deviceType, deviceRole, address) == SUCCESS) {
3346 return SUCCESS;
3347 }
3348 } else if (deviceType == DEVICE_TYPE_DP) {
3349 if (HandleDpDevice(deviceType, address) == SUCCESS) {
3350 return SUCCESS;
3351 }
3352 }
3353 usleep(REHANDLE_DEVICE_RETRY_INTERVAL_IN_MICROSECONDS);
3354 }
3355
3356 AUDIO_ERR_LOG("rehandle device[%{public}d] failed", deviceType);
3357 return ERROR;
3358 }
3359
GetModuleInfo(ClassType classType,std::string & moduleInfoStr)3360 int32_t AudioPolicyService::GetModuleInfo(ClassType classType, std::string &moduleInfoStr)
3361 {
3362 std::list<AudioModuleInfo> moduleInfoList;
3363 {
3364 auto modulesPos = deviceClassInfo_.find(classType);
3365 if (modulesPos == deviceClassInfo_.end()) {
3366 AUDIO_ERR_LOG("find %{public}d type failed", classType);
3367 return ERR_OPERATION_FAILED;
3368 }
3369 moduleInfoList = modulesPos->second;
3370 }
3371 moduleInfoStr = audioPolicyManager_.GetModuleArgs(*moduleInfoList.begin());
3372 return SUCCESS;
3373 }
3374
HandleDpDevice(DeviceType deviceType,const std::string & address)3375 int32_t AudioPolicyService::HandleDpDevice(DeviceType deviceType, const std::string &address)
3376 {
3377 Trace trace("AudioPolicyService::HandleDpDevice");
3378 if (deviceType == DEVICE_TYPE_DP) {
3379 std::string defaulyDPInfo = "";
3380 std::string getDPInfo = "";
3381 GetModuleInfo(ClassType::TYPE_DP, defaulyDPInfo);
3382 CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
3383 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3384 if (gsp != nullptr) {
3385 std::string identity = IPCSkeleton::ResetCallingIdentity();
3386 getDPInfo = gsp->GetAudioParameter(LOCAL_NETWORK_ID, GET_DP_DEVICE_INFO,
3387 defaulyDPInfo + " address=" + address + " ");
3388 IPCSkeleton::SetCallingIdentity(identity);
3389 AUDIO_DEBUG_LOG("device info from dp hal is \n defaulyDPInfo:%{public}s", defaulyDPInfo.c_str());
3390 }
3391 getDPInfo = getDPInfo.empty() ? defaulyDPInfo : getDPInfo;
3392 int32_t ret = LoadDpModule(getDPInfo);
3393 if (ret != SUCCESS) {
3394 AUDIO_ERR_LOG ("load dp module failed");
3395 return ERR_OPERATION_FAILED;
3396 }
3397 std::string activePort = GetSinkPortName(DEVICE_TYPE_DP);
3398 AUDIO_INFO_LOG("port %{public}s, active dp device", activePort.c_str());
3399 } else if (GetCurrentOutputDeviceType() == DEVICE_TYPE_DP) {
3400 std::string activePort = GetSinkPortName(DEVICE_TYPE_DP);
3401 audioPolicyManager_.SuspendAudioDevice(activePort, true);
3402 }
3403
3404 return SUCCESS;
3405 }
3406
UnmutePortAfterMuteDuration(int32_t muteDuration,std::string portName,DeviceType deviceType)3407 void AudioPolicyService::UnmutePortAfterMuteDuration(int32_t muteDuration, std::string portName, DeviceType deviceType)
3408 {
3409 Trace trace("UnmutePortAfterMuteDuration:" + portName + " for " + std::to_string(muteDuration) + "us");
3410
3411 if (!moveDeviceFinished_.load()) {
3412 std::unique_lock<std::mutex> lock(moveDeviceMutex_);
3413 bool loadWaiting = moveDeviceCV_.wait_for(lock,
3414 std::chrono::milliseconds(WAIT_MOVE_DEVICE_MUTE_TIME_MAX_MS),
3415 [this] { return moveDeviceFinished_.load(); }
3416 );
3417 if (!loadWaiting) {
3418 AUDIO_ERR_LOG("move device time out");
3419 }
3420 }
3421 AUDIO_INFO_LOG("%{public}d us for device type[%{public}s]", muteDuration, portName.c_str());
3422
3423 usleep(muteDuration);
3424 if (sinkPortStrToClassStrMap_.count(portName) > 0) {
3425 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3426 if (gsp != nullptr) {
3427 std::string identity = IPCSkeleton::ResetCallingIdentity();
3428 gsp->SetSinkMuteForSwitchDevice(sinkPortStrToClassStrMap_.at(portName), muteDuration, false);
3429 IPCSkeleton::SetCallingIdentity(identity);
3430 }
3431 } else {
3432 audioPolicyManager_.SetSinkMute(portName, false);
3433 }
3434 }
3435
ActivateNewDevice(std::string networkId,DeviceType deviceType,bool isRemote)3436 int32_t AudioPolicyService::ActivateNewDevice(std::string networkId, DeviceType deviceType, bool isRemote)
3437 {
3438 if (isRemote) {
3439 AudioModuleInfo moduleInfo = ConstructRemoteAudioModuleInfo(networkId, GetDeviceRole(deviceType), deviceType);
3440 std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(deviceType));
3441 OpenPortAndInsertIOHandle(moduleName, moduleInfo);
3442 }
3443 return SUCCESS;
3444 }
3445
SetDeviceActive(InternalDeviceType deviceType,bool active)3446 int32_t AudioPolicyService::SetDeviceActive(InternalDeviceType deviceType, bool active)
3447 {
3448 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
3449
3450 AUDIO_WARNING_LOG("Device type[%{public}d] flag[%{public}d]", deviceType, active);
3451 CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
3452
3453 // Activate new device if its already connected
3454 auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &desc) {
3455 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "SetDeviceActive::Invalid device descriptor");
3456 return ((deviceType == desc->deviceType_) || (deviceType == DEVICE_TYPE_FILE_SINK));
3457 };
3458
3459 vector<unique_ptr<AudioDeviceDescriptor>> callDevices = GetAvailableDevicesInner(CALL_OUTPUT_DEVICES);
3460 std::vector<sptr<AudioDeviceDescriptor>> deviceList = {};
3461 for (auto &desc : callDevices) {
3462 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc);
3463 deviceList.push_back(devDesc);
3464 }
3465
3466 auto itr = std::find_if(deviceList.begin(), deviceList.end(), isPresent);
3467 CHECK_AND_RETURN_RET_LOG(itr != deviceList.end(), ERR_OPERATION_FAILED,
3468 "Requested device not available %{public}d ", deviceType);
3469 if (!active) {
3470 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor());
3471 #ifdef BLUETOOTH_ENABLE
3472 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_SCO &&
3473 deviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
3474 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO,
3475 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT);
3476 Bluetooth::AudioHfpManager::DisconnectSco();
3477 }
3478 #endif
3479 } else {
3480 SetPreferredDevice(AUDIO_CALL_RENDER, *itr);
3481 #ifdef BLUETOOTH_ENABLE
3482 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_SCO &&
3483 deviceType != DEVICE_TYPE_BLUETOOTH_SCO) {
3484 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO,
3485 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT);
3486 Bluetooth::AudioHfpManager::DisconnectSco();
3487 }
3488 if (GetCurrentOutputDeviceType() != DEVICE_TYPE_BLUETOOTH_SCO &&
3489 deviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
3490 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO,
3491 (*itr)->macAddress_, USER_SELECT_BT);
3492 }
3493 #endif
3494 }
3495 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
3496 return SUCCESS;
3497 }
3498
IsDeviceActive(InternalDeviceType deviceType)3499 bool AudioPolicyService::IsDeviceActive(InternalDeviceType deviceType)
3500 {
3501 AUDIO_DEBUG_LOG("type [%{public}d]", deviceType);
3502 CHECK_AND_RETURN_RET(GetCurrentOutputDeviceNetworkId() == LOCAL_NETWORK_ID, false);
3503 return GetCurrentOutputDeviceType() == deviceType;
3504 }
3505
GetActiveOutputDevice()3506 DeviceType AudioPolicyService::GetActiveOutputDevice()
3507 {
3508 return GetCurrentOutputDeviceType();
3509 }
3510
GetActiveOutputDeviceDescriptor()3511 unique_ptr<AudioDeviceDescriptor> AudioPolicyService::GetActiveOutputDeviceDescriptor()
3512 {
3513 return make_unique<AudioDeviceDescriptor>(GetCurrentOutputDevice());
3514 }
3515
GetActiveInputDevice()3516 DeviceType AudioPolicyService::GetActiveInputDevice()
3517 {
3518 return GetCurrentInputDeviceType();
3519 }
3520
SetRingerMode(AudioRingerMode ringMode)3521 int32_t AudioPolicyService::SetRingerMode(AudioRingerMode ringMode)
3522 {
3523 int32_t result = audioPolicyManager_.SetRingerMode(ringMode);
3524 if (result == SUCCESS) {
3525 if (Util::IsRingerAudioScene(audioScene_)) {
3526 AUDIO_INFO_LOG("fetch output device after switch new ringmode.");
3527 FetchDevice(true);
3528 }
3529 Volume vol = {false, 1.0f, 0};
3530 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
3531 vol.isMute = (ringMode == RINGER_MODE_NORMAL) ? false : true;
3532 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevel(STREAM_RING));
3533 vol.volumeFloat = GetSystemVolumeInDb(STREAM_RING, vol.volumeInt, curOutputDeviceType);
3534 SetSharedVolume(STREAM_RING, curOutputDeviceType, vol);
3535 }
3536 return result;
3537 }
3538
GetRingerMode() const3539 AudioRingerMode AudioPolicyService::GetRingerMode() const
3540 {
3541 return audioPolicyManager_.GetRingerMode();
3542 }
3543
SetAudioScene(AudioScene audioScene)3544 int32_t AudioPolicyService::SetAudioScene(AudioScene audioScene)
3545 {
3546 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
3547
3548 AUDIO_INFO_LOG("Set audio scene start %{public}d", audioScene);
3549 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3550 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
3551
3552 lastAudioScene_ = audioScene_;
3553 audioScene_ = audioScene;
3554 Bluetooth::AudioHfpManager::SetAudioSceneFromPolicy(audioScene_);
3555 if (lastAudioScene_ != AUDIO_SCENE_DEFAULT && audioScene_ == AUDIO_SCENE_DEFAULT) {
3556 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor());
3557 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor());
3558 #ifdef BLUETOOTH_ENABLE
3559 Bluetooth::AudioHfpManager::DisconnectSco();
3560 #endif
3561 }
3562 if (audioScene_ == AUDIO_SCENE_DEFAULT) {
3563 ClearScoDeviceSuspendState();
3564 }
3565
3566 // fetch input&output device
3567 FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::SET_AUDIO_SCENE);
3568 FetchDevice(false);
3569
3570 std::vector<DeviceType> activeOutputDevices;
3571 bool haveArmUsbDevice = false;
3572 DealAudioSceneOutputDevices(audioScene, activeOutputDevices, haveArmUsbDevice);
3573 // mute primary when play music and ring
3574 if (activeOutputDevices.size() > 1 && IsStreamActive(STREAM_MUSIC)) {
3575 MuteSinkPort(PRIMARY_SPEAKER, SET_BT_ABS_SCENE_DELAY_MS, true);
3576 }
3577 int32_t result = SUCCESS;
3578 std::string identity = IPCSkeleton::ResetCallingIdentity();
3579 if (haveArmUsbDevice) {
3580 result = gsp->SetAudioScene(audioScene, activeOutputDevices, DEVICE_TYPE_USB_ARM_HEADSET,
3581 a2dpOffloadFlag_);
3582 } else {
3583 result = gsp->SetAudioScene(audioScene, activeOutputDevices, GetCurrentInputDeviceType(),
3584 a2dpOffloadFlag_);
3585 }
3586 IPCSkeleton::SetCallingIdentity(identity);
3587 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "SetAudioScene failed [%{public}d]", result);
3588
3589 if (audioScene_ == AUDIO_SCENE_PHONE_CALL) {
3590 // Make sure the STREAM_VOICE_CALL volume is set before the calling starts.
3591 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL));
3592 } else {
3593 SetVoiceRingtoneMute(false);
3594 }
3595
3596 return SUCCESS;
3597 }
3598
AddEarpiece()3599 void AudioPolicyService::AddEarpiece()
3600 {
3601 if (!hasEarpiece_) {
3602 return;
3603 }
3604 sptr<AudioDeviceDescriptor> audioDescriptor =
3605 new (std::nothrow) AudioDeviceDescriptor(DEVICE_TYPE_EARPIECE, OUTPUT_DEVICE);
3606 CHECK_AND_RETURN_LOG(audioDescriptor != nullptr, "Create earpiect device descriptor failed");
3607
3608 std::lock_guard<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_);
3609 // Use speaker streaminfo for earpiece cap
3610 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(),
3611 [](const sptr<AudioDeviceDescriptor> &devDesc) {
3612 CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor");
3613 return (devDesc->deviceType_ == DEVICE_TYPE_SPEAKER);
3614 });
3615 if (itr != connectedDevices_.end()) {
3616 audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0);
3617 }
3618 audioDescriptor->deviceId_ = startDeviceId++;
3619 UpdateDisplayName(audioDescriptor);
3620 audioDeviceManager_.AddNewDevice(audioDescriptor);
3621 connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
3622 AUDIO_INFO_LOG("Add earpiece to device list");
3623 }
3624
GetAudioScene(bool hasSystemPermission) const3625 AudioScene AudioPolicyService::GetAudioScene(bool hasSystemPermission) const
3626 {
3627 AUDIO_DEBUG_LOG("GetAudioScene return value: %{public}d", audioScene_);
3628 if (!hasSystemPermission) {
3629 switch (audioScene_) {
3630 case AUDIO_SCENE_CALL_START:
3631 case AUDIO_SCENE_CALL_END:
3632 return AUDIO_SCENE_DEFAULT;
3633 default:
3634 break;
3635 }
3636 }
3637 return audioScene_;
3638 }
3639
GetLastAudioScene() const3640 AudioScene AudioPolicyService::GetLastAudioScene() const
3641 {
3642 return lastAudioScene_;
3643 }
3644
OnUpdateRouteSupport(bool isSupported)3645 void AudioPolicyService::OnUpdateRouteSupport(bool isSupported)
3646 {
3647 isUpdateRouteSupported_ = isSupported;
3648 }
3649
GetActiveDeviceStreamInfo(DeviceType deviceType,AudioStreamInfo & streamInfo)3650 bool AudioPolicyService::GetActiveDeviceStreamInfo(DeviceType deviceType, AudioStreamInfo &streamInfo)
3651 {
3652 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_);
3653 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
3654 auto configInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_);
3655 if (configInfoPos != connectedA2dpDeviceMap_.end()) {
3656 streamInfo.samplingRate = *configInfoPos->second.streamInfo.samplingRate.rbegin();
3657 streamInfo.format = configInfoPos->second.streamInfo.format;
3658 streamInfo.channels = *configInfoPos->second.streamInfo.channels.rbegin();
3659 return true;
3660 }
3661 }
3662
3663 return false;
3664 }
3665
IsConfigurationUpdated(DeviceType deviceType,const AudioStreamInfo & streamInfo)3666 bool AudioPolicyService::IsConfigurationUpdated(DeviceType deviceType, const AudioStreamInfo &streamInfo)
3667 {
3668 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
3669 AudioStreamInfo audioStreamInfo = {};
3670 if (GetActiveDeviceStreamInfo(deviceType, audioStreamInfo)) {
3671 AUDIO_DEBUG_LOG("Device configurations current rate: %{public}d, format: %{public}d, channel: %{public}d",
3672 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
3673 AUDIO_DEBUG_LOG("Device configurations updated rate: %{public}d, format: %{public}d, channel: %{public}d",
3674 streamInfo.samplingRate, streamInfo.format, streamInfo.channels);
3675 if ((audioStreamInfo.samplingRate != streamInfo.samplingRate)
3676 || (audioStreamInfo.channels != streamInfo.channels)
3677 || (audioStreamInfo.format != streamInfo.format)) {
3678 return true;
3679 }
3680 }
3681 }
3682
3683 return false;
3684 }
3685
CheckAndNotifyUserSelectedDevice(const sptr<AudioDeviceDescriptor> & deviceDescriptor)3686 void AudioPolicyService::CheckAndNotifyUserSelectedDevice(const sptr<AudioDeviceDescriptor> &deviceDescriptor)
3687 {
3688 unique_ptr<AudioDeviceDescriptor> userSelectedMediaDevice = audioStateManager_.GetPreferredMediaRenderDevice();
3689 unique_ptr<AudioDeviceDescriptor> userSelectedCallDevice = audioStateManager_.GetPreferredCallRenderDevice();
3690 if (userSelectedMediaDevice != nullptr
3691 && userSelectedMediaDevice->connectState_ == VIRTUAL_CONNECTED
3692 && deviceDescriptor->IsSameDeviceDesc(*userSelectedMediaDevice)) {
3693 NotifyUserSelectionEventToBt(deviceDescriptor);
3694 }
3695 if (userSelectedCallDevice != nullptr
3696 && userSelectedCallDevice->connectState_ == VIRTUAL_CONNECTED
3697 && deviceDescriptor->IsSameDeviceDesc(*userSelectedCallDevice)) {
3698 NotifyUserSelectionEventToBt(deviceDescriptor);
3699 }
3700 }
3701
UpdateConnectedDevicesWhenConnectingForOutputDevice(const AudioDeviceDescriptor & updatedDesc,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)3702 void AudioPolicyService::UpdateConnectedDevicesWhenConnectingForOutputDevice(
3703 const AudioDeviceDescriptor &updatedDesc, std::vector<sptr<AudioDeviceDescriptor>> &descForCb)
3704 {
3705 AUDIO_INFO_LOG("Filling output device for %{public}d", updatedDesc.deviceType_);
3706
3707 sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(updatedDesc);
3708 audioDescriptor->deviceRole_ = OUTPUT_DEVICE;
3709 // Use speaker streaminfo for all output devices cap
3710 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(),
3711 [](const sptr<AudioDeviceDescriptor> &devDesc) {
3712 CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor");
3713 return (devDesc->deviceType_ == DEVICE_TYPE_SPEAKER);
3714 });
3715 if (itr != connectedDevices_.end()) {
3716 audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0);
3717 }
3718 bool wasVirtualConnected = audioDeviceManager_.IsVirtualConnectedDevice(audioDescriptor);
3719 if (!wasVirtualConnected) {
3720 audioDescriptor->deviceId_ = startDeviceId++;
3721 } else {
3722 audioDeviceManager_.UpdateDeviceDescDeviceId(audioDescriptor);
3723 CheckAndNotifyUserSelectedDevice(audioDescriptor);
3724 }
3725 descForCb.push_back(audioDescriptor);
3726 UpdateDisplayName(audioDescriptor);
3727 connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
3728 audioDeviceManager_.AddNewDevice(audioDescriptor);
3729
3730 if (updatedDesc.connectState_ == VIRTUAL_CONNECTED) {
3731 AUDIO_INFO_LOG("The device is virtual device, no need to update preferred device");
3732 return; // No need to update preferred device for virtual device
3733 }
3734 DeviceUsage usage = GetDeviceUsage(updatedDesc);
3735 std::unique_ptr<AudioDeviceDescriptor> mediaDescriptor = std::move(audioRouterCenter_.FetchOutputDevices(
3736 STREAM_USAGE_MEDIA, -1, ROUTER_TYPE_USER_SELECT).front());
3737 if (audioDescriptor->networkId_ == LOCAL_NETWORK_ID && audioDescriptor->IsSameDeviceDesc(*mediaDescriptor) &&
3738 (usage & MEDIA) == MEDIA) {
3739 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor());
3740 }
3741 std::unique_ptr<AudioDeviceDescriptor> voiceDescriptor = std::move(audioRouterCenter_.FetchOutputDevices(
3742 STREAM_USAGE_VOICE_COMMUNICATION, -1, ROUTER_TYPE_USER_SELECT).front());
3743 if (audioDescriptor->networkId_ == LOCAL_NETWORK_ID && audioDescriptor->IsSameDeviceDesc(*voiceDescriptor) &&
3744 (usage & VOICE) == VOICE) {
3745 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor());
3746 }
3747 }
3748
UpdateConnectedDevicesWhenConnectingForInputDevice(const AudioDeviceDescriptor & updatedDesc,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)3749 void AudioPolicyService::UpdateConnectedDevicesWhenConnectingForInputDevice(
3750 const AudioDeviceDescriptor &updatedDesc, std::vector<sptr<AudioDeviceDescriptor>> &descForCb)
3751 {
3752 AUDIO_INFO_LOG("Filling input device for %{public}d", updatedDesc.deviceType_);
3753
3754 sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(updatedDesc);
3755 audioDescriptor->deviceRole_ = INPUT_DEVICE;
3756 // Use mic streaminfo for all input devices cap
3757 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(),
3758 [](const sptr<AudioDeviceDescriptor> &devDesc) {
3759 CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor");
3760 return (devDesc->deviceType_ == DEVICE_TYPE_MIC);
3761 });
3762 if (itr != connectedDevices_.end()) {
3763 audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0);
3764 }
3765 bool wasVirtualConnected = audioDeviceManager_.IsVirtualConnectedDevice(audioDescriptor);
3766 if (!wasVirtualConnected) {
3767 audioDescriptor->deviceId_ = startDeviceId++;
3768 } else {
3769 audioDeviceManager_.UpdateDeviceDescDeviceId(audioDescriptor);
3770 }
3771 descForCb.push_back(audioDescriptor);
3772 UpdateDisplayName(audioDescriptor);
3773 connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
3774 AddMicrophoneDescriptor(audioDescriptor);
3775 audioDeviceManager_.AddNewDevice(audioDescriptor);
3776 if (updatedDesc.connectState_ == VIRTUAL_CONNECTED) {
3777 return;
3778 }
3779 if (audioDescriptor->deviceCategory_ != BT_UNWEAR_HEADPHONE && audioDescriptor->deviceCategory_ != BT_WATCH) {
3780 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor());
3781 SetPreferredDevice(AUDIO_RECORD_CAPTURE, new(std::nothrow) AudioDeviceDescriptor());
3782 }
3783 }
3784
UpdateConnectedDevicesWhenConnecting(const AudioDeviceDescriptor & updatedDesc,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)3785 void AudioPolicyService::UpdateConnectedDevicesWhenConnecting(const AudioDeviceDescriptor &updatedDesc,
3786 std::vector<sptr<AudioDeviceDescriptor>> &descForCb)
3787 {
3788 AUDIO_INFO_LOG("UpdateConnectedDevicesWhenConnecting In, deviceType: %{public}d", updatedDesc.deviceType_);
3789 if (IsOutputDevice(updatedDesc.deviceType_, updatedDesc.deviceRole_)) {
3790 UpdateConnectedDevicesWhenConnectingForOutputDevice(updatedDesc, descForCb);
3791 }
3792 if (IsInputDevice(updatedDesc.deviceType_, updatedDesc.deviceRole_)) {
3793 UpdateConnectedDevicesWhenConnectingForInputDevice(updatedDesc, descForCb);
3794 }
3795 }
3796
UpdateConnectedDevicesWhenDisconnecting(const AudioDeviceDescriptor & updatedDesc,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)3797 void AudioPolicyService::UpdateConnectedDevicesWhenDisconnecting(const AudioDeviceDescriptor& updatedDesc,
3798 std::vector<sptr<AudioDeviceDescriptor>> &descForCb)
3799 {
3800 AUDIO_INFO_LOG("[%{public}s], devType:[%{public}d]", __func__, updatedDesc.deviceType_);
3801 auto isPresent = [&updatedDesc](const sptr<AudioDeviceDescriptor>& descriptor) {
3802 return descriptor->deviceType_ == updatedDesc.deviceType_ &&
3803 descriptor->macAddress_ == updatedDesc.macAddress_ &&
3804 descriptor->networkId_ == updatedDesc.networkId_;
3805 };
3806
3807 // Remember the disconnected device descriptor and remove it
3808 for (auto it = connectedDevices_.begin(); it != connectedDevices_.end();) {
3809 it = find_if(it, connectedDevices_.end(), isPresent);
3810 if (it != connectedDevices_.end()) {
3811 if ((*it)->deviceType_ == DEVICE_TYPE_DP) { hasDpDevice_ = false; }
3812 if (audioStateManager_.GetPreferredMediaRenderDevice() != nullptr &&
3813 (*it)->IsSameDeviceDesc(*audioStateManager_.GetPreferredMediaRenderDevice())) {
3814 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor());
3815 }
3816 if (audioStateManager_.GetPreferredCallRenderDevice() != nullptr &&
3817 (*it)->IsSameDeviceDesc(*audioStateManager_.GetPreferredCallRenderDevice())) {
3818 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor());
3819 }
3820 if (audioStateManager_.GetPreferredCallCaptureDevice() != nullptr &&
3821 (*it)->IsSameDeviceDesc(*audioStateManager_.GetPreferredCallCaptureDevice())) {
3822 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor());
3823 }
3824 if (audioStateManager_.GetPreferredRecordCaptureDevice() != nullptr &&
3825 (*it)->IsSameDeviceDesc(*audioStateManager_.GetPreferredRecordCaptureDevice())) {
3826 SetPreferredDevice(AUDIO_RECORD_CAPTURE, new(std::nothrow) AudioDeviceDescriptor());
3827 }
3828 descForCb.push_back(*it);
3829 it = connectedDevices_.erase(it);
3830 }
3831 }
3832
3833 // reset disconnected device info in stream
3834 if (IsOutputDevice(updatedDesc.deviceType_)) {
3835 streamCollector_.ResetRendererStreamDeviceInfo(updatedDesc);
3836 }
3837 if (IsInputDevice(updatedDesc.deviceType_)) {
3838 streamCollector_.ResetCapturerStreamDeviceInfo(updatedDesc);
3839 }
3840
3841 sptr<AudioDeviceDescriptor> devDesc = new (std::nothrow) AudioDeviceDescriptor(updatedDesc);
3842 CHECK_AND_RETURN_LOG(devDesc != nullptr, "Create device descriptor failed");
3843 audioDeviceManager_.RemoveNewDevice(devDesc);
3844 RemoveMicrophoneDescriptor(devDesc);
3845 if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
3846 GetCurrentOutputDeviceMacAddr() == updatedDesc.macAddress_) {
3847 a2dpOffloadFlag_ = NO_A2DP_DEVICE;
3848 }
3849 }
3850
OnPnpDeviceStatusUpdated(DeviceType devType,bool isConnected)3851 void AudioPolicyService::OnPnpDeviceStatusUpdated(DeviceType devType, bool isConnected)
3852 {
3853 CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type");
3854 if (!hasModulesLoaded) {
3855 AUDIO_WARNING_LOG("modules has not loaded");
3856 pnpDeviceList_.push_back({devType, isConnected});
3857 return;
3858 }
3859 if (g_adProxy == nullptr) {
3860 GetAudioServerProxy();
3861 }
3862 AudioStreamInfo streamInfo = {};
3863 OnDeviceStatusUpdated(devType, isConnected, "", "", streamInfo);
3864 }
3865
OnPnpDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & name,const std::string & adderess)3866 void AudioPolicyService::OnPnpDeviceStatusUpdated(DeviceType devType, bool isConnected,
3867 const std::string &name, const std::string &adderess)
3868 {
3869 CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type");
3870 if (!hasModulesLoaded) {
3871 AUDIO_WARNING_LOG("modules has not loaded");
3872 pnpDeviceList_.push_back({devType, isConnected});
3873 return;
3874 }
3875 if (g_adProxy == nullptr) {
3876 GetAudioServerProxy();
3877 }
3878 AudioStreamInfo streamInfo = {};
3879 OnDeviceStatusUpdated(devType, isConnected, adderess, name, streamInfo);
3880 }
3881
OnMicrophoneBlockedUpdate(DeviceType devType,DeviceBlockStatus status)3882 void AudioPolicyService::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status)
3883 {
3884 CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type");
3885 if (g_adProxy == nullptr) {
3886 GetAudioServerProxy();
3887 }
3888 OnBlockedStatusUpdated(devType, status);
3889 }
3890
OnBlockedStatusUpdated(DeviceType devType,DeviceBlockStatus status)3891 void AudioPolicyService::OnBlockedStatusUpdated(DeviceType devType, DeviceBlockStatus status)
3892 {
3893 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {};
3894 sptr<AudioDeviceDescriptor> audioDescriptor = new AudioDeviceDescriptor(devType, GetDeviceRole(devType));
3895 descForCb.push_back(audioDescriptor);
3896
3897 vector<unique_ptr<AudioCapturerChangeInfo>> audioChangeInfos;
3898 streamCollector_.GetCurrentCapturerChangeInfos(audioChangeInfos);
3899 for (auto it = audioChangeInfos.begin(); it != audioChangeInfos.end(); it++) {
3900 if ((*it)->capturerState == CAPTURER_RUNNING) {
3901 AUDIO_INFO_LOG("record running");
3902 TriggerMicrophoneBlockedCallback(descForCb, status);
3903 }
3904 }
3905 }
3906
UpdateLocalGroupInfo(bool isConnected,const std::string & macAddress,const std::string & deviceName,const DeviceStreamInfo & streamInfo,AudioDeviceDescriptor & deviceDesc)3907 void AudioPolicyService::UpdateLocalGroupInfo(bool isConnected, const std::string& macAddress,
3908 const std::string& deviceName, const DeviceStreamInfo& streamInfo, AudioDeviceDescriptor& deviceDesc)
3909 {
3910 deviceDesc.SetDeviceInfo(deviceName, macAddress);
3911 deviceDesc.SetDeviceCapability(streamInfo, 0);
3912 UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, LOCAL_NETWORK_ID, isConnected,
3913 NO_REMOTE_ID);
3914 UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, LOCAL_NETWORK_ID, isConnected,
3915 NO_REMOTE_ID);
3916 deviceDesc.networkId_ = LOCAL_NETWORK_ID;
3917 }
3918
HandleLocalDeviceConnected(AudioDeviceDescriptor & updatedDesc)3919 int32_t AudioPolicyService::HandleLocalDeviceConnected(AudioDeviceDescriptor &updatedDesc)
3920 {
3921 AUDIO_INFO_LOG("macAddress:[%{public}s]", GetEncryptAddr(updatedDesc.macAddress_).c_str());
3922 {
3923 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_);
3924 if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
3925 A2dpDeviceConfigInfo configInfo = {updatedDesc.audioStreamInfo_, false};
3926 connectedA2dpDeviceMap_.insert(make_pair(updatedDesc.macAddress_, configInfo));
3927 }
3928 }
3929
3930 if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
3931 int32_t loadOutputResult = HandleArmUsbDevice(updatedDesc.deviceType_, OUTPUT_DEVICE, updatedDesc.macAddress_);
3932 if (loadOutputResult != SUCCESS) {
3933 loadOutputResult = RehandlePnpDevice(updatedDesc.deviceType_, OUTPUT_DEVICE, updatedDesc.macAddress_);
3934 }
3935 int32_t loadInputResult = HandleArmUsbDevice(updatedDesc.deviceType_, INPUT_DEVICE, updatedDesc.macAddress_);
3936 if (loadInputResult != SUCCESS) {
3937 loadInputResult = RehandlePnpDevice(updatedDesc.deviceType_, INPUT_DEVICE, updatedDesc.macAddress_);
3938 }
3939 if (loadOutputResult != SUCCESS && loadInputResult != SUCCESS) {
3940 hasArmUsbDevice_ = false;
3941 updatedDesc.deviceType_ = DEVICE_TYPE_USB_HEADSET;
3942 AUDIO_ERR_LOG("Load usb failed, set arm usb flag to false");
3943 return ERROR;
3944 }
3945 // Distinguish between USB input and output (need fix)
3946 if (loadOutputResult == SUCCESS && loadInputResult == SUCCESS) {
3947 updatedDesc.deviceRole_ = DEVICE_ROLE_MAX;
3948 } else {
3949 updatedDesc.deviceRole_ = (loadOutputResult == SUCCESS) ? OUTPUT_DEVICE : INPUT_DEVICE;
3950 }
3951 AUDIO_INFO_LOG("Load usb role is %{public}d", updatedDesc.deviceRole_);
3952 return SUCCESS;
3953 }
3954
3955 // DP device only for output.
3956 if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) {
3957 CHECK_AND_RETURN_RET_LOG(!hasDpDevice_, ERROR, "DP device already exists, ignore this one.");
3958 int32_t result = HandleDpDevice(updatedDesc.deviceType_, updatedDesc.macAddress_);
3959 if (result != SUCCESS) {
3960 result = RehandlePnpDevice(updatedDesc.deviceType_, OUTPUT_DEVICE, updatedDesc.macAddress_);
3961 }
3962 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Load dp failed.");
3963 hasDpDevice_ = true;
3964 }
3965
3966 return SUCCESS;
3967 }
3968
HandleLocalDeviceDisconnected(const AudioDeviceDescriptor & updatedDesc)3969 int32_t AudioPolicyService::HandleLocalDeviceDisconnected(const AudioDeviceDescriptor &updatedDesc)
3970 {
3971 if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
3972 UpdateActiveA2dpDeviceWhenDisconnecting(updatedDesc.macAddress_);
3973 }
3974
3975 if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
3976 ClosePortAndEraseIOHandle(USB_SPEAKER);
3977 ClosePortAndEraseIOHandle(USB_MIC);
3978 }
3979 if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) {
3980 ClosePortAndEraseIOHandle(DP_SINK);
3981 }
3982
3983 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3984 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERROR, "UpdateActiveDevicesRoute, Audio Server Proxy is null");
3985 std::string identity = IPCSkeleton::ResetCallingIdentity();
3986 gsp->ResetRouteForDisconnect(updatedDesc.deviceType_);
3987 IPCSkeleton::SetCallingIdentity(identity);
3988
3989 return SUCCESS;
3990 }
3991
UpdateActiveA2dpDeviceWhenDisconnecting(const std::string & macAddress)3992 void AudioPolicyService::UpdateActiveA2dpDeviceWhenDisconnecting(const std::string& macAddress)
3993 {
3994 bool flag = false;
3995 {
3996 std::unique_lock<std::mutex> lock(a2dpDeviceMapMutex_);
3997 connectedA2dpDeviceMap_.erase(macAddress);
3998 flag = (connectedA2dpDeviceMap_.size() == 0);
3999 }
4000
4001 if (flag) {
4002 activeBTDevice_ = "";
4003 ClosePortAndEraseIOHandle(BLUETOOTH_SPEAKER);
4004 audioPolicyManager_.SetAbsVolumeScene(false);
4005 SetSharedAbsVolumeScene(false);
4006 #ifdef BLUETOOTH_ENABLE
4007 Bluetooth::AudioA2dpManager::SetActiveA2dpDevice("");
4008 #endif
4009 return;
4010 }
4011 }
4012
FindConnectedHeadset()4013 DeviceType AudioPolicyService::FindConnectedHeadset()
4014 {
4015 DeviceType retType = DEVICE_TYPE_NONE;
4016 for (const auto& devDesc: connectedDevices_) {
4017 if ((devDesc->deviceType_ == DEVICE_TYPE_WIRED_HEADSET) ||
4018 (devDesc->deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES) ||
4019 (devDesc->deviceType_ == DEVICE_TYPE_USB_HEADSET) ||
4020 (devDesc->deviceType_ == DEVICE_TYPE_DP) ||
4021 (devDesc->deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET)) {
4022 retType = devDesc->deviceType_;
4023 break;
4024 }
4025 }
4026 return retType;
4027 }
4028
HandleSpecialDeviceType(DeviceType & devType,bool & isConnected,const std::string & address)4029 int32_t AudioPolicyService::HandleSpecialDeviceType(DeviceType &devType, bool &isConnected, const std::string &address)
4030 {
4031 // usb device needs to be distinguished form arm or hifi
4032 if (devType == DEVICE_TYPE_USB_HEADSET || devType == DEVICE_TYPE_USB_ARM_HEADSET) {
4033 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
4034 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERROR, "HandleSpecialDeviceType, Audio server Proxy is null");
4035 AUDIO_INFO_LOG("has hifi:%{public}d, has arm:%{public}d", hasHifiUsbDevice_, hasArmUsbDevice_);
4036 std::string identity = IPCSkeleton::ResetCallingIdentity();
4037
4038 // Hal only support one HiFi device, If HiFi is already online, the following devices should be ARM.
4039 // But when the second usb device went online, the return value of this interface was not accurate.
4040 // So special handling was done when usb device was connected and disconnected.
4041 const std::string value = gsp->GetAudioParameter("need_change_usb_device");
4042
4043 IPCSkeleton::SetCallingIdentity(identity);
4044 AUDIO_INFO_LOG("get value %{public}s from hal when usb device connect", value.c_str());
4045 if (isConnected) {
4046 bool isArmConnect = (value == "false" || hasHifiUsbDevice_);
4047 if (isArmConnect) {
4048 hasArmUsbDevice_ = true;
4049 devType = DEVICE_TYPE_USB_ARM_HEADSET;
4050 CHECK_AND_RETURN_RET_LOG(!hasHifiUsbDevice_, ERROR, "Hifi device already exists, ignore this one.");
4051 } else {
4052 hasHifiUsbDevice_ = true;
4053 CHECK_AND_RETURN_RET_LOG(!hasArmUsbDevice_, ERROR, "Arm device already exists, ignore this one.");
4054 }
4055 } else {
4056 bool isArmDisconnect = ((hasArmUsbDevice_ && !hasHifiUsbDevice_) ||
4057 (hasArmUsbDevice_ && hasHifiUsbDevice_ && value == "true"));
4058 if (isArmDisconnect) {
4059 devType = DEVICE_TYPE_USB_ARM_HEADSET;
4060 hasArmUsbDevice_ = false;
4061 } else {
4062 hasHifiUsbDevice_ = false;
4063 }
4064 }
4065 }
4066
4067 // Special logic for extern cable, need refactor
4068 if (devType == DEVICE_TYPE_EXTERN_CABLE) {
4069 CHECK_AND_RETURN_RET_LOG(isConnected, ERROR, "Extern cable disconnected, do nothing");
4070 DeviceType connectedHeadsetType = FindConnectedHeadset();
4071 if (connectedHeadsetType == DEVICE_TYPE_NONE) {
4072 AUDIO_INFO_LOG("Extern cable connect without headset connected before, do nothing");
4073 return ERROR;
4074 }
4075 devType = connectedHeadsetType;
4076 isConnected = false;
4077 }
4078
4079 return SUCCESS;
4080 }
4081
ResetToSpeaker(DeviceType devType)4082 void AudioPolicyService::ResetToSpeaker(DeviceType devType)
4083 {
4084 if (devType != GetCurrentOutputDeviceType()) {
4085 return;
4086 }
4087 if (devType == DEVICE_TYPE_BLUETOOTH_SCO || devType == DEVICE_TYPE_USB_HEADSET ||
4088 devType == DEVICE_TYPE_WIRED_HEADSET || devType == DEVICE_TYPE_WIRED_HEADPHONES) {
4089 UpdateActiveDeviceRoute(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG);
4090 }
4091 }
4092
OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)4093 void AudioPolicyService::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress,
4094 const std::string& deviceName, const AudioStreamInfo& streamInfo)
4095 {
4096 // Pnp device status update
4097 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
4098
4099 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN;
4100 // fill device change action for callback
4101 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {};
4102
4103 int32_t result = ERROR;
4104 result = HandleSpecialDeviceType(devType, isConnected, macAddress);
4105 CHECK_AND_RETURN_LOG(result == SUCCESS, "handle special deviceType failed.");
4106
4107 AUDIO_WARNING_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d], address[%{public}s]",
4108 devType, isConnected, GetEncryptStr(macAddress).c_str());
4109
4110 AudioDeviceDescriptor updatedDesc(devType, GetDeviceRole(devType));
4111 UpdateLocalGroupInfo(isConnected, macAddress, deviceName, streamInfo, updatedDesc);
4112
4113 auto isPresent = [&updatedDesc] (const sptr<AudioDeviceDescriptor> &descriptor) {
4114 return descriptor->deviceType_ == updatedDesc.deviceType_ &&
4115 descriptor->macAddress_ == updatedDesc.macAddress_ &&
4116 descriptor->networkId_ == updatedDesc.networkId_;
4117 };
4118 if (isConnected) {
4119 // If device already in list, remove it else do not modify the list
4120 connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent),
4121 connectedDevices_.end());
4122 // If the pnp device fails to load, it will not connect
4123 result = HandleLocalDeviceConnected(updatedDesc);
4124 CHECK_AND_RETURN_LOG(result == SUCCESS, "Connect local device failed.");
4125 UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb);
4126
4127 reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE;
4128 } else {
4129 UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb);
4130 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
4131 result = HandleLocalDeviceDisconnected(updatedDesc);
4132 CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed.");
4133 }
4134
4135 TriggerDeviceChangedCallback(descForCb, isConnected);
4136 TriggerAvailableDeviceChangedCallback(descForCb, isConnected);
4137
4138 // fetch input&output device
4139 FetchDevice(true, reason);
4140 FetchDevice(false);
4141
4142 // update a2dp offload
4143 UpdateA2dpOffloadFlagForAllStream();
4144 }
4145
OnDeviceStatusUpdated(AudioDeviceDescriptor & updatedDesc,bool isConnected)4146 void AudioPolicyService::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, bool isConnected)
4147 {
4148 // Bluetooth device status updated
4149 DeviceType devType = updatedDesc.deviceType_;
4150 string macAddress = updatedDesc.macAddress_;
4151 string deviceName = updatedDesc.deviceName_;
4152 bool isActualConnection = (updatedDesc.connectState_ != VIRTUAL_CONNECTED);
4153 AUDIO_WARNING_LOG("Device connection is actual connection: %{public}d", isActualConnection);
4154
4155 AudioStreamInfo streamInfo = {};
4156 #ifdef BLUETOOTH_ENABLE
4157 if (devType == DEVICE_TYPE_BLUETOOTH_A2DP && isActualConnection && isConnected) {
4158 int32_t ret = Bluetooth::AudioA2dpManager::GetA2dpDeviceStreamInfo(macAddress, streamInfo);
4159 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Get a2dp device stream info failed!");
4160 }
4161 #endif
4162 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
4163 AUDIO_WARNING_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d], mac[%{public}s]",
4164 devType, isConnected, GetEncryptStr(macAddress).c_str());
4165
4166 UpdateLocalGroupInfo(isConnected, macAddress, deviceName, streamInfo, updatedDesc);
4167 // fill device change action for callback
4168 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN;
4169 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {};
4170 UpdateDeviceList(updatedDesc, isConnected, descForCb, reason);
4171
4172 TriggerDeviceChangedCallback(descForCb, isConnected);
4173 TriggerAvailableDeviceChangedCallback(descForCb, isConnected);
4174
4175 if (!isActualConnection) {
4176 return;
4177 }
4178 // fetch input&output device
4179 FetchDevice(true, reason);
4180 FetchDevice(false);
4181 // update a2dp offload
4182 if (devType == DEVICE_TYPE_BLUETOOTH_A2DP) {
4183 UpdateA2dpOffloadFlagForAllStream();
4184 }
4185 }
4186
UpdateDeviceList(AudioDeviceDescriptor & updatedDesc,bool isConnected,std::vector<sptr<AudioDeviceDescriptor>> & descForCb,AudioStreamDeviceChangeReasonExt & reason)4187 void AudioPolicyService::UpdateDeviceList(AudioDeviceDescriptor &updatedDesc, bool isConnected,
4188 std::vector<sptr<AudioDeviceDescriptor>> &descForCb,
4189 AudioStreamDeviceChangeReasonExt &reason)
4190 {
4191 auto isPresent = [&updatedDesc] (const sptr<AudioDeviceDescriptor> &descriptor) {
4192 return descriptor->deviceType_ == updatedDesc.deviceType_ &&
4193 descriptor->macAddress_ == updatedDesc.macAddress_ &&
4194 descriptor->networkId_ == updatedDesc.networkId_;
4195 };
4196 if (isConnected) {
4197 // deduplicate
4198 connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent),
4199 connectedDevices_.end());
4200 UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb);
4201 int32_t result = HandleLocalDeviceConnected(updatedDesc);
4202 CHECK_AND_RETURN_LOG(result == SUCCESS, "Connect local device failed.");
4203 reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE;
4204 #ifdef BLUETOOTH_ENABLE
4205 CheckAndActiveHfpDevice(updatedDesc);
4206 #endif
4207 } else {
4208 UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb);
4209 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
4210 FetchDevice(true, reason); // fix pop, fetch device before unload module
4211 int32_t result = HandleLocalDeviceDisconnected(updatedDesc);
4212 CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed.");
4213 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
4214 }
4215 }
4216
4217 #ifdef FEATURE_DTMF_TONE
GetSupportedTones()4218 std::vector<int32_t> AudioPolicyService::GetSupportedTones()
4219 {
4220 std::vector<int> supportedToneList = {};
4221 for (auto i = toneDescriptorMap.begin(); i != toneDescriptorMap.end(); i++) {
4222 supportedToneList.push_back(i->first);
4223 }
4224 return supportedToneList;
4225 }
4226
GetToneConfig(int32_t ltonetype)4227 std::shared_ptr<ToneInfo> AudioPolicyService::GetToneConfig(int32_t ltonetype)
4228 {
4229 if (toneDescriptorMap.find(ltonetype) == toneDescriptorMap.end()) {
4230 return nullptr;
4231 }
4232 AUDIO_DEBUG_LOG("AudioPolicyService GetToneConfig %{public}d", ltonetype);
4233 return toneDescriptorMap[ltonetype];
4234 }
4235 #endif
4236
UpdateA2dpOffloadFlagBySpatialService(const std::string & macAddress,std::unordered_map<uint32_t,bool> & sessionIDToSpatializationEnabledMap)4237 void AudioPolicyService::UpdateA2dpOffloadFlagBySpatialService(
4238 const std::string& macAddress, std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnabledMap)
4239 {
4240 auto it = spatialDeviceMap_.find(macAddress);
4241 DeviceType spatialDevice;
4242 if (it != spatialDeviceMap_.end()) {
4243 spatialDevice = it->second;
4244 } else {
4245 AUDIO_DEBUG_LOG("we can't find the spatialDevice of hvs");
4246 spatialDevice = DEVICE_TYPE_NONE;
4247 }
4248 AUDIO_INFO_LOG("Update a2dpOffloadFlag spatialDevice: %{public}d", spatialDevice);
4249 UpdateA2dpOffloadFlagForAllStream(sessionIDToSpatializationEnabledMap, spatialDevice);
4250 }
4251
UpdateA2dpOffloadFlagForAllStream(std::unordered_map<uint32_t,bool> & sessionIDToSpatializationEnabledMap,DeviceType deviceType)4252 void AudioPolicyService::UpdateA2dpOffloadFlagForAllStream(
4253 std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnabledMap, DeviceType deviceType)
4254 {
4255 #ifdef BLUETOOTH_ENABLE
4256 vector<Bluetooth::A2dpStreamInfo> allSessionInfos;
4257 Bluetooth::A2dpStreamInfo a2dpStreamInfo;
4258 vector<unique_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos;
4259 streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
4260 std::vector<int32_t> stopPlayingStream(0);
4261 for (auto &changeInfo : audioRendererChangeInfos) {
4262 if (changeInfo->rendererState != RENDERER_RUNNING) {
4263 stopPlayingStream.emplace_back(changeInfo->sessionId);
4264 continue;
4265 }
4266 a2dpStreamInfo.sessionId = changeInfo->sessionId;
4267 a2dpStreamInfo.streamType = GetStreamType(changeInfo->sessionId);
4268 if (sessionIDToSpatializationEnabledMap.count(static_cast<uint32_t>(a2dpStreamInfo.sessionId))) {
4269 a2dpStreamInfo.isSpatialAudio =
4270 sessionIDToSpatializationEnabledMap[static_cast<uint32_t>(a2dpStreamInfo.sessionId)];
4271 } else {
4272 a2dpStreamInfo.isSpatialAudio = 0;
4273 }
4274 allSessionInfos.push_back(a2dpStreamInfo);
4275 }
4276 if (stopPlayingStream.size() > 0) {
4277 OffloadStopPlaying(stopPlayingStream);
4278 }
4279 UpdateA2dpOffloadFlag(allSessionInfos, deviceType);
4280 #endif
4281 AUDIO_DEBUG_LOG("deviceType %{public}d", deviceType);
4282 }
4283
UpdateA2dpOffloadFlagForAllStream(DeviceType deviceType)4284 int32_t AudioPolicyService::UpdateA2dpOffloadFlagForAllStream(DeviceType deviceType)
4285 {
4286 int32_t activeSessionsSize = 0;
4287 #ifdef BLUETOOTH_ENABLE
4288 vector<Bluetooth::A2dpStreamInfo> allSessionInfos;
4289 Bluetooth::A2dpStreamInfo a2dpStreamInfo;
4290 vector<unique_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos;
4291 streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
4292 {
4293 AudioXCollie audioXCollie("AudioPolicyService::UpdateA2dpOffloadFlagForAllStream", BLUETOOTH_TIME_OUT_SECONDS);
4294 std::vector<int32_t> stopPlayingStream(0);
4295 for (auto &changeInfo : audioRendererChangeInfos) {
4296 if (changeInfo->rendererState != RENDERER_RUNNING) {
4297 stopPlayingStream.emplace_back(changeInfo->sessionId);
4298 continue;
4299 }
4300 a2dpStreamInfo.sessionId = changeInfo->sessionId;
4301 a2dpStreamInfo.streamType = GetStreamType(changeInfo->sessionId);
4302 StreamUsage tempStreamUsage = changeInfo->rendererInfo.streamUsage;
4303 AudioSpatializationState spatialState =
4304 AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState(tempStreamUsage);
4305 a2dpStreamInfo.isSpatialAudio = spatialState.spatializationEnabled;
4306 allSessionInfos.push_back(a2dpStreamInfo);
4307 }
4308 if (stopPlayingStream.size() > 0) {
4309 OffloadStopPlaying(stopPlayingStream);
4310 }
4311 }
4312 UpdateA2dpOffloadFlag(allSessionInfos, deviceType);
4313 activeSessionsSize = static_cast<int32_t>(allSessionInfos.size());
4314 #endif
4315 AUDIO_DEBUG_LOG("deviceType %{public}d", deviceType);
4316 return activeSessionsSize;
4317 }
4318
OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)4319 void AudioPolicyService::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress,
4320 const std::string &deviceName, const AudioStreamInfo &streamInfo)
4321 {
4322 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
4323
4324 AUDIO_INFO_LOG("OnDeviceConfigurationChanged start, deviceType: %{public}d, currentActiveDevice_: %{public}d, "
4325 "macAddress:[%{public}s], activeBTDevice_:[%{public}s]", deviceType, GetCurrentOutputDeviceType(),
4326 GetEncryptAddr(macAddress).c_str(), GetEncryptAddr(activeBTDevice_).c_str());
4327 // only for the active a2dp device.
4328 if ((deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) && !macAddress.compare(activeBTDevice_)) {
4329 auto activeSessionsSize = UpdateA2dpOffloadFlagForAllStream();
4330 AUDIO_DEBUG_LOG("streamInfo.sampleRate: %{public}d, a2dpOffloadFlag_: %{public}d",
4331 streamInfo.samplingRate, a2dpOffloadFlag_);
4332 if (!IsConfigurationUpdated(deviceType, streamInfo) ||
4333 (activeSessionsSize > 0 && a2dpOffloadFlag_ == A2DP_OFFLOAD)) {
4334 AUDIO_DEBUG_LOG("Audio configuration same");
4335 return;
4336 }
4337
4338 connectedA2dpDeviceMap_[macAddress].streamInfo = streamInfo;
4339 ReloadA2dpOffloadOnDeviceChanged(deviceType, macAddress, deviceName, streamInfo);
4340 } else if (connectedA2dpDeviceMap_.find(macAddress) != connectedA2dpDeviceMap_.end()) {
4341 AUDIO_DEBUG_LOG("Audio configuration update, macAddress:[%{public}s], streamInfo.sampleRate: %{public}d",
4342 GetEncryptAddr(macAddress).c_str(), streamInfo.samplingRate);
4343 connectedA2dpDeviceMap_[macAddress].streamInfo = streamInfo;
4344 }
4345 }
4346
ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)4347 void AudioPolicyService::ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType, const std::string &macAddress,
4348 const std::string &deviceName, const AudioStreamInfo &streamInfo)
4349 {
4350 uint32_t bufferSize = (streamInfo.samplingRate * GetSampleFormatValue(streamInfo.format)
4351 * streamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR);
4352 AUDIO_DEBUG_LOG("Updated buffer size: %{public}d", bufferSize);
4353
4354 auto a2dpModulesPos = deviceClassInfo_.find(ClassType::TYPE_A2DP);
4355 if (a2dpModulesPos != deviceClassInfo_.end()) {
4356 auto moduleInfoList = a2dpModulesPos->second;
4357 for (auto &moduleInfo : moduleInfoList) {
4358 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
4359 CHECK_AND_CONTINUE_LOG(IOHandles_.find(moduleInfo.name) != IOHandles_.end(),
4360 "Cannot find module %{public}s", moduleInfo.name.c_str());
4361 moduleInfo.channels = to_string(streamInfo.channels);
4362 moduleInfo.rate = to_string(streamInfo.samplingRate);
4363 moduleInfo.format = ConvertToHDIAudioFormat(streamInfo.format);
4364 moduleInfo.bufferSize = to_string(bufferSize);
4365 moduleInfo.renderInIdleState = "1";
4366 moduleInfo.sinkLatency = "0";
4367
4368 // First unload the existing bt sink
4369 AUDIO_DEBUG_LOG("UnLoad existing a2dp module");
4370 std::string currentActivePort = GetSinkPortName(GetCurrentOutputDeviceType());
4371 AudioIOHandle activateDeviceIOHandle = IOHandles_[BLUETOOTH_SPEAKER];
4372 MuteDefaultSinkPort();
4373 audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
4374 audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle);
4375
4376 // Load bt sink module again with new configuration
4377 AUDIO_DEBUG_LOG("Reload a2dp module [%{public}s]", moduleInfo.name.c_str());
4378 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
4379 if (ioHandle == OPEN_PORT_FAILURE) {
4380 audioPolicyManager_.SuspendAudioDevice(currentActivePort, false);
4381 AUDIO_ERR_LOG("OpenAudioPort failed %{public}d", ioHandle);
4382 return;
4383 }
4384 IOHandles_[moduleInfo.name] = ioHandle;
4385 std::string portName = GetSinkPortName(deviceType);
4386 if (!IsVoiceCallRelatedScene()) {
4387 audioPolicyManager_.SetDeviceActive(deviceType, portName, true);
4388 }
4389 audioPolicyManager_.SuspendAudioDevice(portName, false);
4390 audioPolicyManager_.SuspendAudioDevice(currentActivePort, false);
4391
4392 auto isPresent = [&macAddress] (const sptr<AudioDeviceDescriptor> &descriptor) {
4393 return descriptor->macAddress_ == macAddress;
4394 };
4395
4396 sptr<AudioDeviceDescriptor> audioDescriptor
4397 = new(std::nothrow) AudioDeviceDescriptor(deviceType, OUTPUT_DEVICE);
4398 audioDescriptor->SetDeviceInfo(deviceName, macAddress);
4399 audioDescriptor->SetDeviceCapability(streamInfo, 0);
4400 std::replace_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent, audioDescriptor);
4401 break;
4402 }
4403 }
4404 }
4405
RemoveDeviceInRouterMap(std::string networkId)4406 void AudioPolicyService::RemoveDeviceInRouterMap(std::string networkId)
4407 {
4408 std::lock_guard<std::mutex> lock(routerMapMutex_);
4409 std::unordered_map<int32_t, std::pair<std::string, int32_t>>::iterator it;
4410 for (it = routerMap_.begin();it != routerMap_.end();) {
4411 if (it->second.first == networkId) {
4412 routerMap_.erase(it++);
4413 } else {
4414 it++;
4415 }
4416 }
4417 }
4418
RemoveDeviceInFastRouterMap(std::string networkId)4419 void AudioPolicyService::RemoveDeviceInFastRouterMap(std::string networkId)
4420 {
4421 std::lock_guard<std::mutex> lock(routerMapMutex_);
4422 std::unordered_map<int32_t, std::pair<std::string, DeviceRole>>::iterator it;
4423 for (it = fastRouterMap_.begin();it != fastRouterMap_.end();) {
4424 if (it->second.first == networkId) {
4425 fastRouterMap_.erase(it++);
4426 } else {
4427 it++;
4428 }
4429 }
4430 }
4431
SetDisplayName(const std::string & deviceName,bool isLocalDevice)4432 void AudioPolicyService::SetDisplayName(const std::string &deviceName, bool isLocalDevice)
4433 {
4434 for (const auto& deviceInfo : connectedDevices_) {
4435 if ((isLocalDevice && deviceInfo->networkId_ == LOCAL_NETWORK_ID) ||
4436 (!isLocalDevice && deviceInfo->networkId_ != LOCAL_NETWORK_ID)) {
4437 deviceInfo->displayName_ = deviceName;
4438 }
4439 }
4440 }
4441
RegisterRemoteDevStatusCallback()4442 void AudioPolicyService::RegisterRemoteDevStatusCallback()
4443 {
4444 #ifdef FEATURE_DEVICE_MANAGER
4445 AUDIO_INFO_LOG("RegisterRemoteDevStatusCallback start");
4446 std::shared_ptr<DistributedHardware::DmInitCallback> initCallback = std::make_shared<DeviceInitCallBack>();
4447 int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(AUDIO_SERVICE_PKG, initCallback);
4448 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Init device manage failed");
4449 std::shared_ptr<DistributedHardware::DeviceStatusCallback> callback = std::make_shared<DeviceStatusCallbackImpl>();
4450 DistributedHardware::DeviceManager::GetInstance().RegisterDevStatusCallback(AUDIO_SERVICE_PKG, "", callback);
4451 AUDIO_INFO_LOG("Done");
4452 #endif
4453 }
4454
CreateDataShareHelperInstance()4455 std::shared_ptr<DataShare::DataShareHelper> AudioPolicyService::CreateDataShareHelperInstance()
4456 {
4457 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4458 CHECK_AND_RETURN_RET_LOG(samgr != nullptr, nullptr, "[Policy Service] Get samgr failed.");
4459
4460 sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(AUDIO_POLICY_SERVICE_ID);
4461 CHECK_AND_RETURN_RET_LOG(remoteObject != nullptr, nullptr, "[Policy Service] audio service remote object is NULL.");
4462
4463 int64_t startTime = ClockTime::GetCurNano();
4464 sptr<IRemoteObject> dataSharedServer = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
4465 int64_t cost = ClockTime::GetCurNano() - startTime;
4466 if (cost > CALL_IPC_COST_TIME_MS) {
4467 AUDIO_WARNING_LOG("Call get DataShare server cost too long: %{public}" PRId64"ms.", cost / AUDIO_US_PER_SECOND);
4468 }
4469
4470 CHECK_AND_RETURN_RET_LOG(dataSharedServer != nullptr, nullptr, "DataShare server is not started!");
4471
4472 WatchTimeout guard("DataShare::DataShareHelper::Create", CALL_IPC_COST_TIME_MS);
4473 std::pair<int, std::shared_ptr<DataShare::DataShareHelper>> res = DataShare::DataShareHelper::Create(remoteObject,
4474 SETTINGS_DATA_BASE_URI, SETTINGS_DATA_EXT_URI);
4475 guard.CheckCurrTimeout();
4476 if (res.first == DataShare::E_DATA_SHARE_NOT_READY) {
4477 AUDIO_WARNING_LOG("DataShareHelper::Create failed: E_DATA_SHARE_NOT_READY");
4478 return nullptr;
4479 }
4480 std::shared_ptr<DataShare::DataShareHelper> dataShareHelper = res.second;
4481 CHECK_AND_RETURN_RET_LOG(res.first == DataShare::E_OK && dataShareHelper != nullptr, nullptr, "fail:%{public}d",
4482 res.first);
4483 return dataShareHelper;
4484 }
4485
GetDeviceNameFromDataShareHelper(std::string & deviceName)4486 int32_t AudioPolicyService::GetDeviceNameFromDataShareHelper(std::string &deviceName)
4487 {
4488 std::shared_ptr<DataShare::DataShareHelper> dataShareHelper = CreateDataShareHelperInstance();
4489 CHECK_AND_RETURN_RET_LOG(dataShareHelper != nullptr, ERROR, "GetDeviceNameFromDataShareHelper NULL");
4490
4491 std::shared_ptr<Uri> uri = std::make_shared<Uri>(SETTINGS_DATA_BASE_URI);
4492 std::vector<std::string> columns;
4493 columns.emplace_back(SETTINGS_DATA_FIELD_VALUE);
4494 DataShare::DataSharePredicates predicates;
4495 predicates.EqualTo(SETTINGS_DATA_FIELD_KEYWORD, PREDICATES_STRING);
4496
4497 WatchTimeout guard("dataShareHelper->Query:DefaultDeviceName");
4498 auto resultSet = dataShareHelper->Query(*uri, predicates, columns);
4499 if (resultSet == nullptr) {
4500 AUDIO_ERR_LOG("Failed to query device name from dataShareHelper!");
4501 dataShareHelper->Release();
4502 return ERROR;
4503 }
4504 guard.CheckCurrTimeout();
4505
4506 int32_t numRows = 0;
4507 resultSet->GetRowCount(numRows);
4508 if (numRows <= 0) {
4509 AUDIO_ERR_LOG("The result of querying is zero row!");
4510 resultSet->Close();
4511 dataShareHelper->Release();
4512 return ERROR;
4513 }
4514
4515 int columnIndex;
4516 resultSet->GoToFirstRow();
4517 resultSet->GetColumnIndex(SETTINGS_DATA_FIELD_VALUE, columnIndex);
4518 resultSet->GetString(columnIndex, deviceName);
4519 AUDIO_INFO_LOG("GetDeviceNameFromDataShareHelper deviceName[%{public}s]", deviceName.c_str());
4520
4521 resultSet->Close();
4522 dataShareHelper->Release();
4523 return SUCCESS;
4524 }
4525
IsDataShareReady()4526 bool AudioPolicyService::IsDataShareReady()
4527 {
4528 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4529 CHECK_AND_RETURN_RET_LOG(samgr != nullptr, false, "[Policy Service] Get samgr failed.");
4530 sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(AUDIO_POLICY_SERVICE_ID);
4531 CHECK_AND_RETURN_RET_LOG(remoteObject != nullptr, false, "[Policy Service] audio service remote object is NULL.");
4532 WatchTimeout guard("DataShare::DataShareHelper::Create:IsDataShareReady", CALL_IPC_COST_TIME_MS);
4533 std::pair<int, std::shared_ptr<DataShare::DataShareHelper>> res = DataShare::DataShareHelper::Create(remoteObject,
4534 SETTINGS_DATA_BASE_URI, SETTINGS_DATA_EXT_URI);
4535 guard.CheckCurrTimeout();
4536 if (res.first == DataShare::E_OK) {
4537 AUDIO_INFO_LOG("DataShareHelper is ready.");
4538 auto helper = res.second;
4539 if (helper != nullptr) {
4540 helper->Release();
4541 }
4542 return true;
4543 } else {
4544 AUDIO_WARNING_LOG("DataShareHelper::Create failed: E_DATA_SHARE_NOT_READY");
4545 return false;
4546 }
4547 }
4548
SetDataShareReady(std::atomic<bool> isDataShareReady)4549 void AudioPolicyService::SetDataShareReady(std::atomic<bool> isDataShareReady)
4550 {
4551 audioPolicyManager_.SetDataShareReady(std::atomic_load(&isDataShareReady));
4552 }
4553
RegisterNameMonitorHelper()4554 void AudioPolicyService::RegisterNameMonitorHelper()
4555 {
4556 std::shared_ptr<DataShare::DataShareHelper> dataShareHelper = CreateDataShareHelperInstance();
4557 CHECK_AND_RETURN_LOG(dataShareHelper != nullptr, "dataShareHelper is NULL");
4558
4559 auto uri = std::make_shared<Uri>(std::string(SETTINGS_DATA_BASE_URI) + "&key=" + PREDICATES_STRING);
4560 sptr<AAFwk::DataAbilityObserverStub> settingDataObserver = std::make_unique<DataShareObserverCallBack>().release();
4561 dataShareHelper->RegisterObserver(*uri, settingDataObserver);
4562
4563 dataShareHelper->Release();
4564 }
4565
UpdateDisplayName(sptr<AudioDeviceDescriptor> deviceDescriptor)4566 void AudioPolicyService::UpdateDisplayName(sptr<AudioDeviceDescriptor> deviceDescriptor)
4567 {
4568 if (deviceDescriptor->networkId_ == LOCAL_NETWORK_ID) {
4569 std::string devicesName = "";
4570 int32_t ret = GetDeviceNameFromDataShareHelper(devicesName);
4571 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Local UpdateDisplayName init device failed");
4572 deviceDescriptor->displayName_ = devicesName;
4573 } else {
4574 #ifdef FEATURE_DEVICE_MANAGER
4575 std::shared_ptr<DistributedHardware::DmInitCallback> callback = std::make_shared<DeviceInitCallBack>();
4576 int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(AUDIO_SERVICE_PKG, callback);
4577 CHECK_AND_RETURN_LOG(ret == SUCCESS, "UpdateDisplayName init device failed");
4578 std::vector<DistributedHardware::DmDeviceInfo> deviceList;
4579 if (DistributedHardware::DeviceManager::GetInstance()
4580 .GetTrustedDeviceList(AUDIO_SERVICE_PKG, "", deviceList) == SUCCESS) {
4581 for (auto deviceInfo : deviceList) {
4582 std::string strNetworkId(deviceInfo.networkId);
4583 if (strNetworkId == deviceDescriptor->networkId_) {
4584 AUDIO_INFO_LOG("UpdateDisplayName remote name [%{public}s]", deviceInfo.deviceName);
4585 deviceDescriptor->displayName_ = deviceInfo.deviceName;
4586 break;
4587 }
4588 }
4589 };
4590 #endif
4591 }
4592 }
4593
HandleOfflineDistributedDevice()4594 void AudioPolicyService::HandleOfflineDistributedDevice()
4595 {
4596 std::vector<sptr<AudioDeviceDescriptor>> deviceChangeDescriptor = {};
4597
4598 std::vector<sptr<AudioDeviceDescriptor>> connectedDevices = connectedDevices_;
4599 for (auto deviceDesc : connectedDevices) {
4600 if (deviceDesc != nullptr && deviceDesc->networkId_ != LOCAL_NETWORK_ID) {
4601 const std::string networkId = deviceDesc->networkId_;
4602 UpdateConnectedDevicesWhenDisconnecting(deviceDesc, deviceChangeDescriptor);
4603 std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(deviceDesc->deviceType_));
4604 MuteDefaultSinkPort();
4605 ClosePortAndEraseIOHandle(moduleName);
4606 RemoveDeviceInRouterMap(moduleName);
4607 RemoveDeviceInFastRouterMap(networkId);
4608 if (GetDeviceRole(deviceDesc->deviceType_) == DeviceRole::INPUT_DEVICE) {
4609 remoteCapturerSwitch_ = true;
4610 }
4611 }
4612 }
4613
4614 TriggerDeviceChangedCallback(deviceChangeDescriptor, false);
4615 TriggerAvailableDeviceChangedCallback(deviceChangeDescriptor, false);
4616
4617 FetchDevice(true);
4618 FetchDevice(false);
4619 }
4620
HandleDistributedDeviceUpdate(DStatusInfo & statusInfo,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)4621 int32_t AudioPolicyService::HandleDistributedDeviceUpdate(DStatusInfo &statusInfo,
4622 std::vector<sptr<AudioDeviceDescriptor>> &descForCb)
4623 {
4624 DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin);
4625 const std::string networkId = statusInfo.networkId;
4626 AudioDeviceDescriptor deviceDesc(devType, GetDeviceRole(devType));
4627 deviceDesc.SetDeviceInfo(statusInfo.deviceName, statusInfo.macAddress);
4628 deviceDesc.SetDeviceCapability(statusInfo.streamInfo, 0);
4629 deviceDesc.networkId_ = networkId;
4630 UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, networkId, statusInfo.isConnected,
4631 statusInfo.mappingVolumeId);
4632 UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, networkId,
4633 statusInfo.isConnected, statusInfo.mappingInterruptId);
4634 if (statusInfo.isConnected) {
4635 for (auto devDes : connectedDevices_) {
4636 if (devDes->deviceType_ == devType && devDes->networkId_ == networkId) {
4637 return ERROR;
4638 }
4639 }
4640 int32_t ret = ActivateNewDevice(statusInfo.networkId, devType,
4641 statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED);
4642 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "DEVICE online but open audio device failed.");
4643 UpdateConnectedDevicesWhenConnecting(deviceDesc, descForCb);
4644
4645 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
4646 if (gsp != nullptr && statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED) {
4647 std::string identity = IPCSkeleton::ResetCallingIdentity();
4648 gsp->NotifyDeviceInfo(networkId, true);
4649 IPCSkeleton::SetCallingIdentity(identity);
4650 }
4651 } else {
4652 UpdateConnectedDevicesWhenDisconnecting(deviceDesc, descForCb);
4653 std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(devType));
4654 ClosePortAndEraseIOHandle(moduleName);
4655 RemoveDeviceInRouterMap(moduleName);
4656 RemoveDeviceInFastRouterMap(networkId);
4657 }
4658 return SUCCESS;
4659 }
4660
OnDeviceStatusUpdated(DStatusInfo statusInfo,bool isStop)4661 void AudioPolicyService::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop)
4662 {
4663 // Distributed devices status update
4664 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
4665
4666 AUDIO_WARNING_LOG("Device connection updated | HDI_PIN[%{public}d] CONNECT_STATUS[%{public}d] NETWORKID\
4667 [%{public}s]", statusInfo.hdiPin, statusInfo.isConnected, GetEncryptStr(statusInfo.networkId).c_str());
4668 if (isStop) {
4669 HandleOfflineDistributedDevice();
4670 return;
4671 }
4672 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {};
4673 int32_t ret = HandleDistributedDeviceUpdate(statusInfo, descForCb);
4674 CHECK_AND_RETURN_LOG(ret == SUCCESS, "HandleDistributedDeviceUpdate return directly.");
4675
4676 TriggerDeviceChangedCallback(descForCb, statusInfo.isConnected);
4677 TriggerAvailableDeviceChangedCallback(descForCb, statusInfo.isConnected);
4678
4679 FetchDevice(true);
4680 FetchDevice(false);
4681
4682 DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin);
4683 if (GetDeviceRole(devType) == DeviceRole::INPUT_DEVICE) {
4684 remoteCapturerSwitch_ = true;
4685 }
4686
4687 // update a2dp offload
4688 UpdateA2dpOffloadFlagForAllStream();
4689 }
4690
OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo & moduleInfo)4691 bool AudioPolicyService::OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo &moduleInfo)
4692 {
4693 auto devType = GetDeviceType(moduleInfo.name);
4694 if (devType != DEVICE_TYPE_MIC) {
4695 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
4696
4697 if (devType == DEVICE_TYPE_SPEAKER) {
4698 auto result = audioPolicyManager_.SetDeviceActive(devType, moduleInfo.name, true);
4699 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, false, "[module_load]::Device failed %{public}d", devType);
4700 }
4701 }
4702
4703 if (devType == DEVICE_TYPE_MIC) {
4704 primaryMicModuleInfo_ = moduleInfo;
4705 }
4706
4707 if (devType == DEVICE_TYPE_SPEAKER || devType == DEVICE_TYPE_MIC) {
4708 AddAudioDevice(moduleInfo, devType);
4709 }
4710
4711 std::lock_guard<std::mutex> lock(defaultDeviceLoadMutex_);
4712 SetDefaultDeviceLoadFlag(true);
4713 loadDefaultDeviceCV_.notify_all();
4714
4715 return true;
4716 }
4717
OnServiceConnected(AudioServiceIndex serviceIndex)4718 void AudioPolicyService::OnServiceConnected(AudioServiceIndex serviceIndex)
4719 {
4720 AUDIO_INFO_LOG("[module_load]::OnServiceConnected for [%{public}d]", serviceIndex);
4721 CHECK_AND_RETURN_LOG(serviceIndex >= HDI_SERVICE_INDEX && serviceIndex <= AUDIO_SERVICE_INDEX, "invalid index");
4722
4723 // If audio service or hdi service is not ready, donot load default modules
4724 lock_guard<mutex> lock(serviceFlagMutex_);
4725 serviceFlag_.set(serviceIndex, true);
4726 if (serviceFlag_.count() != MIN_SERVICE_COUNT) {
4727 AUDIO_INFO_LOG("[module_load]::hdi service or audio service not up. Cannot load default module now");
4728 return;
4729 }
4730
4731 int32_t result = ERROR;
4732 AUDIO_DEBUG_LOG("[module_load]::HDI and AUDIO SERVICE is READY. Loading default modules");
4733 for (const auto &device : deviceClassInfo_) {
4734 if (device.first == ClassType::TYPE_PRIMARY || device.first == ClassType::TYPE_FILE_IO) {
4735 auto moduleInfoList = device.second;
4736 for (auto &moduleInfo : moduleInfoList) {
4737 AUDIO_INFO_LOG("[module_load]::Load module[%{public}s]", moduleInfo.name.c_str());
4738 moduleInfo.sinkLatency = sinkLatencyInMsec_ != 0 ? to_string(sinkLatencyInMsec_) : "";
4739 if (OpenPortAndAddDeviceOnServiceConnected(moduleInfo)) {
4740 result = SUCCESS;
4741 }
4742 SetOffloadAvailableFromXML(moduleInfo);
4743 }
4744 }
4745 }
4746
4747 if (result == SUCCESS) {
4748 AUDIO_INFO_LOG("[module_load]::Setting speaker as active device on bootup");
4749 hasModulesLoaded = true;
4750 unique_ptr<AudioDeviceDescriptor> outDevice = audioDeviceManager_.GetRenderDefaultDevice();
4751 SetCurrentOutputDevice(*outDevice);
4752 unique_ptr<AudioDeviceDescriptor> inDevice = audioDeviceManager_.GetCaptureDefaultDevice();
4753 SetCurrenInputDevice(*inDevice);
4754 SetVolumeForSwitchDevice(GetCurrentOutputDeviceType());
4755 OnPreferredDeviceUpdated(GetCurrentOutputDevice(), GetCurrentInputDeviceType());
4756 AddEarpiece();
4757 for (auto it = pnpDeviceList_.begin(); it != pnpDeviceList_.end(); ++it) {
4758 OnPnpDeviceStatusUpdated((*it).first, (*it).second);
4759 }
4760 audioEffectService_.SetMasterSinkAvailable();
4761 }
4762 // load inner-cap-sink
4763 LoadModernInnerCapSink();
4764 // RegisterBluetoothListener() will be called when bluetooth_host is online
4765 // load hdi-effect-model
4766 LoadHdiEffectModel();
4767 }
4768
checkOffloadAvailable(AudioModuleInfo & moduleInfo)4769 void AudioPolicyService::checkOffloadAvailable(AudioModuleInfo& moduleInfo)
4770 {
4771 if (moduleInfo.name == "Speaker") {
4772 for (auto& portInfo: moduleInfo.ports) {
4773 if ((portInfo.adapterName == "primary") && (portInfo.offloadEnable == "1")) {
4774 isOffloadAvailable_ = true;
4775 }
4776 }
4777 }
4778 }
4779
OnServiceDisconnected(AudioServiceIndex serviceIndex)4780 void AudioPolicyService::OnServiceDisconnected(AudioServiceIndex serviceIndex)
4781 {
4782 AUDIO_WARNING_LOG("Start for [%{public}d]", serviceIndex);
4783 }
4784
OnForcedDeviceSelected(DeviceType devType,const std::string & macAddress)4785 void AudioPolicyService::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress)
4786 {
4787 if (macAddress.empty()) {
4788 AUDIO_ERR_LOG("OnForcedDeviceSelected failed as the macAddress is empty!");
4789 return;
4790 }
4791 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
4792 AUDIO_INFO_LOG("bt select device type[%{public}d] address[%{public}s]",
4793 devType, GetEncryptAddr(macAddress).c_str());
4794 std::vector<unique_ptr<AudioDeviceDescriptor>> bluetoothDevices =
4795 audioDeviceManager_.GetAvailableBluetoothDevice(devType, macAddress);
4796 std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors;
4797 for (auto &dec : bluetoothDevices) {
4798 if (dec->deviceRole_ == DeviceRole::OUTPUT_DEVICE) {
4799 sptr<AudioDeviceDescriptor> tempDec = new(std::nothrow) AudioDeviceDescriptor(*dec);
4800 audioDeviceDescriptors.push_back(move(tempDec));
4801 }
4802 }
4803 int32_t res = DeviceParamsCheck(DeviceRole::OUTPUT_DEVICE, audioDeviceDescriptors);
4804 CHECK_AND_RETURN_LOG(res == SUCCESS, "OnForcedDeviceSelected DeviceParamsCheck no success");
4805 audioDeviceDescriptors[0]->isEnable_ = true;
4806 audioDeviceManager_.UpdateDevicesListInfo(audioDeviceDescriptors[0], ENABLE_UPDATE);
4807 if (devType == DEVICE_TYPE_BLUETOOTH_SCO) {
4808 SetPreferredDevice(AUDIO_CALL_RENDER, audioDeviceDescriptors[0]);
4809 ClearScoDeviceSuspendState(audioDeviceDescriptors[0]->macAddress_);
4810 } else {
4811 SetPreferredDevice(AUDIO_MEDIA_RENDER, audioDeviceDescriptors[0]);
4812 }
4813 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
4814 }
4815
OnMonoAudioConfigChanged(bool audioMono)4816 void AudioPolicyService::OnMonoAudioConfigChanged(bool audioMono)
4817 {
4818 AUDIO_DEBUG_LOG("audioMono = %{public}s", audioMono? "true": "false");
4819 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
4820 CHECK_AND_RETURN_LOG(gsp != nullptr, "OnMonoAudioConfigChanged, Audio Server Proxy is null");
4821 std::string identity = IPCSkeleton::ResetCallingIdentity();
4822 gsp->SetAudioMonoState(audioMono);
4823 IPCSkeleton::SetCallingIdentity(identity);
4824 }
4825
OnAudioBalanceChanged(float audioBalance)4826 void AudioPolicyService::OnAudioBalanceChanged(float audioBalance)
4827 {
4828 AUDIO_DEBUG_LOG("audioBalance = %{public}f", audioBalance);
4829 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
4830 CHECK_AND_RETURN_LOG(gsp != nullptr, "OnMonoAudioConfigChanged, Audio Server Proxy is null");
4831 std::string identity = IPCSkeleton::ResetCallingIdentity();
4832 gsp->SetAudioBalanceValue(audioBalance);
4833 IPCSkeleton::SetCallingIdentity(identity);
4834 }
4835
UpdateEffectDefaultSink(DeviceType deviceType)4836 void AudioPolicyService::UpdateEffectDefaultSink(DeviceType deviceType)
4837 {
4838 Trace trace("OnPreferredOutputDeviceUpdated:" + std::to_string(deviceType));
4839 effectActiveDevice_ = deviceType;
4840 switch (deviceType) {
4841 case DeviceType::DEVICE_TYPE_EARPIECE:
4842 case DeviceType::DEVICE_TYPE_SPEAKER:
4843 case DeviceType::DEVICE_TYPE_FILE_SINK:
4844 case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
4845 case DeviceType::DEVICE_TYPE_USB_HEADSET:
4846 case DeviceType::DEVICE_TYPE_DP:
4847 case DeviceType::DEVICE_TYPE_USB_ARM_HEADSET:
4848 case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
4849 case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO: {
4850 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
4851 CHECK_AND_RETURN_LOG(gsp != nullptr, "Service proxy unavailable");
4852 std::string sinkName = GetSinkPortName(deviceType);
4853 std::string identity = IPCSkeleton::ResetCallingIdentity();
4854 gsp->SetOutputDeviceSink(deviceType, sinkName);
4855 IPCSkeleton::SetCallingIdentity(identity);
4856
4857 break;
4858 }
4859 default:
4860 break;
4861 }
4862 }
4863
LoadSinksForCapturer()4864 void AudioPolicyService::LoadSinksForCapturer()
4865 {
4866 AUDIO_INFO_LOG("Start");
4867 AudioStreamInfo streamInfo;
4868 LoadInnerCapturerSink(INNER_CAPTURER_SINK_LEGACY, streamInfo);
4869
4870 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
4871 CHECK_AND_RETURN_LOG(gsp != nullptr, "LoadSinksForCapturer error for gsp null");
4872 std::string identity = IPCSkeleton::ResetCallingIdentity();
4873 bool ret = gsp->CreatePlaybackCapturerManager();
4874 IPCSkeleton::SetCallingIdentity(identity);
4875 CHECK_AND_RETURN_LOG(ret, "PlaybackCapturerManager create failed");
4876 }
4877
LoadInnerCapturerSink(string moduleName,AudioStreamInfo streamInfo)4878 void AudioPolicyService::LoadInnerCapturerSink(string moduleName, AudioStreamInfo streamInfo)
4879 {
4880 AUDIO_INFO_LOG("Start");
4881 uint32_t bufferSize = (streamInfo.samplingRate * GetSampleFormatValue(streamInfo.format)
4882 * streamInfo.channels) / PCM_8_BIT * RENDER_FRAME_INTERVAL_IN_SECONDS;
4883
4884 AudioModuleInfo moduleInfo = {};
4885 moduleInfo.lib = "libmodule-inner-capturer-sink.z.so";
4886 moduleInfo.format = ConvertToHDIAudioFormat(streamInfo.format);
4887 moduleInfo.name = moduleName;
4888 moduleInfo.networkId = "LocalDevice";
4889 moduleInfo.channels = std::to_string(streamInfo.channels);
4890 moduleInfo.rate = std::to_string(streamInfo.samplingRate);
4891 moduleInfo.bufferSize = std::to_string(bufferSize);
4892
4893 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
4894 }
4895
UnloadInnerCapturerSink(string moduleName)4896 void AudioPolicyService::UnloadInnerCapturerSink(string moduleName)
4897 {
4898 ClosePortAndEraseIOHandle(moduleName);
4899 }
4900
LoadModernInnerCapSink()4901 void AudioPolicyService::LoadModernInnerCapSink()
4902 {
4903 AUDIO_INFO_LOG("Start");
4904 AudioModuleInfo moduleInfo = {};
4905 moduleInfo.lib = "libmodule-inner-capturer-sink.z.so";
4906 moduleInfo.name = INNER_CAPTURER_SINK;
4907
4908 moduleInfo.format = "s16le";
4909 moduleInfo.channels = "2"; // 2 channel
4910 moduleInfo.rate = "48000";
4911 moduleInfo.bufferSize = "3840"; // 20ms
4912
4913 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
4914 }
4915
LoadEffectLibrary()4916 void AudioPolicyService::LoadEffectLibrary()
4917 {
4918 // IPC -> audioservice load library
4919 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
4920 CHECK_AND_RETURN_LOG(gsp != nullptr, "LoadEffectLibrary, Audio Server Proxy is null");
4921 OriginalEffectConfig oriEffectConfig = {};
4922 audioEffectService_.GetOriginalEffectConfig(oriEffectConfig);
4923 vector<Effect> successLoadedEffects;
4924 std::string identity = IPCSkeleton::ResetCallingIdentity();
4925 bool loadSuccess = gsp->LoadAudioEffectLibraries(oriEffectConfig.libraries,
4926 oriEffectConfig.effects,
4927 successLoadedEffects);
4928 IPCSkeleton::SetCallingIdentity(identity);
4929 if (!loadSuccess) {
4930 AUDIO_ERR_LOG("Load audio effect failed, please check log");
4931 }
4932
4933 audioEffectService_.UpdateAvailableEffects(successLoadedEffects);
4934 audioEffectService_.BuildAvailableAEConfig();
4935
4936 // Initialize EffectChainManager in audio service through IPC
4937 SupportedEffectConfig supportedEffectConfig;
4938 audioEffectService_.GetSupportedEffectConfig(supportedEffectConfig);
4939 EffectChainManagerParam effectChainManagerParam;
4940 EffectChainManagerParam enhanceChainManagerParam;
4941 audioEffectService_.ConstructEffectChainManagerParam(effectChainManagerParam);
4942 audioEffectService_.ConstructEnhanceChainManagerParam(enhanceChainManagerParam);
4943
4944 identity = IPCSkeleton::ResetCallingIdentity();
4945 bool ret = gsp->CreateEffectChainManager(supportedEffectConfig.effectChains,
4946 effectChainManagerParam, enhanceChainManagerParam);
4947 IPCSkeleton::SetCallingIdentity(identity);
4948 CHECK_AND_RETURN_LOG(ret, "EffectChainManager create failed");
4949
4950 audioEffectService_.SetEffectChainManagerAvailable();
4951 AudioSpatializationService::GetAudioSpatializationService().Init(supportedEffectConfig.effectChains);
4952 }
4953
GetEffectManagerInfo()4954 void AudioPolicyService::GetEffectManagerInfo()
4955 {
4956 converterConfig_ = GetConverterConfig();
4957 audioEffectService_.GetSupportedEffectConfig(supportedEffectConfig_);
4958 }
4959
AddAudioDevice(AudioModuleInfo & moduleInfo,InternalDeviceType devType)4960 void AudioPolicyService::AddAudioDevice(AudioModuleInfo& moduleInfo, InternalDeviceType devType)
4961 {
4962 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
4963
4964 // add new device into active device list
4965 std::string volumeGroupName = GetGroupName(moduleInfo.name, VOLUME_TYPE);
4966 std::string interruptGroupName = GetGroupName(moduleInfo.name, INTERRUPT_TYPE);
4967 int32_t volumeGroupId = GROUP_ID_NONE;
4968 int32_t interruptGroupId = GROUP_ID_NONE;
4969 UpdateGroupInfo(GroupType::VOLUME_TYPE, volumeGroupName, volumeGroupId, LOCAL_NETWORK_ID, true,
4970 NO_REMOTE_ID);
4971 UpdateGroupInfo(GroupType::INTERRUPT_TYPE, interruptGroupName, interruptGroupId, LOCAL_NETWORK_ID,
4972 true, NO_REMOTE_ID);
4973
4974 sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(devType,
4975 GetDeviceRole(moduleInfo.role), volumeGroupId, interruptGroupId, LOCAL_NETWORK_ID);
4976 if (!moduleInfo.supportedRate_.empty() && !moduleInfo.supportedChannels_.empty()) {
4977 DeviceStreamInfo streamInfo = {};
4978 for (auto supportedRate : moduleInfo.supportedRate_) {
4979 streamInfo.samplingRate.insert(static_cast<AudioSamplingRate>(supportedRate));
4980 }
4981 for (auto supportedChannels : moduleInfo.supportedChannels_) {
4982 streamInfo.channels.insert(static_cast<AudioChannel>(supportedChannels));
4983 }
4984 audioDescriptor->SetDeviceCapability(streamInfo, 0);
4985 }
4986
4987 audioDescriptor->deviceId_ = startDeviceId++;
4988 UpdateDisplayName(audioDescriptor);
4989 audioDeviceManager_.AddNewDevice(audioDescriptor);
4990 connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
4991 AddMicrophoneDescriptor(audioDescriptor);
4992 }
4993
OnAudioPolicyXmlParsingCompleted(const std::unordered_map<AdaptersType,AudioAdapterInfo> adapterInfoMap)4994 void AudioPolicyService::OnAudioPolicyXmlParsingCompleted(
4995 const std::unordered_map<AdaptersType, AudioAdapterInfo> adapterInfoMap)
4996 {
4997 AUDIO_INFO_LOG("adapterInfo num [%{public}zu]", adapterInfoMap.size());
4998 CHECK_AND_RETURN_LOG(!adapterInfoMap.empty(), "failed to parse audiopolicy xml file. Received data is empty");
4999 adapterInfoMap_ = adapterInfoMap;
5000
5001 for (auto &adapterInfo : adapterInfoMap_) {
5002 for (auto &deviceInfos : (adapterInfo.second).deviceInfos_) {
5003 if (deviceInfos.type_ == EARPIECE_TYPE_NAME) {
5004 AUDIO_INFO_LOG("Has earpiece");
5005 hasEarpiece_ = true;
5006 break;
5007 }
5008 }
5009 if (hasEarpiece_) {
5010 break;
5011 }
5012 }
5013 isAdapterInfoMap_.store(true);
5014
5015 audioDeviceManager_.UpdateEarpieceStatus(hasEarpiece_);
5016 }
5017
5018 // Parser callbacks
OnXmlParsingCompleted(const std::unordered_map<ClassType,std::list<AudioModuleInfo>> & xmlData)5019 void AudioPolicyService::OnXmlParsingCompleted(const std::unordered_map<ClassType, std::list<AudioModuleInfo>> &xmlData)
5020 {
5021 AUDIO_INFO_LOG("device class num [%{public}zu]", xmlData.size());
5022 CHECK_AND_RETURN_LOG(!xmlData.empty(), "failed to parse xml file. Received data is empty");
5023
5024 deviceClassInfo_ = xmlData;
5025 }
5026
OnVolumeGroupParsed(std::unordered_map<std::string,std::string> & volumeGroupData)5027 void AudioPolicyService::OnVolumeGroupParsed(std::unordered_map<std::string, std::string>& volumeGroupData)
5028 {
5029 AUDIO_INFO_LOG("group data num [%{public}zu]", volumeGroupData.size());
5030 CHECK_AND_RETURN_LOG(!volumeGroupData.empty(), "failed to parse xml file. Received data is empty");
5031
5032 volumeGroupData_ = volumeGroupData;
5033 }
5034
OnInterruptGroupParsed(std::unordered_map<std::string,std::string> & interruptGroupData)5035 void AudioPolicyService::OnInterruptGroupParsed(std::unordered_map<std::string, std::string>& interruptGroupData)
5036 {
5037 AUDIO_INFO_LOG("group data num [%{public}zu]", interruptGroupData.size());
5038 CHECK_AND_RETURN_LOG(!interruptGroupData.empty(), "failed to parse xml file. Received data is empty");
5039
5040 interruptGroupData_ = interruptGroupData;
5041 }
5042
OnGlobalConfigsParsed(GlobalConfigs & globalConfigs)5043 void AudioPolicyService::OnGlobalConfigsParsed(GlobalConfigs &globalConfigs)
5044 {
5045 globalConfigs_ = globalConfigs;
5046 }
5047
OnVoipConfigParsed(bool enableFastVoip)5048 void AudioPolicyService::OnVoipConfigParsed(bool enableFastVoip)
5049 {
5050 enableFastVoip_ = enableFastVoip;
5051 }
5052
GetAudioAdapterInfos(std::unordered_map<AdaptersType,AudioAdapterInfo> & adapterInfoMap)5053 void AudioPolicyService::GetAudioAdapterInfos(std::unordered_map<AdaptersType, AudioAdapterInfo> &adapterInfoMap)
5054 {
5055 adapterInfoMap = adapterInfoMap_;
5056 }
5057
GetVolumeGroupData(std::unordered_map<std::string,std::string> & volumeGroupData)5058 void AudioPolicyService::GetVolumeGroupData(std::unordered_map<std::string, std::string>& volumeGroupData)
5059 {
5060 volumeGroupData = volumeGroupData_;
5061 }
5062
GetInterruptGroupData(std::unordered_map<std::string,std::string> & interruptGroupData)5063 void AudioPolicyService::GetInterruptGroupData(std::unordered_map<std::string, std::string>& interruptGroupData)
5064 {
5065 interruptGroupData = interruptGroupData_;
5066 }
5067
GetDeviceClassInfo(std::unordered_map<ClassType,std::list<AudioModuleInfo>> & deviceClassInfo)5068 void AudioPolicyService::GetDeviceClassInfo(std::unordered_map<ClassType, std::list<AudioModuleInfo>> &deviceClassInfo)
5069 {
5070 deviceClassInfo = deviceClassInfo_;
5071 }
5072
GetGlobalConfigs(GlobalConfigs & globalConfigs)5073 void AudioPolicyService::GetGlobalConfigs(GlobalConfigs &globalConfigs)
5074 {
5075 globalConfigs = globalConfigs_;
5076 }
5077
GetVoipConfig()5078 bool AudioPolicyService::GetVoipConfig()
5079 {
5080 return enableFastVoip_;
5081 }
5082
AddAudioPolicyClientProxyMap(int32_t clientPid,const sptr<IAudioPolicyClient> & cb)5083 void AudioPolicyService::AddAudioPolicyClientProxyMap(int32_t clientPid, const sptr<IAudioPolicyClient>& cb)
5084 {
5085 if (audioPolicyServerHandler_ != nullptr) {
5086 audioPolicyServerHandler_->AddAudioPolicyClientProxyMap(clientPid, cb);
5087 }
5088 }
5089
ReduceAudioPolicyClientProxyMap(pid_t clientPid)5090 void AudioPolicyService::ReduceAudioPolicyClientProxyMap(pid_t clientPid)
5091 {
5092 if (audioPolicyServerHandler_ != nullptr) {
5093 audioPolicyServerHandler_->RemoveAudioPolicyClientProxyMap(clientPid);
5094 }
5095 }
5096
SetAvailableDeviceChangeCallback(const int32_t clientId,const AudioDeviceUsage usage,const sptr<IRemoteObject> & object,bool hasBTPermission)5097 int32_t AudioPolicyService::SetAvailableDeviceChangeCallback(const int32_t clientId, const AudioDeviceUsage usage,
5098 const sptr<IRemoteObject> &object, bool hasBTPermission)
5099 {
5100 sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object);
5101
5102 if (callback != nullptr) {
5103 callback->hasBTPermission_ = hasBTPermission;
5104
5105 if (audioPolicyServerHandler_ != nullptr) {
5106 audioPolicyServerHandler_->AddAvailableDeviceChangeMap(clientId, usage, callback);
5107 }
5108 }
5109
5110 return SUCCESS;
5111 }
5112
SetQueryClientTypeCallback(const sptr<IRemoteObject> & object)5113 int32_t AudioPolicyService::SetQueryClientTypeCallback(const sptr<IRemoteObject> &object)
5114 {
5115 #ifdef FEATURE_APPGALLERY
5116 sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object);
5117 if (callback != nullptr) {
5118 ClientTypeManager::GetInstance()->SetQueryClientTypeCallback(callback);
5119 } else {
5120 AUDIO_ERR_LOG("Client type callback is null");
5121 }
5122 #endif
5123 return SUCCESS;
5124 }
5125
UnsetAvailableDeviceChangeCallback(const int32_t clientId,AudioDeviceUsage usage)5126 int32_t AudioPolicyService::UnsetAvailableDeviceChangeCallback(const int32_t clientId, AudioDeviceUsage usage)
5127 {
5128 AUDIO_INFO_LOG("UnsetAvailableDeviceChangeCallback start");
5129
5130 if (audioPolicyServerHandler_ != nullptr) {
5131 audioPolicyServerHandler_->RemoveAvailableDeviceChangeMap(clientId, usage);
5132 }
5133 return SUCCESS;
5134 }
5135
UpdateRendererInfoWhenNoPermission(const unique_ptr<AudioRendererChangeInfo> & audioRendererChangeInfos,bool hasSystemPermission)5136 static void UpdateRendererInfoWhenNoPermission(const unique_ptr<AudioRendererChangeInfo> &audioRendererChangeInfos,
5137 bool hasSystemPermission)
5138 {
5139 if (!hasSystemPermission) {
5140 audioRendererChangeInfos->clientUID = 0;
5141 audioRendererChangeInfos->rendererState = RENDERER_INVALID;
5142 }
5143 }
5144
UpdateCapturerInfoWhenNoPermission(const unique_ptr<AudioCapturerChangeInfo> & audioCapturerChangeInfos,bool hasSystemPermission)5145 static void UpdateCapturerInfoWhenNoPermission(const unique_ptr<AudioCapturerChangeInfo> &audioCapturerChangeInfos,
5146 bool hasSystemPermission)
5147 {
5148 if (!hasSystemPermission) {
5149 audioCapturerChangeInfos->clientUID = 0;
5150 audioCapturerChangeInfos->capturerState = CAPTURER_INVALID;
5151 }
5152 }
5153
HasLowLatencyCapability(DeviceType deviceType,bool isRemote)5154 bool AudioPolicyService::HasLowLatencyCapability(DeviceType deviceType, bool isRemote)
5155 {
5156 // Distributed devices are low latency devices
5157 if (isRemote) {
5158 return true;
5159 }
5160
5161 switch (deviceType) {
5162 case DeviceType::DEVICE_TYPE_EARPIECE:
5163 case DeviceType::DEVICE_TYPE_SPEAKER:
5164 case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
5165 case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
5166 case DeviceType::DEVICE_TYPE_USB_HEADSET:
5167 case DeviceType::DEVICE_TYPE_DP:
5168 return true;
5169
5170 case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
5171 case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
5172 return false;
5173 default:
5174 return false;
5175 }
5176 }
5177
UpdateDeviceInfo(AudioDeviceDescriptor & deviceInfo,const sptr<AudioDeviceDescriptor> & desc,bool hasBTPermission,bool hasSystemPermission)5178 void AudioPolicyService::UpdateDeviceInfo(AudioDeviceDescriptor &deviceInfo, const sptr<AudioDeviceDescriptor> &desc,
5179 bool hasBTPermission, bool hasSystemPermission)
5180 {
5181 deviceInfo.deviceType_ = desc->deviceType_;
5182 deviceInfo.deviceRole_ = desc->deviceRole_;
5183 deviceInfo.deviceId_ = desc->deviceId_;
5184 deviceInfo.channelMasks_ = desc->channelMasks_;
5185 deviceInfo.channelIndexMasks_ = desc->channelIndexMasks_;
5186 deviceInfo.displayName_ = desc->displayName_;
5187 deviceInfo.connectState_ = desc->connectState_;
5188
5189 if (deviceInfo.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
5190 deviceInfo.a2dpOffloadFlag_ = a2dpOffloadFlag_;
5191 }
5192
5193 if (hasBTPermission) {
5194 deviceInfo.deviceName_ = desc->deviceName_;
5195 deviceInfo.macAddress_ = desc->macAddress_;
5196 deviceInfo.deviceCategory_ = desc->deviceCategory_;
5197 } else {
5198 deviceInfo.deviceName_ = "";
5199 deviceInfo.macAddress_ = "";
5200 deviceInfo.deviceCategory_ = CATEGORY_DEFAULT;
5201 }
5202
5203 deviceInfo.isLowLatencyDevice_ = HasLowLatencyCapability(deviceInfo.deviceType_,
5204 desc->networkId_ != LOCAL_NETWORK_ID);
5205
5206 if (hasSystemPermission) {
5207 deviceInfo.networkId_ = desc->networkId_;
5208 deviceInfo.volumeGroupId_ = desc->volumeGroupId_;
5209 deviceInfo.interruptGroupId_ = desc->interruptGroupId_;
5210 } else {
5211 deviceInfo.networkId_ = "";
5212 deviceInfo.volumeGroupId_ = GROUP_ID_NONE;
5213 deviceInfo.interruptGroupId_ = GROUP_ID_NONE;
5214 }
5215 deviceInfo.audioStreamInfo_.samplingRate = desc->audioStreamInfo_.samplingRate;
5216 deviceInfo.audioStreamInfo_.encoding = desc->audioStreamInfo_.encoding;
5217 deviceInfo.audioStreamInfo_.format = desc->audioStreamInfo_.format;
5218 deviceInfo.audioStreamInfo_.channels = desc->audioStreamInfo_.channels;
5219 }
5220
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object,const int32_t apiVersion)5221 int32_t AudioPolicyService::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
5222 const sptr<IRemoteObject> &object, const int32_t apiVersion)
5223 {
5224 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
5225
5226 if (mode == AUDIO_MODE_RECORD) {
5227 AddAudioCapturerMicrophoneDescriptor(streamChangeInfo.audioCapturerChangeInfo.sessionId, DEVICE_TYPE_NONE);
5228 if (apiVersion > 0 && apiVersion < API_11) {
5229 UpdateDeviceInfo(streamChangeInfo.audioCapturerChangeInfo.inputDeviceInfo,
5230 new AudioDeviceDescriptor(GetCurrentInputDevice()), false, false);
5231 }
5232 } else if (apiVersion > 0 && apiVersion < API_11) {
5233 UpdateDeviceInfo(streamChangeInfo.audioRendererChangeInfo.outputDeviceInfo,
5234 new AudioDeviceDescriptor(GetCurrentOutputDevice()), false, false);
5235 }
5236 return streamCollector_.RegisterTracker(mode, streamChangeInfo, object);
5237 }
5238
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)5239 int32_t AudioPolicyService::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
5240 {
5241 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
5242
5243 HandleAudioCaptureState(mode, streamChangeInfo);
5244 int32_t ret = streamCollector_.UpdateTracker(mode, streamChangeInfo);
5245
5246 const auto &rendererState = streamChangeInfo.audioRendererChangeInfo.rendererState;
5247 if (rendererState == RENDERER_PREPARED || rendererState == RENDERER_NEW || rendererState == RENDERER_INVALID) {
5248 return ret; // only update tracker in new and prepared
5249 }
5250
5251 if (rendererState == RENDERER_RELEASED && !streamCollector_.ExistStreamForPipe(PIPE_TYPE_MULTICHANNEL)) {
5252 DynamicUnloadModule(PIPE_TYPE_MULTICHANNEL);
5253 }
5254
5255 if (mode == AUDIO_MODE_PLAYBACK && (rendererState == RENDERER_STOPPED || rendererState == RENDERER_PAUSED ||
5256 rendererState == RENDERER_RELEASED)) {
5257 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(streamChangeInfo.audioRendererChangeInfo.sessionId);
5258 if (rendererState == RENDERER_RELEASED) {
5259 audioDeviceManager_.RemoveSelectedDefaultOutputDevice(streamChangeInfo.audioRendererChangeInfo.sessionId);
5260 }
5261 FetchDevice(true);
5262 }
5263
5264 if (enableDualHalToneState_ && (mode == AUDIO_MODE_PLAYBACK)
5265 && (rendererState == RENDERER_STOPPED || rendererState == RENDERER_RELEASED)) {
5266 const int32_t sessionId = streamChangeInfo.audioRendererChangeInfo.sessionId;
5267 const StreamUsage streamUsage = streamChangeInfo.audioRendererChangeInfo.rendererInfo.streamUsage;
5268 if ((sessionId == enableDualHalToneSessionId_) && Util::IsRingerOrAlarmerStreamUsage(streamUsage)) {
5269 AUDIO_INFO_LOG("disable dual hal tone when ringer/alarm renderer stop/release.");
5270 UpdateDualToneState(false, enableDualHalToneSessionId_);
5271 }
5272 }
5273
5274 UpdateA2dpOffloadFlagForAllStream(GetCurrentOutputDeviceType());
5275 SendA2dpConnectedWhileRunning(rendererState, streamChangeInfo.audioRendererChangeInfo.sessionId);
5276 return ret;
5277 }
5278
HandleAudioCaptureState(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)5279 void AudioPolicyService::HandleAudioCaptureState(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
5280 {
5281 if (mode == AUDIO_MODE_RECORD &&
5282 (streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_RELEASED ||
5283 streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_STOPPED)) {
5284 if (streamChangeInfo.audioCapturerChangeInfo.capturerInfo.sourceType == SOURCE_TYPE_VOICE_RECOGNITION) {
5285 BluetoothScoDisconectForRecongnition();
5286 Bluetooth::AudioHfpManager::ClearRecongnitionStatus();
5287 }
5288 audioCaptureMicrophoneDescriptor_.erase(streamChangeInfo.audioCapturerChangeInfo.sessionId);
5289 }
5290 }
5291
SendA2dpConnectedWhileRunning(const RendererState & rendererState,const uint32_t & sessionId)5292 void AudioPolicyService::SendA2dpConnectedWhileRunning(const RendererState &rendererState, const uint32_t &sessionId)
5293 {
5294 if ((rendererState == RENDERER_RUNNING) && (audioA2dpOffloadManager_ != nullptr) &&
5295 !audioA2dpOffloadManager_->IsA2dpOffloadConnecting(sessionId)) {
5296 AUDIO_INFO_LOG("Notify client not to block.");
5297 std::thread sendConnectedToClient(&AudioPolicyService::UpdateSessionConnectionState, this, sessionId,
5298 DATA_LINK_CONNECTED);
5299 sendConnectedToClient.detach();
5300 }
5301 }
5302
FetchOutputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo,const AudioStreamDeviceChangeReasonExt reason)5303 void AudioPolicyService::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo,
5304 const AudioStreamDeviceChangeReasonExt reason)
5305 {
5306 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
5307 AUDIO_INFO_LOG("fetch device for track, sessionid:%{public}d start",
5308 streamChangeInfo.audioRendererChangeInfo.sessionId);
5309
5310 AudioMode mode = AudioMode::AUDIO_MODE_PLAYBACK;
5311 // Set prerunningState true to refetch devices when device info change before update tracker to running
5312 streamChangeInfo.audioRendererChangeInfo.prerunningState = true;
5313 if (streamCollector_.UpdateTrackerInternal(mode, streamChangeInfo) != SUCCESS) {
5314 return;
5315 }
5316
5317 vector<unique_ptr<AudioRendererChangeInfo>> rendererChangeInfo;
5318 rendererChangeInfo.push_back(
5319 make_unique<AudioRendererChangeInfo>(streamChangeInfo.audioRendererChangeInfo));
5320 streamCollector_.GetRendererStreamInfo(streamChangeInfo, *rendererChangeInfo[0]);
5321
5322 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStarting(streamChangeInfo.audioRendererChangeInfo.sessionId);
5323
5324 FetchOutputDevice(rendererChangeInfo, reason);
5325 }
5326
FetchInputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo)5327 void AudioPolicyService::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo)
5328 {
5329 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
5330 AUDIO_INFO_LOG("fetch device for track, sessionid:%{public}d start",
5331 streamChangeInfo.audioRendererChangeInfo.sessionId);
5332
5333 vector<unique_ptr<AudioCapturerChangeInfo>> capturerChangeInfo;
5334 capturerChangeInfo.push_back(
5335 make_unique<AudioCapturerChangeInfo>(streamChangeInfo.audioCapturerChangeInfo));
5336 streamCollector_.GetCapturerStreamInfo(streamChangeInfo, *capturerChangeInfo[0]);
5337
5338 FetchInputDevice(capturerChangeInfo);
5339 }
5340
GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos,bool hasBTPermission,bool hasSystemPermission)5341 int32_t AudioPolicyService::GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>>
5342 &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission)
5343 {
5344 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
5345
5346 int32_t status = streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
5347 CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status,
5348 "AudioPolicyServer:: Get renderer change info failed");
5349
5350 std::vector<sptr<AudioDeviceDescriptor>> outputDevices = GetDevicesInner(OUTPUT_DEVICES_FLAG);
5351 DeviceType activeDeviceType = GetCurrentOutputDeviceType();
5352 DeviceRole activeDeviceRole = OUTPUT_DEVICE;
5353 for (sptr<AudioDeviceDescriptor> desc : outputDevices) {
5354 if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
5355 if (activeDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP &&
5356 desc->macAddress_ != GetCurrentOutputDeviceMacAddr()) {
5357 // This A2DP device is not the active A2DP device. Skip it.
5358 continue;
5359 }
5360 size_t rendererInfosSize = audioRendererChangeInfos.size();
5361 for (size_t i = 0; i < rendererInfosSize; i++) {
5362 UpdateRendererInfoWhenNoPermission(audioRendererChangeInfos[i], hasSystemPermission);
5363 UpdateDeviceInfo(audioRendererChangeInfos[i]->outputDeviceInfo, desc, hasBTPermission,
5364 hasSystemPermission);
5365 }
5366 break;
5367 }
5368 }
5369
5370 return status;
5371 }
5372
GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos,bool hasBTPermission,bool hasSystemPermission)5373 int32_t AudioPolicyService::GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>>
5374 &audioCapturerChangeInfos, bool hasBTPermission, bool hasSystemPermission)
5375 {
5376 int status = streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos);
5377 CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status,
5378 "AudioPolicyServer:: Get capturer change info failed");
5379
5380 std::vector<sptr<AudioDeviceDescriptor>> inputDevices = GetDevicesInner(INPUT_DEVICES_FLAG);
5381 DeviceType activeDeviceType = GetCurrentInputDeviceType();
5382 DeviceRole activeDeviceRole = INPUT_DEVICE;
5383 for (sptr<AudioDeviceDescriptor> desc : inputDevices) {
5384 if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
5385 size_t capturerInfosSize = audioCapturerChangeInfos.size();
5386 for (size_t i = 0; i < capturerInfosSize; i++) {
5387 UpdateCapturerInfoWhenNoPermission(audioCapturerChangeInfos[i], hasSystemPermission);
5388 UpdateDeviceInfo(audioCapturerChangeInfos[i]->inputDeviceInfo, desc, hasBTPermission,
5389 hasSystemPermission);
5390 }
5391 break;
5392 }
5393 }
5394
5395 return status;
5396 }
5397
RegisteredTrackerClientDied(pid_t uid)5398 void AudioPolicyService::RegisteredTrackerClientDied(pid_t uid)
5399 {
5400 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
5401
5402 UpdateDefaultOutputDeviceWhenStopping(static_cast<int32_t>(uid));
5403
5404 RemoveAudioCapturerMicrophoneDescriptor(static_cast<int32_t>(uid));
5405 streamCollector_.RegisteredTrackerClientDied(static_cast<int32_t>(uid));
5406
5407 ClientDiedDisconnectScoNormal();
5408 ClientDiedDisconnectScoRecognition();
5409
5410 if (!streamCollector_.ExistStreamForPipe(PIPE_TYPE_OFFLOAD)) {
5411 DynamicUnloadModule(PIPE_TYPE_OFFLOAD);
5412 }
5413
5414 if (!streamCollector_.ExistStreamForPipe(PIPE_TYPE_MULTICHANNEL)) {
5415 DynamicUnloadModule(PIPE_TYPE_MULTICHANNEL);
5416 }
5417 }
5418
ClientDiedDisconnectScoNormal()5419 void AudioPolicyService::ClientDiedDisconnectScoNormal()
5420 {
5421 DeviceType deviceType = GetCurrentOutputDeviceType();
5422 bool hasRunningRendererStream = streamCollector_.HasRunningRendererStream();
5423 if (hasRunningRendererStream && deviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
5424 return;
5425 }
5426 AUDIO_WARNING_LOG("Client died disconnect sco for normal");
5427 Bluetooth::AudioHfpManager::DisconnectSco();
5428 }
5429
ClientDiedDisconnectScoRecognition()5430 void AudioPolicyService::ClientDiedDisconnectScoRecognition()
5431 {
5432 bool hasRunningRecognitionCapturerStream = streamCollector_.HasRunningRecognitionCapturerStream();
5433 if (hasRunningRecognitionCapturerStream) {
5434 return;
5435 }
5436 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice();
5437 if (tempDesc.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO) {
5438 return;
5439 }
5440 if (Bluetooth::AudioHfpManager::GetScoCategory() == Bluetooth::ScoCategory::SCO_RECOGNITION ||
5441 Bluetooth::AudioHfpManager::GetRecognitionStatus() == Bluetooth::RecognitionStatus::RECOGNITION_CONNECTING) {
5442 AUDIO_WARNING_LOG("Client died disconnect sco for recognition");
5443 BluetoothScoDisconectForRecongnition();
5444 Bluetooth::AudioHfpManager::ClearRecongnitionStatus();
5445 }
5446 }
5447
ReconfigureAudioChannel(const uint32_t & channelCount,DeviceType deviceType)5448 int32_t AudioPolicyService::ReconfigureAudioChannel(const uint32_t &channelCount, DeviceType deviceType)
5449 {
5450 if (GetCurrentOutputDeviceType() != DEVICE_TYPE_FILE_SINK) {
5451 AUDIO_INFO_LOG("FILE_SINK_DEVICE is not active. Cannot reconfigure now");
5452 return ERROR;
5453 }
5454
5455 std::string module = FILE_SINK;
5456
5457 if (deviceType == DeviceType::DEVICE_TYPE_FILE_SINK) {
5458 CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_8 && channelCount >= MONO, ERROR, "Invalid sink channel");
5459 module = FILE_SINK;
5460 } else if (deviceType == DeviceType::DEVICE_TYPE_FILE_SOURCE) {
5461 CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_6 && channelCount >= MONO, ERROR, "Invalid src channel");
5462 module = FILE_SOURCE;
5463 } else {
5464 AUDIO_ERR_LOG("Invalid DeviceType");
5465 return ERROR;
5466 }
5467
5468 ClosePortAndEraseIOHandle(module);
5469
5470 auto fileClass = deviceClassInfo_.find(ClassType::TYPE_FILE_IO);
5471 if (fileClass != deviceClassInfo_.end()) {
5472 auto moduleInfoList = fileClass->second;
5473 for (auto &moduleInfo : moduleInfoList) {
5474 if (module == moduleInfo.name) {
5475 moduleInfo.channels = to_string(channelCount);
5476 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
5477 audioPolicyManager_.SetDeviceActive(deviceType, module, true);
5478 }
5479 }
5480 }
5481
5482 return SUCCESS;
5483 }
5484
5485 // private methods
GetSinkIOHandle(InternalDeviceType deviceType)5486 AudioIOHandle AudioPolicyService::GetSinkIOHandle(InternalDeviceType deviceType)
5487 {
5488 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
5489 AudioIOHandle ioHandle;
5490 switch (deviceType) {
5491 case InternalDeviceType::DEVICE_TYPE_WIRED_HEADSET:
5492 case InternalDeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
5493 case InternalDeviceType::DEVICE_TYPE_USB_HEADSET:
5494 case InternalDeviceType::DEVICE_TYPE_EARPIECE:
5495 case InternalDeviceType::DEVICE_TYPE_SPEAKER:
5496 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
5497 ioHandle = IOHandles_[PRIMARY_SPEAKER];
5498 break;
5499 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET:
5500 ioHandle = IOHandles_[USB_SPEAKER];
5501 break;
5502 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
5503 ioHandle = IOHandles_[BLUETOOTH_SPEAKER];
5504 break;
5505 case InternalDeviceType::DEVICE_TYPE_FILE_SINK:
5506 ioHandle = IOHandles_[FILE_SINK];
5507 break;
5508 case InternalDeviceType::DEVICE_TYPE_DP:
5509 ioHandle = IOHandles_[DP_SINK];
5510 break;
5511 default:
5512 ioHandle = IOHandles_[PRIMARY_SPEAKER];
5513 break;
5514 }
5515 return ioHandle;
5516 }
5517
GetSourceIOHandle(InternalDeviceType deviceType)5518 AudioIOHandle AudioPolicyService::GetSourceIOHandle(InternalDeviceType deviceType)
5519 {
5520 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
5521 AudioIOHandle ioHandle;
5522 switch (deviceType) {
5523 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET:
5524 ioHandle = IOHandles_[USB_MIC];
5525 break;
5526 case InternalDeviceType::DEVICE_TYPE_MIC:
5527 ioHandle = IOHandles_[PRIMARY_MIC];
5528 break;
5529 case InternalDeviceType::DEVICE_TYPE_FILE_SOURCE:
5530 ioHandle = IOHandles_[FILE_SOURCE];
5531 break;
5532 default:
5533 ioHandle = IOHandles_[PRIMARY_MIC];
5534 break;
5535 }
5536 return ioHandle;
5537 }
5538
GetDeviceType(const std::string & deviceName)5539 InternalDeviceType AudioPolicyService::GetDeviceType(const std::string &deviceName)
5540 {
5541 InternalDeviceType devType = InternalDeviceType::DEVICE_TYPE_NONE;
5542 if (deviceName == "Speaker") {
5543 devType = InternalDeviceType::DEVICE_TYPE_SPEAKER;
5544 } else if (deviceName == "Built_in_mic") {
5545 devType = InternalDeviceType::DEVICE_TYPE_MIC;
5546 } else if (deviceName == "Built_in_wakeup") {
5547 devType = InternalDeviceType::DEVICE_TYPE_WAKEUP;
5548 } else if (deviceName == "fifo_output" || deviceName == "fifo_input") {
5549 devType = DEVICE_TYPE_BLUETOOTH_SCO;
5550 } else if (deviceName == "file_sink") {
5551 devType = DEVICE_TYPE_FILE_SINK;
5552 } else if (deviceName == "file_source") {
5553 devType = DEVICE_TYPE_FILE_SOURCE;
5554 }
5555
5556 return devType;
5557 }
5558
GetGroupName(const std::string & deviceName,const GroupType type)5559 std::string AudioPolicyService::GetGroupName(const std::string& deviceName, const GroupType type)
5560 {
5561 std::string groupName = GROUP_NAME_NONE;
5562 if (type == VOLUME_TYPE) {
5563 auto iter = volumeGroupData_.find(deviceName);
5564 if (iter != volumeGroupData_.end()) {
5565 groupName = iter->second;
5566 }
5567 } else {
5568 auto iter = interruptGroupData_.find(deviceName);
5569 if (iter != interruptGroupData_.end()) {
5570 groupName = iter->second;
5571 }
5572 }
5573 return groupName;
5574 }
5575
WriteDeviceChangedSysEvents(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)5576 void AudioPolicyService::WriteDeviceChangedSysEvents(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected)
5577 {
5578 Trace trace("AudioPolicyService::WriteDeviceChangedSysEvents");
5579 for (auto deviceDescriptor : desc) {
5580 if (deviceDescriptor != nullptr) {
5581 if ((deviceDescriptor->deviceType_ == DEVICE_TYPE_WIRED_HEADSET)
5582 || (deviceDescriptor->deviceType_ == DEVICE_TYPE_USB_HEADSET)
5583 || (deviceDescriptor->deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES)) {
5584 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
5585 Media::MediaMonitor::AUDIO, Media::MediaMonitor::HEADSET_CHANGE,
5586 Media::MediaMonitor::BEHAVIOR_EVENT);
5587 bean->Add("HASMIC", 1);
5588 bean->Add("ISCONNECT", isConnected ? 1 : 0);
5589 bean->Add("DEVICETYPE", deviceDescriptor->deviceType_);
5590 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
5591 }
5592
5593 if (!isConnected) {
5594 continue;
5595 }
5596
5597 if (deviceDescriptor->deviceRole_ == OUTPUT_DEVICE) {
5598 vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
5599 for (SinkInput sinkInput : sinkInputs) {
5600 WriteOutDeviceChangedSysEvents(deviceDescriptor, sinkInput);
5601 }
5602 } else if (deviceDescriptor->deviceRole_ == INPUT_DEVICE) {
5603 vector<SourceOutput> sourceOutputs;
5604 {
5605 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
5606 if (std::any_of(IOHandles_.cbegin(), IOHandles_.cend(), [](const auto &pair) {
5607 return std::find(SourceNames.cbegin(), SourceNames.cend(), pair.first) != SourceNames.end();
5608 })) {
5609 sourceOutputs = audioPolicyManager_.GetAllSourceOutputs();
5610 }
5611 }
5612 for (SourceOutput sourceOutput : sourceOutputs) {
5613 WriteInDeviceChangedSysEvents(deviceDescriptor, sourceOutput);
5614 }
5615 }
5616 }
5617 }
5618 }
5619
WriteOutDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> & deviceDescriptor,const SinkInput & sinkInput)5620 void AudioPolicyService::WriteOutDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> &deviceDescriptor,
5621 const SinkInput &sinkInput)
5622 {
5623 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
5624 Media::MediaMonitor::AUDIO, Media::MediaMonitor::DEVICE_CHANGE,
5625 Media::MediaMonitor::BEHAVIOR_EVENT);
5626 bean->Add("ISOUTPUT", 1);
5627 bean->Add("STREAMID", sinkInput.streamId);
5628 bean->Add("STREAMTYPE", sinkInput.streamType);
5629 bean->Add("DEVICETYPE", deviceDescriptor->deviceType_);
5630 bean->Add("NETWORKID", ConvertNetworkId(deviceDescriptor->networkId_));
5631 bean->Add("ADDRESS", GetEncryptAddr(deviceDescriptor->macAddress_));
5632 bean->Add("DEVICE_NAME", deviceDescriptor->deviceName_);
5633 bean->Add("BT_TYPE", deviceDescriptor->deviceCategory_);
5634 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
5635 }
5636
WriteInDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> & deviceDescriptor,const SourceOutput & sourceOutput)5637 void AudioPolicyService::WriteInDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> &deviceDescriptor,
5638 const SourceOutput &sourceOutput)
5639 {
5640 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
5641 Media::MediaMonitor::AUDIO, Media::MediaMonitor::DEVICE_CHANGE,
5642 Media::MediaMonitor::BEHAVIOR_EVENT);
5643 bean->Add("ISOUTPUT", 0);
5644 bean->Add("STREAMID", sourceOutput.streamId);
5645 bean->Add("STREAMTYPE", sourceOutput.streamType);
5646 bean->Add("DEVICETYPE", deviceDescriptor->deviceType_);
5647 bean->Add("NETWORKID", ConvertNetworkId(deviceDescriptor->networkId_));
5648 bean->Add("ADDRESS", GetEncryptAddr(deviceDescriptor->macAddress_));
5649 bean->Add("DEVICE_NAME", deviceDescriptor->deviceName_);
5650 bean->Add("BT_TYPE", deviceDescriptor->deviceCategory_);
5651 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
5652 }
5653
UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> & desc)5654 void AudioPolicyService::UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> &desc)
5655 {
5656 AUDIO_INFO_LOG("UpdateTrackerDeviceChange start");
5657
5658 DeviceType activeDevice = DEVICE_TYPE_NONE;
5659 auto isOutputDevicePresent = [&activeDevice, this] (const sptr<AudioDeviceDescriptor> &desc) {
5660 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
5661 if ((activeDevice == desc->deviceType_) && (OUTPUT_DEVICE == desc->deviceRole_)) {
5662 if (activeDevice == DEVICE_TYPE_BLUETOOTH_A2DP) {
5663 // If the device type is A2DP, need to compare mac address in addition.
5664 return desc->macAddress_ == GetCurrentOutputDeviceMacAddr();
5665 }
5666 return true;
5667 }
5668 return false;
5669 };
5670 auto isInputDevicePresent = [&activeDevice] (const sptr<AudioDeviceDescriptor> &desc) {
5671 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
5672 return ((activeDevice == desc->deviceType_) && (INPUT_DEVICE == desc->deviceRole_));
5673 };
5674
5675 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
5676 for (sptr<AudioDeviceDescriptor> deviceDesc : desc) {
5677 if (deviceDesc->deviceRole_ == OUTPUT_DEVICE) {
5678 activeDevice = curOutputDeviceType;
5679 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isOutputDevicePresent);
5680 if (itr != connectedDevices_.end()) {
5681 AudioDeviceDescriptor outputDevice(AudioDeviceDescriptor::DEVICE_INFO);
5682 UpdateDeviceInfo(outputDevice, *itr, true, true);
5683 streamCollector_.UpdateTracker(AUDIO_MODE_PLAYBACK, outputDevice);
5684 }
5685 }
5686
5687 if (deviceDesc->deviceRole_ == INPUT_DEVICE) {
5688 activeDevice = GetCurrentInputDeviceType();
5689 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isInputDevicePresent);
5690 if (itr != connectedDevices_.end()) {
5691 AudioDeviceDescriptor inputDevice(AudioDeviceDescriptor::DEVICE_INFO);
5692 UpdateDeviceInfo(inputDevice, *itr, true, true);
5693 UpdateAudioCapturerMicrophoneDescriptor((*itr)->deviceType_);
5694 streamCollector_.UpdateTracker(AUDIO_MODE_RECORD, inputDevice);
5695 }
5696 }
5697 }
5698 }
5699
UpdateGroupInfo(GroupType type,std::string groupName,int32_t & groupId,std::string networkId,bool connected,int32_t mappingId)5700 void AudioPolicyService::UpdateGroupInfo(GroupType type, std::string groupName, int32_t& groupId, std::string networkId,
5701 bool connected, int32_t mappingId)
5702 {
5703 ConnectType connectType = CONNECT_TYPE_LOCAL;
5704 if (networkId != LOCAL_NETWORK_ID) {
5705 connectType = CONNECT_TYPE_DISTRIBUTED;
5706 }
5707 if (type == GroupType::VOLUME_TYPE) {
5708 auto isPresent = [&groupName, &networkId] (const sptr<VolumeGroupInfo> &volumeInfo) {
5709 return ((groupName == volumeInfo->groupName_) || (networkId == volumeInfo->networkId_));
5710 };
5711
5712 auto iter = std::find_if(volumeGroups_.begin(), volumeGroups_.end(), isPresent);
5713 if (iter != volumeGroups_.end()) {
5714 groupId = (*iter)->volumeGroupId_;
5715 // if status is disconnected, remove the group that has none audio device
5716 std::vector<sptr<AudioDeviceDescriptor>> devsInGroup = GetDevicesForGroup(type, groupId);
5717 if (!connected && devsInGroup.size() == 0) {
5718 volumeGroups_.erase(iter);
5719 }
5720 return;
5721 }
5722 if (groupName != GROUP_NAME_NONE && connected) {
5723 groupId = AudioGroupHandle::GetInstance().GetNextId(type);
5724 sptr<VolumeGroupInfo> volumeGroupInfo = new(std::nothrow) VolumeGroupInfo(groupId,
5725 mappingId, groupName, networkId, connectType);
5726 volumeGroups_.push_back(volumeGroupInfo);
5727 }
5728 } else {
5729 auto isPresent = [&groupName, &networkId] (const sptr<InterruptGroupInfo> &info) {
5730 return ((groupName == info->groupName_) || (networkId == info->networkId_));
5731 };
5732
5733 auto iter = std::find_if(interruptGroups_.begin(), interruptGroups_.end(), isPresent);
5734 if (iter != interruptGroups_.end()) {
5735 groupId = (*iter)->interruptGroupId_;
5736 // if status is disconnected, remove the group that has none audio device
5737 std::vector<sptr<AudioDeviceDescriptor>> devsInGroup = GetDevicesForGroup(type, groupId);
5738 if (!connected && devsInGroup.size() == 0) {
5739 interruptGroups_.erase(iter);
5740 }
5741 return;
5742 }
5743 if (groupName != GROUP_NAME_NONE && connected) {
5744 groupId = AudioGroupHandle::GetInstance().GetNextId(type);
5745 sptr<InterruptGroupInfo> interruptGroupInfo = new(std::nothrow) InterruptGroupInfo(groupId, mappingId,
5746 groupName, networkId, connectType);
5747 interruptGroups_.push_back(interruptGroupInfo);
5748 }
5749 }
5750 }
5751
GetDevicesForGroup(GroupType type,int32_t groupId)5752 std::vector<sptr<OHOS::AudioStandard::AudioDeviceDescriptor>> AudioPolicyService::GetDevicesForGroup(GroupType type,
5753 int32_t groupId)
5754 {
5755 std::vector<sptr<OHOS::AudioStandard::AudioDeviceDescriptor>> devices = {};
5756 for (auto devDes : connectedDevices_) {
5757 if (devDes == nullptr) {
5758 continue;
5759 }
5760 bool inVolumeGroup = type == VOLUME_TYPE && devDes->volumeGroupId_ == groupId;
5761 bool inInterruptGroup = type == INTERRUPT_TYPE && devDes->interruptGroupId_ == groupId;
5762
5763 if (inVolumeGroup || inInterruptGroup) {
5764 sptr<AudioDeviceDescriptor> device = new AudioDeviceDescriptor(*devDes);
5765 devices.push_back(device);
5766 }
5767 }
5768 return devices;
5769 }
5770
UpdateDescWhenNoBTPermission(vector<sptr<AudioDeviceDescriptor>> & deviceDescs)5771 void AudioPolicyService::UpdateDescWhenNoBTPermission(vector<sptr<AudioDeviceDescriptor>> &deviceDescs)
5772 {
5773 AUDIO_WARNING_LOG("UpdateDescWhenNoBTPermission: No bt permission");
5774
5775 for (sptr<AudioDeviceDescriptor> &desc : deviceDescs) {
5776 if ((desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) || (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO)) {
5777 sptr<AudioDeviceDescriptor> copyDesc = new AudioDeviceDescriptor(desc);
5778 copyDesc->deviceName_ = "";
5779 copyDesc->macAddress_ = "";
5780 desc = copyDesc;
5781 }
5782 }
5783 }
5784
SetSharedAbsVolumeScene(const bool support)5785 void AudioPolicyService::SetSharedAbsVolumeScene(const bool support)
5786 {
5787 CHECK_AND_RETURN_LOG(sharedAbsVolumeScene_ != nullptr, "sharedAbsVolumeScene is nullptr");
5788 *sharedAbsVolumeScene_ = support;
5789 }
5790
SetAbsVolumeSceneAsync(const std::string & macAddress,const bool support)5791 void AudioPolicyService::SetAbsVolumeSceneAsync(const std::string &macAddress, const bool support)
5792 {
5793 usleep(SET_BT_ABS_SCENE_DELAY_MS);
5794 AUDIO_INFO_LOG("success for macAddress:[%{public}s], support: %{public}d, active bt:[%{public}s]",
5795 GetEncryptAddr(macAddress).c_str(), support, GetEncryptAddr(activeBTDevice_).c_str());
5796
5797 if (activeBTDevice_ == macAddress) {
5798 audioPolicyManager_.SetAbsVolumeScene(support);
5799 int32_t volumeLevel = audioPolicyManager_.GetSystemVolumeLevelNoMuteState(STREAM_MUSIC);
5800 audioPolicyManager_.SetSystemVolumeLevel(STREAM_MUSIC, volumeLevel);
5801 }
5802 }
5803
SetDeviceAbsVolumeSupported(const std::string & macAddress,const bool support)5804 int32_t AudioPolicyService::SetDeviceAbsVolumeSupported(const std::string &macAddress, const bool support)
5805 {
5806 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_);
5807 // Maximum number of attempts, preventing situations where a2dp device has not yet finished coming online.
5808 int maxRetries = 3;
5809 int retryCount = 0;
5810 while (retryCount < maxRetries) {
5811 retryCount++;
5812 auto configInfoPos = connectedA2dpDeviceMap_.find(macAddress);
5813 if (configInfoPos != connectedA2dpDeviceMap_.end()) {
5814 configInfoPos->second.absVolumeSupport = support;
5815 break;
5816 }
5817 CHECK_AND_RETURN_RET_LOG(retryCount != maxRetries, ERROR,
5818 "failed, can't find device for macAddress:[%{public}s]", GetEncryptAddr(macAddress).c_str());;
5819 usleep(ABS_VOLUME_SUPPORT_RETRY_INTERVAL_IN_MICROSECONDS);
5820 }
5821
5822 // The delay setting is due to move a2dp sink after this
5823 std::thread setAbsSceneThrd(&AudioPolicyService::SetAbsVolumeSceneAsync, this, macAddress, support);
5824 setAbsSceneThrd.detach();
5825
5826 return SUCCESS;
5827 }
5828
IsAbsVolumeScene() const5829 bool AudioPolicyService::IsAbsVolumeScene() const
5830 {
5831 return audioPolicyManager_.IsAbsVolumeScene();
5832 }
5833
IsWiredHeadSet(const DeviceType & deviceType)5834 bool AudioPolicyService::IsWiredHeadSet(const DeviceType &deviceType)
5835 {
5836 switch (deviceType) {
5837 case DEVICE_TYPE_WIRED_HEADSET:
5838 case DEVICE_TYPE_WIRED_HEADPHONES:
5839 case DEVICE_TYPE_USB_HEADSET:
5840 case DEVICE_TYPE_USB_ARM_HEADSET:
5841 return true;
5842 default:
5843 return false;
5844 }
5845 }
5846
IsBlueTooth(const DeviceType & deviceType)5847 bool AudioPolicyService::IsBlueTooth(const DeviceType &deviceType)
5848 {
5849 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP || deviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
5850 if (GetCurrentOutputDeviceCategory() == BT_HEADPHONE) {
5851 return true;
5852 }
5853 }
5854 return false;
5855 }
5856
CheckBlueToothActiveMusicTime(int32_t safeVolume)5857 void AudioPolicyService::CheckBlueToothActiveMusicTime(int32_t safeVolume)
5858 {
5859 if (startSafeTimeBt_ == 0) {
5860 startSafeTimeBt_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
5861 }
5862 int32_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
5863 if (activeSafeTimeBt_ >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) {
5864 AUDIO_INFO_LOG("safe volume timeout");
5865 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, SAFE_ACTIVE);
5866 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, 0);
5867 startSafeTimeBt_ = 0;
5868 safeStatusBt_ = SAFE_ACTIVE;
5869 RestoreSafeVolume(STREAM_MUSIC, safeVolume);
5870 activeSafeTimeBt_ = 0;
5871 } else if (currentTime - startSafeTimeBt_ >= ONE_MINUTE) {
5872 AUDIO_INFO_LOG("safe volume 1 min timeout");
5873 activeSafeTimeBt_ = audioPolicyManager_.GetCurentDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP);
5874 activeSafeTimeBt_ += currentTime - startSafeTimeBt_;
5875 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, activeSafeTimeBt_);
5876 startSafeTimeBt_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
5877 }
5878 startSafeTime_ = 0;
5879 }
5880
CheckWiredActiveMusicTime(int32_t safeVolume)5881 void AudioPolicyService::CheckWiredActiveMusicTime(int32_t safeVolume)
5882 {
5883 if (startSafeTime_ == 0) {
5884 startSafeTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
5885 }
5886 int32_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
5887 if (activeSafeTime_ >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) {
5888 AUDIO_INFO_LOG("safe volume timeout");
5889 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET, SAFE_ACTIVE);
5890 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, 0);
5891 startSafeTime_ = 0;
5892 safeStatus_ = SAFE_ACTIVE;
5893 RestoreSafeVolume(STREAM_MUSIC, safeVolume);
5894 activeSafeTime_ = 0;
5895 } else if (currentTime - startSafeTime_ >= ONE_MINUTE) {
5896 AUDIO_INFO_LOG("safe volume 1 min timeout");
5897 activeSafeTime_ = audioPolicyManager_.GetCurentDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET);
5898 activeSafeTime_ += currentTime - startSafeTime_;
5899 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, activeSafeTime_);
5900 startSafeTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
5901 }
5902 startSafeTimeBt_ = 0;
5903 }
5904
RestoreSafeVolume(AudioStreamType streamType,int32_t safeVolume)5905 void AudioPolicyService::RestoreSafeVolume(AudioStreamType streamType, int32_t safeVolume)
5906 {
5907 userSelect_ = false;
5908 isDialogSelectDestroy_.store(false);
5909
5910 if (GetSystemVolumeLevel(streamType) <= safeVolume) {
5911 AUDIO_INFO_LOG("current volume <= safe volume, don't update volume.");
5912 return;
5913 }
5914
5915 AUDIO_INFO_LOG("restore safe volume.");
5916 SetSystemVolumeLevel(streamType, safeVolume);
5917
5918 VolumeEvent volumeEvent;
5919 volumeEvent.volumeType = streamType;
5920 volumeEvent.volume = GetSystemVolumeLevel(streamType);
5921 volumeEvent.updateUi = true;
5922 volumeEvent.volumeGroupId = 0;
5923 volumeEvent.networkId = LOCAL_NETWORK_ID;
5924 if (audioPolicyServerHandler_ != nullptr && IsRingerModeMute()) {
5925 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
5926 }
5927 }
5928
CheckActiveMusicTime()5929 int32_t AudioPolicyService::CheckActiveMusicTime()
5930 {
5931 AUDIO_INFO_LOG("enter");
5932 int32_t safeVolume = audioPolicyManager_.GetSafeVolumeLevel();
5933 bool isUpSafeVolume = false;
5934 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
5935 while (!safeVolumeExit_) {
5936 isUpSafeVolume = GetSystemVolumeLevel(STREAM_MUSIC) > safeVolume ? true : false;
5937 AUDIO_INFO_LOG("deviceType_:%{public}d, isUpSafeVolume:%{public}d",
5938 curOutputDeviceType, isUpSafeVolume);
5939 if ((safeStatusBt_ == SAFE_INACTIVE || isUpSafeVolume) &&
5940 IsBlueTooth(curOutputDeviceType)) {
5941 CheckBlueToothActiveMusicTime(safeVolume);
5942 } else if ((safeStatus_ == SAFE_INACTIVE || isUpSafeVolume) &&
5943 IsWiredHeadSet(curOutputDeviceType)) {
5944 CheckWiredActiveMusicTime(safeVolume);
5945 } else {
5946 startSafeTime_ = 0;
5947 startSafeTimeBt_ = 0;
5948 }
5949 sleep(ONE_MINUTE);
5950 }
5951 return 0;
5952 }
5953
CreateCheckMusicActiveThread()5954 void AudioPolicyService::CreateCheckMusicActiveThread()
5955 {
5956 std::lock_guard<std::mutex> lock(checkMusicActiveThreadMutex_);
5957 if (calculateLoopSafeTime_ == nullptr) {
5958 calculateLoopSafeTime_ = std::make_unique<std::thread>([this] { this->CheckActiveMusicTime(); });
5959 pthread_setname_np(calculateLoopSafeTime_->native_handle(), "OS_AudioPolicySafe");
5960 }
5961 }
5962
CreateSafeVolumeDialogThread()5963 void AudioPolicyService::CreateSafeVolumeDialogThread()
5964 {
5965 std::lock_guard<std::mutex> safeVolumeLock(safeVolumeMutex_);
5966 AUDIO_INFO_LOG("enter");
5967 if (safeVolumeDialogThrd_ != nullptr && safeVolumeDialogThrd_->joinable()) {
5968 AUDIO_INFO_LOG("safeVolumeDialogThread exit begin");
5969 safeVolumeDialogThrd_->join();
5970 safeVolumeDialogThrd_.reset();
5971 safeVolumeDialogThrd_ = nullptr;
5972 AUDIO_INFO_LOG("safeVolumeDialogThread exit end");
5973 }
5974
5975 AUDIO_INFO_LOG("create thread begin");
5976 safeVolumeDialogThrd_ = std::make_unique<std::thread>([this] { this->ShowDialog(); });
5977 pthread_setname_np(safeVolumeDialogThrd_->native_handle(), "OS_AudioSafeDialog");
5978 isSafeVolumeDialogShowing_.store(true);
5979 AUDIO_INFO_LOG("create thread end");
5980 }
5981
DealWithSafeVolume(const int32_t volumeLevel,bool isA2dpDevice)5982 int32_t AudioPolicyService::DealWithSafeVolume(const int32_t volumeLevel, bool isA2dpDevice)
5983 {
5984 if (isA2dpDevice) {
5985 DeviceCategory curOutputDeviceCategory = GetCurrentOutputDeviceCategory();
5986 AUDIO_INFO_LOG("bluetooth Category:%{public}d", curOutputDeviceCategory);
5987 if (curOutputDeviceCategory != BT_HEADPHONE) {
5988 return volumeLevel;
5989 }
5990 }
5991
5992 int32_t sVolumeLevel = volumeLevel;
5993 safeStatusBt_ = audioPolicyManager_.GetCurrentDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP);
5994 safeStatus_ = audioPolicyManager_.GetCurrentDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET);
5995 if ((safeStatusBt_ == SAFE_INACTIVE && isA2dpDevice) ||
5996 (safeStatus_ == SAFE_INACTIVE && !isA2dpDevice)) {
5997 CreateCheckMusicActiveThread();
5998 return sVolumeLevel;
5999 }
6000
6001 if ((isA2dpDevice && safeStatusBt_ == SAFE_ACTIVE) ||
6002 (!isA2dpDevice && safeStatus_ == SAFE_ACTIVE)) {
6003 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
6004 if (!isSafeVolumeDialogShowing_.load()) {
6005 CreateSafeVolumeDialogThread();
6006 } else {
6007 AUDIO_INFO_LOG("Safe volume dialog is showing");
6008 }
6009 return sVolumeLevel;
6010 }
6011 return sVolumeLevel;
6012 }
6013
ShowDialog()6014 int32_t AudioPolicyService::ShowDialog()
6015 {
6016 auto abilityMgrClient = AAFwk::AbilityManagerClient::GetInstance();
6017 if (abilityMgrClient == nullptr) {
6018 isSafeVolumeDialogShowing_.store(false);
6019 AUDIO_INFO_LOG("abilityMgrClient malloc failed");
6020 return ERROR;
6021 }
6022 sptr<OHOS::AAFwk::IAbilityConnection> dialogConnectionCallback = new (std::nothrow)AudioDialogAbilityConnection();
6023 if (dialogConnectionCallback == nullptr) {
6024 isSafeVolumeDialogShowing_.store(false);
6025 AUDIO_INFO_LOG("dialogConnectionCallback malloc failed");
6026 return ERROR;
6027 }
6028
6029 AAFwk::Want want;
6030 std::string bundleName = "com.ohos.sceneboard";
6031 std::string abilityName = "com.ohos.sceneboard.systemdialog";
6032 want.SetElementName(bundleName, abilityName);
6033 ErrCode result = abilityMgrClient->ConnectAbility(want, dialogConnectionCallback,
6034 AppExecFwk::Constants::INVALID_USERID);
6035 if (result != SUCCESS) {
6036 isSafeVolumeDialogShowing_.store(false);
6037 AUDIO_INFO_LOG("ConnectAbility failed");
6038 return result;
6039 }
6040
6041 AUDIO_INFO_LOG("show safe Volume Dialog");
6042 std::unique_lock<std::mutex> lock(dialogMutex_);
6043 isSafeVolumeDialogShowing_.store(true);
6044 if (!isDialogSelectDestroy_.load()) {
6045 auto status = dialogSelectCondition_.wait_for(lock, std::chrono::seconds(WAIT_DIALOG_CLOSE_TIME_S),
6046 [this] () { return isDialogSelectDestroy_.load() || !isSafeVolumeDialogShowing_.load(); });
6047 if (!status) {
6048 AUDIO_ERR_LOG("user cancel or not select.");
6049 }
6050 isDialogSelectDestroy_.store(false);
6051 }
6052 return result;
6053 }
6054
HandleAbsBluetoothVolume(const std::string & macAddress,const int32_t volumeLevel)6055 int32_t AudioPolicyService::HandleAbsBluetoothVolume(const std::string &macAddress, const int32_t volumeLevel)
6056 {
6057 int32_t sVolumeLevel = volumeLevel;
6058 if (isAbsBtFirstBoot_) {
6059 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
6060 isAbsBtFirstBoot_ = false;
6061 Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(macAddress, sVolumeLevel);
6062 } else {
6063 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
6064 if (sVolumeLevel != volumeLevel) {
6065 Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(macAddress, sVolumeLevel);
6066 }
6067 }
6068 return sVolumeLevel;
6069 }
6070
IsVgsVolumeSupported() const6071 bool AudioPolicyService::IsVgsVolumeSupported() const
6072 {
6073 return audioPolicyManager_.IsVgsVolumeSupported();
6074 }
6075
SetA2dpDeviceVolume(const std::string & macAddress,const int32_t volumeLevel,bool internalCall)6076 int32_t AudioPolicyService::SetA2dpDeviceVolume(const std::string &macAddress, const int32_t volumeLevel,
6077 bool internalCall)
6078 {
6079 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_);
6080 auto configInfoPos = connectedA2dpDeviceMap_.find(macAddress);
6081 CHECK_AND_RETURN_RET_LOG(configInfoPos != connectedA2dpDeviceMap_.end() && configInfoPos->second.absVolumeSupport,
6082 ERROR, "failed for macAddress:[%{public}s]", GetEncryptAddr(macAddress).c_str());
6083 configInfoPos->second.volumeLevel = volumeLevel;
6084 int32_t sVolumeLevel = volumeLevel;
6085 if (volumeLevel > audioPolicyManager_.GetSafeVolumeLevel()) {
6086 if (internalCall) {
6087 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
6088 } else {
6089 sVolumeLevel = HandleAbsBluetoothVolume(macAddress, volumeLevel);
6090 }
6091 }
6092 configInfoPos->second.volumeLevel = sVolumeLevel;
6093 bool mute = sVolumeLevel == 0 ? true : false;
6094 configInfoPos->second.mute = mute;
6095 audioPolicyManager_.SetAbsVolumeMute(mute);
6096 AUDIO_INFO_LOG("success for macaddress:[%{public}s], volume value:[%{public}d]",
6097 GetEncryptAddr(macAddress).c_str(), sVolumeLevel);
6098 CHECK_AND_RETURN_RET_LOG(sVolumeLevel == volumeLevel, ERR_UNKNOWN, "safevolume did not deal");
6099 return SUCCESS;
6100 }
6101
TriggerDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)6102 void AudioPolicyService::TriggerDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected)
6103 {
6104 Trace trace("AudioPolicyService::TriggerDeviceChangedCallback");
6105 WriteDeviceChangedSysEvents(desc, isConnected);
6106 if (audioPolicyServerHandler_ != nullptr) {
6107 audioPolicyServerHandler_->SendDeviceChangedCallback(desc, isConnected);
6108 }
6109 }
6110
TriggerMicrophoneBlockedCallback(const vector<sptr<AudioDeviceDescriptor>> & desc,DeviceBlockStatus status)6111 void AudioPolicyService::TriggerMicrophoneBlockedCallback(const vector<sptr<AudioDeviceDescriptor>> &desc,
6112 DeviceBlockStatus status)
6113 {
6114 Trace trace("AudioPolicyService::TriggerMicrophoneBlockedCallback");
6115 if (audioPolicyServerHandler_ != nullptr) {
6116 audioPolicyServerHandler_->SendMicrophoneBlockedCallback(desc, status);
6117 }
6118 }
6119
GetDeviceRole(DeviceType deviceType) const6120 DeviceRole AudioPolicyService::GetDeviceRole(DeviceType deviceType) const
6121 {
6122 switch (deviceType) {
6123 case DeviceType::DEVICE_TYPE_EARPIECE:
6124 case DeviceType::DEVICE_TYPE_SPEAKER:
6125 case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
6126 case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
6127 case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
6128 case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
6129 case DeviceType::DEVICE_TYPE_USB_HEADSET:
6130 case DeviceType::DEVICE_TYPE_DP:
6131 case DeviceType::DEVICE_TYPE_USB_ARM_HEADSET:
6132 case DeviceType::DEVICE_TYPE_REMOTE_CAST:
6133 return DeviceRole::OUTPUT_DEVICE;
6134 case DeviceType::DEVICE_TYPE_MIC:
6135 case DeviceType::DEVICE_TYPE_WAKEUP:
6136 return DeviceRole::INPUT_DEVICE;
6137 default:
6138 return DeviceRole::DEVICE_ROLE_NONE;
6139 }
6140 }
6141
GetDeviceRole(const std::string & role)6142 DeviceRole AudioPolicyService::GetDeviceRole(const std::string &role)
6143 {
6144 if (role == ROLE_SINK) {
6145 return DeviceRole::OUTPUT_DEVICE;
6146 } else if (role == ROLE_SOURCE) {
6147 return DeviceRole::INPUT_DEVICE;
6148 } else {
6149 return DeviceRole::DEVICE_ROLE_NONE;
6150 }
6151 }
6152
GetDeviceRole(AudioPin pin) const6153 DeviceRole AudioPolicyService::GetDeviceRole(AudioPin pin) const
6154 {
6155 switch (pin) {
6156 case OHOS::AudioStandard::AUDIO_PIN_NONE:
6157 return DeviceRole::DEVICE_ROLE_NONE;
6158 case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER:
6159 case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET:
6160 case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT:
6161 case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI:
6162 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB:
6163 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT:
6164 case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT:
6165 return DeviceRole::OUTPUT_DEVICE;
6166 case OHOS::AudioStandard::AUDIO_PIN_IN_MIC:
6167 case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC:
6168 case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN:
6169 case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT:
6170 case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT:
6171 return DeviceRole::INPUT_DEVICE;
6172 default:
6173 return DeviceRole::DEVICE_ROLE_NONE;
6174 }
6175 }
6176
OnAudioLatencyParsed(uint64_t latency)6177 void AudioPolicyService::OnAudioLatencyParsed(uint64_t latency)
6178 {
6179 audioLatencyInMsec_ = latency;
6180 }
6181
GetAudioLatencyFromXml() const6182 int32_t AudioPolicyService::GetAudioLatencyFromXml() const
6183 {
6184 return audioLatencyInMsec_;
6185 }
6186
OnSinkLatencyParsed(uint32_t latency)6187 void AudioPolicyService::OnSinkLatencyParsed(uint32_t latency)
6188 {
6189 sinkLatencyInMsec_ = latency;
6190 }
6191
GetSinkLatencyFromXml() const6192 uint32_t AudioPolicyService::GetSinkLatencyFromXml() const
6193 {
6194 return sinkLatencyInMsec_;
6195 }
6196
getFastControlParam()6197 bool AudioPolicyService::getFastControlParam()
6198 {
6199 int32_t fastControlFlag = 1; // default 1, set isFastControlled_ true
6200 GetSysPara("persist.multimedia.audioflag.fastcontrolled", fastControlFlag);
6201 if (fastControlFlag == 0) {
6202 isFastControlled_ = false;
6203 }
6204 return isFastControlled_;
6205 }
6206
GetPreferredOutputStreamType(AudioRendererInfo & rendererInfo,const std::string & bundleName)6207 int32_t AudioPolicyService::GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo, const std::string &bundleName)
6208 {
6209 // Use GetPreferredOutputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream
6210 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList = GetPreferredOutputDeviceDescriptors(rendererInfo);
6211 if (preferredDeviceList.size() == 0) {
6212 return AUDIO_FLAG_INVALID;
6213 }
6214
6215 int32_t flag = GetPreferredOutputStreamTypeInner(rendererInfo.streamUsage, preferredDeviceList[0]->deviceType_,
6216 rendererInfo.rendererFlags, preferredDeviceList[0]->networkId_, rendererInfo.samplingRate);
6217 if (isFastControlled_ && (rendererInfo.playerType != PLAYER_TYPE_SOUND_POOL) &&
6218 (flag == AUDIO_FLAG_MMAP || flag == AUDIO_FLAG_VOIP_FAST)) {
6219 std::string bundleNamePre = CHECK_FAST_BLOCK_PREFIX + bundleName;
6220 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
6221 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, AUDIO_FLAG_NORMAL,
6222 "GetPreferredOutputStreamType, Audio server Proxy is null");
6223 std::string result = gsp->GetAudioParameter(bundleNamePre);
6224 if (result == "true") {
6225 AUDIO_INFO_LOG("%{public}s not in fast list", bundleName.c_str());
6226 return AUDIO_FLAG_NORMAL;
6227 }
6228 }
6229 return flag;
6230 }
6231
SetNormalVoipFlag(const bool & normalVoipFlag)6232 void AudioPolicyService::SetNormalVoipFlag(const bool &normalVoipFlag)
6233 {
6234 normalVoipFlag_ = normalVoipFlag;
6235 }
6236
GetVoipRendererFlag(const std::string & sinkPortName,const std::string & networkId,const AudioSamplingRate & samplingRate)6237 int32_t AudioPolicyService::GetVoipRendererFlag(const std::string &sinkPortName, const std::string &networkId,
6238 const AudioSamplingRate &samplingRate)
6239 {
6240 // VoIP stream has three mode for different products.
6241 if (enableFastVoip_ && (sinkPortName == PRIMARY_SPEAKER && networkId == LOCAL_NETWORK_ID)) {
6242 if (samplingRate != SAMPLE_RATE_48000 && samplingRate != SAMPLE_RATE_16000) {
6243 return AUDIO_FLAG_NORMAL;
6244 }
6245 return AUDIO_FLAG_VOIP_FAST;
6246 } else if (!normalVoipFlag_ && (sinkPortName == PRIMARY_SPEAKER) && (networkId == LOCAL_NETWORK_ID)) {
6247 AUDIO_INFO_LOG("Direct VoIP mode is supported for the device");
6248 return AUDIO_FLAG_VOIP_DIRECT;
6249 }
6250
6251 return AUDIO_FLAG_NORMAL;
6252 }
6253
GetPreferredOutputStreamTypeInner(StreamUsage streamUsage,DeviceType deviceType,int32_t flags,std::string & networkId,AudioSamplingRate & samplingRate)6254 int32_t AudioPolicyService::GetPreferredOutputStreamTypeInner(StreamUsage streamUsage, DeviceType deviceType,
6255 int32_t flags, std::string &networkId, AudioSamplingRate &samplingRate)
6256 {
6257 AUDIO_INFO_LOG("Device type: %{public}d, stream usage: %{public}d, flag: %{public}d",
6258 deviceType, streamUsage, flags);
6259 std::string sinkPortName = GetSinkPortName(deviceType);
6260 if (streamUsage == STREAM_USAGE_VOICE_COMMUNICATION || streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) {
6261 // Avoid two voip stream existing
6262 if (streamCollector_.HasVoipRendererStream()) {
6263 AUDIO_WARNING_LOG("Voip Change To Normal");
6264 return AUDIO_FLAG_NORMAL;
6265 }
6266
6267 // VoIP stream. Need to judge whether it is fast or direct mode.
6268 int32_t flag = GetVoipRendererFlag(sinkPortName, networkId, samplingRate);
6269 if (flag == AUDIO_FLAG_VOIP_FAST || flag == AUDIO_FLAG_VOIP_DIRECT) {
6270 return flag;
6271 }
6272 }
6273 if (!isAdapterInfoMap_.load()) {
6274 return AUDIO_FLAG_NORMAL;
6275 }
6276 if (adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[sinkPortName])) == adapterInfoMap_.end()) {
6277 return AUDIO_FLAG_INVALID;
6278 }
6279 AudioAdapterInfo adapterInfo;
6280 auto it = adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[sinkPortName]));
6281 if (it != adapterInfoMap_.end()) {
6282 adapterInfo = it->second;
6283 } else {
6284 AUDIO_ERR_LOG("Invalid adapter");
6285 return AUDIO_FLAG_INVALID;
6286 }
6287
6288 AudioPipeDeviceInfo* deviceInfo = adapterInfo.GetDeviceInfoByDeviceType(deviceType);
6289 CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, AUDIO_FLAG_INVALID, "Device type is not supported");
6290 for (auto &supportPipe : deviceInfo->supportPipes_) {
6291 PipeInfo* pipeInfo = adapterInfo.GetPipeByName(supportPipe);
6292 if (pipeInfo == nullptr) {
6293 continue;
6294 }
6295 if (flags == AUDIO_FLAG_MMAP && pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) {
6296 return AUDIO_FLAG_MMAP;
6297 }
6298 if (flags == AUDIO_FLAG_VOIP_FAST && pipeInfo->audioUsage_ == AUDIO_USAGE_VOIP &&
6299 pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) {
6300 return AUDIO_FLAG_VOIP_FAST;
6301 }
6302 }
6303 return AUDIO_FLAG_NORMAL;
6304 }
6305
GetPreferredInputStreamType(AudioCapturerInfo & capturerInfo)6306 int32_t AudioPolicyService::GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo)
6307 {
6308 // Use GetPreferredInputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream
6309 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList = GetPreferredInputDeviceDescriptors(capturerInfo);
6310 if (preferredDeviceList.size() == 0) {
6311 return AUDIO_FLAG_INVALID;
6312 }
6313 return GetPreferredInputStreamTypeInner(capturerInfo.sourceType, preferredDeviceList[0]->deviceType_,
6314 capturerInfo.originalFlag, preferredDeviceList[0]->networkId_, capturerInfo.samplingRate);
6315 }
6316
GetPreferredInputStreamTypeFromDeviceInfo(AudioAdapterInfo & adapterInfo,DeviceType deviceType,int32_t flags)6317 int32_t AudioPolicyService::GetPreferredInputStreamTypeFromDeviceInfo(AudioAdapterInfo &adapterInfo,
6318 DeviceType deviceType, int32_t flags)
6319 {
6320 AudioPipeDeviceInfo* deviceInfo = adapterInfo.GetDeviceInfoByDeviceType(deviceType);
6321 CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, AUDIO_FLAG_INVALID, "Device type is not supported");
6322 for (auto &supportPipe : deviceInfo->supportPipes_) {
6323 PipeInfo* pipeInfo = adapterInfo.GetPipeByName(supportPipe);
6324 if (pipeInfo == nullptr) {
6325 continue;
6326 }
6327 if (flags == AUDIO_FLAG_MMAP && pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) {
6328 return AUDIO_FLAG_MMAP;
6329 }
6330 if (flags == AUDIO_FLAG_VOIP_FAST && pipeInfo->audioUsage_ == AUDIO_USAGE_VOIP &&
6331 pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) {
6332 // Avoid voip stream existing with other
6333 if (streamCollector_.ChangeVoipCapturerStreamToNormal()) {
6334 AUDIO_WARNING_LOG("Voip Change To Normal By DeviceInfo");
6335 return AUDIO_FLAG_NORMAL;
6336 }
6337 return AUDIO_FLAG_VOIP_FAST;
6338 }
6339 }
6340 return AUDIO_FLAG_NORMAL;
6341 }
6342
GetPreferredInputStreamTypeInner(SourceType sourceType,DeviceType deviceType,int32_t flags,const std::string & networkId,const AudioSamplingRate & samplingRate)6343 int32_t AudioPolicyService::GetPreferredInputStreamTypeInner(SourceType sourceType, DeviceType deviceType,
6344 int32_t flags, const std::string &networkId, const AudioSamplingRate &samplingRate)
6345 {
6346 AUDIO_INFO_LOG("Device type: %{public}d, source type: %{public}d, flag: %{public}d",
6347 deviceType, sourceType, flags);
6348
6349 std::string sourcePortName = GetSourcePortName(deviceType);
6350 AUDIO_INFO_LOG("sourcePortName: %{public}s", sourcePortName.c_str());
6351 if (sourceType == SOURCE_TYPE_VOICE_COMMUNICATION &&
6352 (sourcePortName == PRIMARY_MIC && networkId == LOCAL_NETWORK_ID)) {
6353 if (enableFastVoip_ && (samplingRate == SAMPLE_RATE_16000 || samplingRate == SAMPLE_RATE_48000)) {
6354 // Avoid voip stream existing with other
6355 if (streamCollector_.ChangeVoipCapturerStreamToNormal()) {
6356 AUDIO_WARNING_LOG("Voip Change To Normal");
6357 return AUDIO_FLAG_NORMAL;
6358 }
6359 return AUDIO_FLAG_VOIP_FAST;
6360 }
6361 return AUDIO_FLAG_NORMAL;
6362 }
6363 if (!isAdapterInfoMap_.load()) {
6364 return AUDIO_FLAG_NORMAL;
6365 }
6366 if (adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[sourcePortName])) == adapterInfoMap_.end()) {
6367 return AUDIO_FLAG_INVALID;
6368 }
6369 AudioAdapterInfo adapterInfo;
6370 auto it = adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[sourcePortName]));
6371 if (it != adapterInfoMap_.end()) {
6372 adapterInfo = it->second;
6373 } else {
6374 AUDIO_ERR_LOG("Invalid adapter");
6375 return AUDIO_FLAG_INVALID;
6376 }
6377
6378 return GetPreferredInputStreamTypeFromDeviceInfo(adapterInfo, deviceType, flags);
6379 }
6380
UpdateInputDeviceInfo(DeviceType deviceType)6381 void AudioPolicyService::UpdateInputDeviceInfo(DeviceType deviceType)
6382 {
6383 DeviceType curType = GetCurrentInputDeviceType();
6384
6385 switch (deviceType) {
6386 case DEVICE_TYPE_EARPIECE:
6387 case DEVICE_TYPE_SPEAKER:
6388 case DEVICE_TYPE_BLUETOOTH_A2DP:
6389 curType = DEVICE_TYPE_MIC;
6390 break;
6391 case DEVICE_TYPE_FILE_SINK:
6392 curType = DEVICE_TYPE_FILE_SOURCE;
6393 break;
6394 case DEVICE_TYPE_USB_ARM_HEADSET:
6395 curType = DEVICE_TYPE_USB_HEADSET;
6396 break;
6397 case DEVICE_TYPE_WIRED_HEADSET:
6398 case DEVICE_TYPE_USB_HEADSET:
6399 case DEVICE_TYPE_BLUETOOTH_SCO:
6400 curType = deviceType;
6401 break;
6402 default:
6403 break;
6404 }
6405
6406 SetCurrentInputDeviceType(curType);
6407 AUDIO_DEBUG_LOG("Input device updated to %{public}d", curType);
6408 }
6409
UpdateStreamState(int32_t clientUid,StreamSetStateEventInternal & streamSetStateEventInternal)6410 int32_t AudioPolicyService::UpdateStreamState(int32_t clientUid,
6411 StreamSetStateEventInternal &streamSetStateEventInternal)
6412 {
6413 return streamCollector_.UpdateStreamState(clientUid, streamSetStateEventInternal);
6414 }
6415
GetStreamType(int32_t sessionId)6416 AudioStreamType AudioPolicyService::GetStreamType(int32_t sessionId)
6417 {
6418 return streamCollector_.GetStreamType(sessionId);
6419 }
6420
GetChannelCount(uint32_t sessionId)6421 int32_t AudioPolicyService::GetChannelCount(uint32_t sessionId)
6422 {
6423 return streamCollector_.GetChannelCount(sessionId);
6424 }
6425
GetUid(int32_t sessionId)6426 int32_t AudioPolicyService::GetUid(int32_t sessionId)
6427 {
6428 return streamCollector_.GetUid(sessionId);
6429 }
6430
GetDeviceTypeFromPin(AudioPin hdiPin)6431 DeviceType AudioPolicyService::GetDeviceTypeFromPin(AudioPin hdiPin)
6432 {
6433 switch (hdiPin) {
6434 case OHOS::AudioStandard::AUDIO_PIN_NONE:
6435 break;
6436 case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER:
6437 case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT:
6438 return DeviceType::DEVICE_TYPE_SPEAKER;
6439 case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET:
6440 break;
6441 case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT:
6442 break;
6443 case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI:
6444 break;
6445 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB:
6446 break;
6447 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT:
6448 break;
6449 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_HEADSET:
6450 case OHOS::AudioStandard::AUDIO_PIN_IN_USB_HEADSET:
6451 return DeviceType::DEVICE_TYPE_USB_ARM_HEADSET;
6452 case OHOS::AudioStandard::AUDIO_PIN_IN_MIC:
6453 case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT:
6454 return DeviceType::DEVICE_TYPE_MIC;
6455 case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC:
6456 break;
6457 case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN:
6458 break;
6459 case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT:
6460 break;
6461 default:
6462 break;
6463 }
6464 return DeviceType::DEVICE_TYPE_DEFAULT;
6465 }
6466
SetDefaultDeviceLoadFlag(bool isLoad)6467 void AudioPolicyService::SetDefaultDeviceLoadFlag(bool isLoad)
6468 {
6469 isPrimaryMicModuleInfoLoaded_.store(isLoad);
6470 }
6471
GetVolumeGroupInfos()6472 std::vector<sptr<VolumeGroupInfo>> AudioPolicyService::GetVolumeGroupInfos()
6473 {
6474 if (!isPrimaryMicModuleInfoLoaded_.load()) {
6475 std::unique_lock<std::mutex> lock(defaultDeviceLoadMutex_);
6476 bool loadWaiting = loadDefaultDeviceCV_.wait_for(lock,
6477 std::chrono::milliseconds(WAIT_LOAD_DEFAULT_DEVICE_TIME_MS),
6478 [this] { return isPrimaryMicModuleInfoLoaded_.load(); }
6479 );
6480 if (!loadWaiting) {
6481 AUDIO_ERR_LOG("load default device time out");
6482 }
6483 }
6484
6485 std::vector<sptr<VolumeGroupInfo>> volumeGroupInfos = {};
6486 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
6487 for (auto& v : volumeGroups_) {
6488 sptr<VolumeGroupInfo> info = new(std::nothrow) VolumeGroupInfo(v->volumeGroupId_, v->mappingId_, v->groupName_,
6489 v->networkId_, v->connectType_);
6490 volumeGroupInfos.push_back(info);
6491 }
6492 return volumeGroupInfos;
6493 }
6494
RegiestPolicy()6495 void AudioPolicyService::RegiestPolicy()
6496 {
6497 AUDIO_INFO_LOG("RegiestPolicy start");
6498 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
6499 CHECK_AND_RETURN_LOG(gsp != nullptr, "RegiestPolicy gsp null");
6500 audioPolicyManager_.SetAudioServerProxy(gsp);
6501
6502 sptr<PolicyProviderWrapper> wrapper = new(std::nothrow) PolicyProviderWrapper(this);
6503 CHECK_AND_RETURN_LOG(wrapper != nullptr, "Get null PolicyProviderWrapper");
6504 sptr<IRemoteObject> object = wrapper->AsObject();
6505 CHECK_AND_RETURN_LOG(object != nullptr, "RegiestPolicy AsObject is nullptr");
6506 std::string identity = IPCSkeleton::ResetCallingIdentity();
6507 int32_t ret = gsp->RegiestPolicyProvider(object);
6508 IPCSkeleton::SetCallingIdentity(identity);
6509 AUDIO_DEBUG_LOG("RegiestPolicy result:%{public}d", ret);
6510 }
6511
6512 /*
6513 * lockFlag is use to determinewhether GetPreferredOutputDeviceDescriptor or GetPreferredOutputDeviceDescInner
6514 * is invoked. If deviceStatusUpdateSharedMutex_ write lock is not invoked at the outer layer, lockFlag can be
6515 * set to true. When deviceStatusUpdateSharedMutex_ write lock has been invoked, lockFlag must be set to false.
6516 */
GetProcessDeviceInfo(const AudioProcessConfig & config,bool lockFlag,AudioDeviceDescriptor & deviceInfo)6517 int32_t AudioPolicyService::GetProcessDeviceInfo(const AudioProcessConfig &config, bool lockFlag,
6518 AudioDeviceDescriptor &deviceInfo)
6519 {
6520 AUDIO_INFO_LOG("%{public}s", ProcessConfig::DumpProcessConfig(config).c_str());
6521 AudioSamplingRate samplingRate = config.streamInfo.samplingRate;
6522 if (config.audioMode == AUDIO_MODE_PLAYBACK) {
6523 if (config.rendererInfo.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION ||
6524 config.rendererInfo.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) {
6525 AudioRendererInfo rendererInfo = config.rendererInfo;
6526 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList =
6527 (lockFlag ? GetPreferredOutputDeviceDescriptors(rendererInfo, LOCAL_NETWORK_ID)
6528 : GetPreferredOutputDeviceDescInner(rendererInfo, LOCAL_NETWORK_ID));
6529 int32_t type = GetPreferredOutputStreamTypeInner(rendererInfo.streamUsage,
6530 preferredDeviceList[0]->deviceType_, rendererInfo.originalFlag, preferredDeviceList[0]->networkId_,
6531 samplingRate);
6532 deviceInfo.deviceRole_ = OUTPUT_DEVICE;
6533 return GetVoipDeviceInfo(config, deviceInfo, type, preferredDeviceList);
6534 }
6535 AudioDeviceDescriptor curOutputDeviceDesc = GetCurrentOutputDevice();
6536 deviceInfo.deviceId_ = curOutputDeviceDesc.deviceId_;
6537 deviceInfo.networkId_ = curOutputDeviceDesc.networkId_;
6538 deviceInfo.deviceType_ = curOutputDeviceDesc.deviceType_;
6539 deviceInfo.deviceRole_ = OUTPUT_DEVICE;
6540 } else {
6541 if (config.capturerInfo.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) {
6542 AudioCapturerInfo capturerInfo = config.capturerInfo;
6543 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList =
6544 (lockFlag ? GetPreferredInputDeviceDescriptors(capturerInfo, LOCAL_NETWORK_ID)
6545 : GetPreferredInputDeviceDescInner(capturerInfo, LOCAL_NETWORK_ID));
6546 int32_t type = GetPreferredInputStreamTypeInner(capturerInfo.sourceType,
6547 preferredDeviceList[0]->deviceType_, capturerInfo.originalFlag, preferredDeviceList[0]->networkId_,
6548 samplingRate);
6549 deviceInfo.deviceRole_ = INPUT_DEVICE;
6550 return GetVoipDeviceInfo(config, deviceInfo, type, preferredDeviceList);
6551 }
6552 deviceInfo.deviceId_ = GetCurrentInputDevice().deviceId_;
6553 deviceInfo.networkId_ = GetCurrentInputDevice().networkId_;
6554 deviceInfo.deviceRole_ = INPUT_DEVICE;
6555 deviceInfo.deviceType_ = GetCurrentInputDeviceType();
6556 }
6557
6558 // todo
6559 // check process in routerMap, return target device for it
6560 // put the currentActiveDevice_ in deviceinfo, so it can create with current using device.
6561 // genarate the unique deviceid?
6562 AudioStreamInfo targetStreamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO}; // note: read from xml
6563 deviceInfo.audioStreamInfo_ = targetStreamInfo;
6564 deviceInfo.deviceName_ = "mmap_device";
6565 std::lock_guard<std::mutex> lock(routerMapMutex_);
6566 if (fastRouterMap_.count(config.appInfo.appUid) &&
6567 fastRouterMap_[config.appInfo.appUid].second == deviceInfo.deviceRole_) {
6568 deviceInfo.networkId_ = fastRouterMap_[config.appInfo.appUid].first;
6569 AUDIO_INFO_LOG("use networkid in fastRouterMap_ :%{public}s ", GetEncryptStr(deviceInfo.networkId_).c_str());
6570 }
6571 deviceInfo.a2dpOffloadFlag_ = a2dpOffloadFlag_;
6572 return SUCCESS;
6573 }
6574
GetVoipDeviceInfo(const AudioProcessConfig & config,AudioDeviceDescriptor & deviceInfo,int32_t type,std::vector<sptr<AudioDeviceDescriptor>> & preferredDeviceList)6575 int32_t AudioPolicyService::GetVoipDeviceInfo(const AudioProcessConfig &config, AudioDeviceDescriptor &deviceInfo,
6576 int32_t type, std::vector<sptr<AudioDeviceDescriptor>> &preferredDeviceList)
6577 {
6578 if (type == AUDIO_FLAG_NORMAL) {
6579 AUDIO_WARNING_LOG("Current device %{public}d not support", type);
6580 return ERROR;
6581 }
6582 deviceInfo.deviceId_ = preferredDeviceList[0]->deviceId_;
6583 deviceInfo.networkId_ = preferredDeviceList[0]->networkId_;
6584 deviceInfo.deviceType_ = preferredDeviceList[0]->deviceType_;
6585 deviceInfo.deviceName_ = preferredDeviceList[0]->deviceName_;
6586 if (config.streamInfo.samplingRate <= SAMPLE_RATE_16000) {
6587 deviceInfo.audioStreamInfo_ = {SAMPLE_RATE_16000, ENCODING_PCM, SAMPLE_S16LE, STEREO};
6588 } else {
6589 deviceInfo.audioStreamInfo_ = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO};
6590 }
6591 if (type == AUDIO_FLAG_VOIP_DIRECT) {
6592 AUDIO_INFO_LOG("Direct VoIP stream, deviceInfo has been updated: deviceInfo.deviceType %{public}d",
6593 deviceInfo.deviceType_);
6594 return SUCCESS;
6595 }
6596 std::lock_guard<std::mutex> lock(routerMapMutex_);
6597 if (fastRouterMap_.count(config.appInfo.appUid) &&
6598 fastRouterMap_[config.appInfo.appUid].second == deviceInfo.deviceRole_) {
6599 deviceInfo.networkId_ = fastRouterMap_[config.appInfo.appUid].first;
6600 AUDIO_INFO_LOG("use networkid in fastRouterMap_ :%{public}s ", GetEncryptStr(deviceInfo.networkId_).c_str());
6601 }
6602 deviceInfo.a2dpOffloadFlag_ = a2dpOffloadFlag_;
6603 deviceInfo.isLowLatencyDevice_ = true;
6604 return SUCCESS;
6605 }
6606
InitSharedVolume(std::shared_ptr<AudioSharedMemory> & buffer)6607 int32_t AudioPolicyService::InitSharedVolume(std::shared_ptr<AudioSharedMemory> &buffer)
6608 {
6609 AUDIO_INFO_LOG("InitSharedVolume start");
6610 CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr,
6611 ERR_OPERATION_FAILED, "Get shared memory failed!");
6612
6613 // init volume map
6614 // todo device
6615 for (size_t i = 0; i < IPolicyProvider::GetVolumeVectorSize(); i++) {
6616 int32_t currentVolumeLevel = audioPolicyManager_.GetSystemVolumeLevel(g_volumeIndexVector[i].first);
6617 float volFloat =
6618 GetSystemVolumeInDb(g_volumeIndexVector[i].first, currentVolumeLevel, GetCurrentOutputDeviceType());
6619 volumeVector_[i].isMute = false;
6620 volumeVector_[i].volumeFloat = volFloat;
6621 volumeVector_[i].volumeInt = 0;
6622 }
6623 SetSharedAbsVolumeScene(false);
6624 buffer = policyVolumeMap_;
6625
6626 return SUCCESS;
6627 }
6628
GetSharedVolume(AudioVolumeType streamType,DeviceType deviceType,Volume & vol)6629 bool AudioPolicyService::GetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume &vol)
6630 {
6631 CHECK_AND_RETURN_RET_LOG(volumeVector_ != nullptr, false, "Get shared memory failed!");
6632 size_t index = 0;
6633 if (!IPolicyProvider::GetVolumeIndex(streamType, GetVolumeGroupForDevice(deviceType), index) ||
6634 index >= IPolicyProvider::GetVolumeVectorSize()) {
6635 return false;
6636 }
6637 vol.isMute = volumeVector_[index].isMute;
6638 vol.volumeFloat = volumeVector_[index].volumeFloat;
6639 vol.volumeInt = volumeVector_[index].volumeInt;
6640 return true;
6641 }
6642
SetSharedVolume(AudioVolumeType streamType,DeviceType deviceType,Volume vol)6643 bool AudioPolicyService::SetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume vol)
6644 {
6645 CHECK_AND_RETURN_RET_LOG(volumeVector_ != nullptr, false, "Set shared memory failed!");
6646 size_t index = 0;
6647 if (!IPolicyProvider::GetVolumeIndex(streamType, GetVolumeGroupForDevice(deviceType), index) ||
6648 index >= IPolicyProvider::GetVolumeVectorSize()) {
6649 return false;
6650 }
6651 volumeVector_[index].isMute = vol.isMute;
6652 volumeVector_[index].volumeFloat = vol.volumeFloat;
6653 volumeVector_[index].volumeInt = vol.volumeInt;
6654
6655 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
6656 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, false, "SetSharedVolume, Audio server Proxy is null");
6657
6658 std::string identity = IPCSkeleton::ResetCallingIdentity();
6659 gsp->NotifyStreamVolumeChanged(streamType, vol.volumeFloat);
6660 IPCSkeleton::SetCallingIdentity(identity);
6661 return true;
6662 }
6663
SetParameterCallback(const std::shared_ptr<AudioParameterCallback> & callback)6664 void AudioPolicyService::SetParameterCallback(const std::shared_ptr<AudioParameterCallback>& callback)
6665 {
6666 AUDIO_INFO_LOG("AudioPolicyService::SetParameterCallback");
6667 sptr<AudioManagerListenerStub> parameterChangeCbStub = new(std::nothrow) AudioManagerListenerStub();
6668 CHECK_AND_RETURN_LOG(parameterChangeCbStub != nullptr,
6669 "SetParameterCallback parameterChangeCbStub null");
6670 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
6671 CHECK_AND_RETURN_LOG(gsp != nullptr, "SetParameterCallback gsp null");
6672 parameterChangeCbStub->SetParameterCallback(callback);
6673
6674 sptr<IRemoteObject> object = parameterChangeCbStub->AsObject();
6675 if (object == nullptr) {
6676 AUDIO_ERR_LOG("SetParameterCallback listenerStub object is nullptr");
6677 return;
6678 }
6679 AUDIO_DEBUG_LOG("SetParameterCallback done");
6680 std::string identity = IPCSkeleton::ResetCallingIdentity();
6681 gsp->SetParameterCallback(object);
6682 IPCSkeleton::SetCallingIdentity(identity);
6683 }
6684
CheckStreamOffloadMode(int64_t activateSessionId,AudioStreamType streamType)6685 bool AudioPolicyService::CheckStreamOffloadMode(int64_t activateSessionId, AudioStreamType streamType)
6686 {
6687 if (!GetOffloadAvailableFromXml()) {
6688 AUDIO_INFO_LOG("Offload not available, skipped for set");
6689 return false;
6690 }
6691
6692 if (!CheckActiveOutputDeviceSupportOffload()) {
6693 AUDIO_PRERELEASE_LOGI("Offload not available on current output device, skipped");
6694 return false;
6695 }
6696
6697 if (!streamCollector_.IsOffloadAllowed(activateSessionId)) {
6698 AUDIO_PRERELEASE_LOGI("Offload is not allowed, Skipped");
6699 return false;
6700 }
6701
6702 if ((streamType != STREAM_MUSIC) && (streamType != STREAM_SPEECH)) {
6703 AUDIO_DEBUG_LOG("StreamType not allowed get offload mode, Skipped");
6704 return false;
6705 }
6706
6707 AudioPipeType pipeType;
6708 streamCollector_.GetPipeType(activateSessionId, pipeType);
6709 if (pipeType == PIPE_TYPE_DIRECT_MUSIC) {
6710 AUDIO_INFO_LOG("stream is direct, Skipped");
6711 return false;
6712 }
6713
6714 int32_t channelCount = GetChannelCount(activateSessionId);
6715 if ((channelCount != AudioChannel::MONO) && (channelCount != AudioChannel::STEREO)) {
6716 AUDIO_DEBUG_LOG("ChannelNum not allowed get offload mode, Skipped");
6717 return false;
6718 }
6719
6720 int32_t offloadUID = GetUid(activateSessionId);
6721 if (offloadUID == -1) {
6722 AUDIO_DEBUG_LOG("offloadUID not valid, Skipped");
6723 return false;
6724 }
6725 if (offloadUID == UID_AUDIO) {
6726 AUDIO_DEBUG_LOG("Skip anco_audio out of offload mode");
6727 return false;
6728 }
6729
6730 if (CheckSpatializationAndEffectState()) {
6731 AUDIO_INFO_LOG("spatialization effect in arm, Skipped");
6732 return false;
6733 }
6734 return true;
6735 }
6736
ConstructOffloadAudioModuleInfo(DeviceType deviceType)6737 AudioModuleInfo AudioPolicyService::ConstructOffloadAudioModuleInfo(DeviceType deviceType)
6738 {
6739 AudioModuleInfo audioModuleInfo = {};
6740 audioModuleInfo.lib = "libmodule-hdi-sink.z.so";
6741 audioModuleInfo.format = "s32le"; // 32bit little endian
6742 audioModuleInfo.fixedLatency = "1"; // here we need to set latency fixed for a fixed buffer size.
6743
6744 // used as "sink_name" in hdi_sink.c, hope we could use name to find target sink.
6745 audioModuleInfo.name = OFFLOAD_PRIMARY_SPEAKER;
6746
6747 std::stringstream typeValue;
6748 typeValue << static_cast<int32_t>(deviceType);
6749 audioModuleInfo.deviceType = typeValue.str();
6750
6751 audioModuleInfo.adapterName = "primary";
6752 audioModuleInfo.className = "offload"; // used in renderer_sink_adapter.c
6753 audioModuleInfo.fileName = "offload_dump_file";
6754 audioModuleInfo.offloadEnable = "1";
6755
6756 audioModuleInfo.channels = "2";
6757 audioModuleInfo.rate = "48000";
6758 audioModuleInfo.bufferSize = "7680";
6759
6760 return audioModuleInfo;
6761 }
6762
LoadOffloadModule()6763 int32_t AudioPolicyService::LoadOffloadModule()
6764 {
6765 AUDIO_INFO_LOG("load offload mode");
6766 std::unique_lock<std::mutex> lock(offloadCloseMutex_);
6767 isOffloadOpened_.store(true);
6768 offloadCloseCondition_.notify_all();
6769 {
6770 std::lock_guard<std::mutex> lock(offloadOpenMutex_);
6771 if (IOHandles_.find(OFFLOAD_PRIMARY_SPEAKER) != IOHandles_.end()) {
6772 AUDIO_INFO_LOG("offload is open");
6773 return SUCCESS;
6774 }
6775
6776 DeviceType deviceType = DEVICE_TYPE_SPEAKER;
6777 AudioModuleInfo moduleInfo = ConstructOffloadAudioModuleInfo(deviceType);
6778 return OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
6779 }
6780 return SUCCESS;
6781 }
6782
UnloadOffloadModule()6783 int32_t AudioPolicyService::UnloadOffloadModule()
6784 {
6785 AUDIO_INFO_LOG("unload offload module");
6786 std::unique_lock<std::mutex> lock(offloadCloseMutex_);
6787 // Try to wait 3 seconds before unloading the module, because the audio driver takes some time to process
6788 // the shutdown process..
6789 offloadCloseCondition_.wait_for(lock, std::chrono::seconds(WAIT_OFFLOAD_CLOSE_TIME_S),
6790 [this] () { return isOffloadOpened_.load(); });
6791 {
6792 std::lock_guard<std::mutex> lock(offloadOpenMutex_);
6793 if (isOffloadOpened_.load()) {
6794 AUDIO_INFO_LOG("offload restart");
6795 return ERROR;
6796 }
6797 ClosePortAndEraseIOHandle(OFFLOAD_PRIMARY_SPEAKER);
6798 }
6799 return SUCCESS;
6800 }
6801
CheckStreamMultichannelMode(const int64_t activateSessionId)6802 bool AudioPolicyService::CheckStreamMultichannelMode(const int64_t activateSessionId)
6803 {
6804 if (GetCurrentOutputDeviceNetworkId() != LOCAL_NETWORK_ID ||
6805 GetCurrentOutputDeviceType() == DEVICE_TYPE_REMOTE_CAST) {
6806 return false;
6807 }
6808
6809 // Multi-channel mode only when the number of channels is greater than 2.
6810 int32_t channelCount = GetChannelCount(activateSessionId);
6811 if (channelCount < AudioChannel::CHANNEL_3) {
6812 AUDIO_DEBUG_LOG("ChannelNum not allowed get multichannel mode, Skipped");
6813 return false;
6814 }
6815
6816 // The multi-channel algorithm needs to be supported in the DSP
6817 return GetAudioEffectOffloadFlag();
6818 }
6819
ConstructMchAudioModuleInfo(DeviceType deviceType)6820 AudioModuleInfo AudioPolicyService::ConstructMchAudioModuleInfo(DeviceType deviceType)
6821 {
6822 AudioModuleInfo audioModuleInfo = {};
6823 audioModuleInfo.lib = "libmodule-hdi-sink.z.so";
6824 audioModuleInfo.format = "s32le"; // 32bit little endian
6825 audioModuleInfo.fixedLatency = "1"; // here we need to set latency fixed for a fixed buffer size.
6826
6827 // used as "sink_name" in hdi_sink.c, hope we could use name to find target sink.
6828 audioModuleInfo.name = MCH_PRIMARY_SPEAKER;
6829
6830 std::stringstream typeValue;
6831 typeValue << static_cast<int32_t>(deviceType);
6832 audioModuleInfo.deviceType = typeValue.str();
6833
6834 audioModuleInfo.adapterName = "primary";
6835 audioModuleInfo.className = "multichannel"; // used in renderer_sink_adapter.c
6836 audioModuleInfo.fileName = "mch_dump_file";
6837
6838 audioModuleInfo.channels = "6";
6839 audioModuleInfo.rate = "48000";
6840 audioModuleInfo.bufferSize = "7680";
6841
6842 return audioModuleInfo;
6843 }
6844
LoadMchModule()6845 int32_t AudioPolicyService::LoadMchModule()
6846 {
6847 AUDIO_INFO_LOG("load multichannel mode");
6848 DeviceType deviceType = DEVICE_TYPE_SPEAKER;
6849 AudioModuleInfo moduleInfo = ConstructMchAudioModuleInfo(deviceType);
6850 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
6851 return SUCCESS;
6852 }
6853
UnloadMchModule()6854 int32_t AudioPolicyService::UnloadMchModule()
6855 {
6856 AUDIO_INFO_LOG("unload multichannel module");
6857 return ClosePortAndEraseIOHandle(MCH_PRIMARY_SPEAKER);
6858 }
6859
CheckStreamMode(const int64_t activateSessionId)6860 void AudioPolicyService::CheckStreamMode(const int64_t activateSessionId)
6861 {
6862 if (CheckStreamMultichannelMode(activateSessionId)) {
6863 AudioPipeType pipeMultiChannel = PIPE_TYPE_MULTICHANNEL;
6864 int32_t ret = ActivateAudioConcurrency(pipeMultiChannel);
6865 CHECK_AND_RETURN_LOG(ret == SUCCESS, "concede incoming multichannel");
6866 MoveToNewPipeInner(activateSessionId, PIPE_TYPE_MULTICHANNEL);
6867 }
6868 }
6869
MoveToNewPipe(uint32_t sessionId,AudioPipeType pipeType)6870 int32_t AudioPolicyService::MoveToNewPipe(uint32_t sessionId, AudioPipeType pipeType)
6871 {
6872 // Check if the stream exists
6873 int32_t defaultUid = -1;
6874 if (defaultUid == streamCollector_.GetUid(sessionId)) {
6875 AUDIO_ERR_LOG("The audio stream information [%{public}d] is illegal", sessionId);
6876 return ERROR;
6877 }
6878 // move the stream to new pipe
6879 return MoveToNewPipeInner(sessionId, pipeType);
6880 }
6881
DynamicUnloadModule(const AudioPipeType pipeType)6882 int32_t AudioPolicyService::DynamicUnloadModule(const AudioPipeType pipeType)
6883 {
6884 switch (pipeType) {
6885 case PIPE_TYPE_OFFLOAD:
6886 if (isOffloadOpened_.load()) {
6887 isOffloadOpened_.store(false);
6888 auto unloadFirOffloadThrd = [this] { this->UnloadOffloadModule(); };
6889 std::thread unloadOffloadThrd(unloadFirOffloadThrd);
6890 unloadOffloadThrd.detach();
6891 }
6892 break;
6893 case PIPE_TYPE_MULTICHANNEL:
6894 return UnloadMchModule();
6895 default:
6896 AUDIO_WARNING_LOG("not supported for pipe type %{public}d", pipeType);
6897 break;
6898 }
6899 return SUCCESS;
6900 }
6901
MoveToNewPipeInner(uint32_t sessionId,AudioPipeType pipeType)6902 int32_t AudioPolicyService::MoveToNewPipeInner(uint32_t sessionId, AudioPipeType pipeType)
6903 {
6904 AudioPipeType oldPipeType;
6905 streamCollector_.GetPipeType(sessionId, oldPipeType);
6906 if (oldPipeType == pipeType) {
6907 AUDIO_ERR_LOG("the same type [%{public}d],no need to move", pipeType);
6908 return SUCCESS;
6909 }
6910 Trace trace("AudioPolicyService::MoveToNewPipeInner");
6911 AUDIO_INFO_LOG("start move stream into new pipe %{public}d", pipeType);
6912 int32_t ret = ERROR;
6913 std::string portName = PORT_NONE;
6914 AudioStreamType streamType = streamCollector_.GetStreamType(sessionId);
6915 DeviceType deviceType = GetActiveOutputDevice();
6916 switch (pipeType) {
6917 case PIPE_TYPE_OFFLOAD: {
6918 if (!CheckStreamOffloadMode(sessionId, streamType)) {
6919 return ERROR;
6920 }
6921 if (LoadOffloadModule() != SUCCESS) {
6922 return ERROR;
6923 }
6924 portName = GetSinkPortName(deviceType, pipeType);
6925 ret = MoveToOutputDevice(sessionId, portName);
6926 break;
6927 }
6928 case PIPE_TYPE_MULTICHANNEL: {
6929 if (!CheckStreamMultichannelMode(sessionId)) {
6930 return ERROR;
6931 }
6932 if (IOHandles_.find(MCH_PRIMARY_SPEAKER) == IOHandles_.end()) {
6933 // load moudle and move into new sink
6934 LoadMchModule();
6935 }
6936 portName = GetSinkPortName(deviceType, pipeType);
6937 ret = MoveToOutputDevice(sessionId, portName);
6938 break;
6939 }
6940 case PIPE_TYPE_NORMAL_OUT: {
6941 portName = GetSinkPortName(deviceType, pipeType);
6942 ret = MoveToOutputDevice(sessionId, portName);
6943 break;
6944 }
6945 default:
6946 AUDIO_WARNING_LOG("not supported for pipe type %{public}d", pipeType);
6947 break;
6948 }
6949 if (ret == SUCCESS) {
6950 streamCollector_.UpdateRendererPipeInfo(sessionId, pipeType);
6951 }
6952 return ret;
6953 }
6954
GetMaxRendererInstances()6955 int32_t AudioPolicyService::GetMaxRendererInstances()
6956 {
6957 for (auto &configInfo : globalConfigs_.outputConfigInfos_) {
6958 if (configInfo.name_ == "normal" && configInfo.value_ != "") {
6959 AUDIO_INFO_LOG("Max output normal instance is %{public}s", configInfo.value_.c_str());
6960 return (int32_t)std::stoi(configInfo.value_);
6961 }
6962 }
6963 return DEFAULT_MAX_OUTPUT_NORMAL_INSTANCES;
6964 }
6965
CheckMaxRendererInstances()6966 int32_t AudioPolicyService::CheckMaxRendererInstances()
6967 {
6968 std::vector<std::unique_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos;
6969 streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
6970 AUDIO_INFO_LOG("Audio current renderer change infos size: %{public}zu", audioRendererChangeInfos.size());
6971 int32_t maxRendererInstances = GetMaxRendererInstances();
6972 if (audioRendererChangeInfos.size() >= static_cast<size_t>(maxRendererInstances)) {
6973 std::map<int32_t, int32_t> appUseNumMap;
6974 int32_t mostAppUid = INVALID_APP_UID;
6975 int32_t mostAppNum = INVALID_APP_CREATED_AUDIO_STREAM_NUM;
6976 for (auto it = audioRendererChangeInfos.begin(); it != audioRendererChangeInfos.end(); it++) {
6977 auto appUseNum = appUseNumMap.find((*it)->clientUID);
6978 if (appUseNum != appUseNumMap.end()) {
6979 appUseNumMap[(*it)->clientUID] = ++appUseNum->second;
6980 } else {
6981 appUseNumMap.emplace((*it)->clientUID, INITIAL_VALUE);
6982 }
6983 }
6984 for (auto iter = appUseNumMap.begin(); iter != appUseNumMap.end(); iter++) {
6985 if (iter->second > mostAppNum) {
6986 mostAppNum = iter->second;
6987 mostAppUid = iter->first;
6988 }
6989 }
6990 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
6991 Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::AUDIO_STREAM_EXHAUSTED_STATS,
6992 Media::MediaMonitor::EventType::FREQUENCY_AGGREGATION_EVENT);
6993 bean->Add("CLIENT_UID", mostAppUid);
6994 bean->Add("STREAM_NUM", mostAppNum);
6995 AUDIO_INFO_LOG("mostAppUid: %{public}d, mostAppNum: %{public}d", mostAppUid, mostAppNum);
6996 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
6997 }
6998
6999 CHECK_AND_RETURN_RET_LOG(audioRendererChangeInfos.size() < static_cast<size_t>(maxRendererInstances), ERR_OVERFLOW,
7000 "The current number of audio renderer streams is greater than the maximum number of configured instances");
7001
7002 return SUCCESS;
7003 }
7004
7005 #ifdef BLUETOOTH_ENABLE
RegisterBluetoothDeathCallback()7006 const sptr<IStandardAudioService> RegisterBluetoothDeathCallback()
7007 {
7008 lock_guard<mutex> lock(g_btProxyMutex);
7009 if (g_btProxy == nullptr) {
7010 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
7011 CHECK_AND_RETURN_RET_LOG(samgr != nullptr, nullptr,
7012 "RegisterBluetoothDeathCallback: get sa manager failed");
7013 sptr<IRemoteObject> object = samgr->GetSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID);
7014 CHECK_AND_RETURN_RET_LOG(object != nullptr, nullptr,
7015 "RegisterBluetoothDeathCallback: get audio service remote object failed");
7016 g_btProxy = iface_cast<IStandardAudioService>(object);
7017 CHECK_AND_RETURN_RET_LOG(g_btProxy != nullptr, nullptr,
7018 "RegisterBluetoothDeathCallback: get audio service proxy failed");
7019
7020 // register death recipent
7021 sptr<AudioServerDeathRecipient> asDeathRecipient = new(std::nothrow) AudioServerDeathRecipient(getpid());
7022 if (asDeathRecipient != nullptr) {
7023 asDeathRecipient->SetNotifyCb([] (pid_t pid) {
7024 AudioPolicyService::BluetoothServiceCrashedCallback(pid);
7025 });
7026 bool result = object->AddDeathRecipient(asDeathRecipient);
7027 if (!result) {
7028 AUDIO_ERR_LOG("RegisterBluetoothDeathCallback: failed to add deathRecipient");
7029 }
7030 }
7031 }
7032 sptr<IStandardAudioService> gasp = g_btProxy;
7033 return gasp;
7034 }
7035
BluetoothServiceCrashedCallback(pid_t pid)7036 void AudioPolicyService::BluetoothServiceCrashedCallback(pid_t pid)
7037 {
7038 AUDIO_INFO_LOG("Bluetooth sa crashed, will restore proxy in next call");
7039 lock_guard<mutex> lock(g_btProxyMutex);
7040 g_btProxy = nullptr;
7041 isBtListenerRegistered = false;
7042 Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSink();
7043 Bluetooth::AudioHfpManager::DisconnectBluetoothHfpSink();
7044 }
7045 #endif
7046
RegisterBluetoothListener()7047 void AudioPolicyService::RegisterBluetoothListener()
7048 {
7049 #ifdef BLUETOOTH_ENABLE
7050 AUDIO_INFO_LOG("Enter AudioPolicyService::RegisterBluetoothListener");
7051 Bluetooth::RegisterDeviceObserver(deviceStatusListener_->deviceObserver_);
7052 if (isBtListenerRegistered) {
7053 AUDIO_INFO_LOG("audio policy service already register bt listerer, return");
7054 return;
7055 }
7056 Bluetooth::AudioA2dpManager::RegisterBluetoothA2dpListener();
7057 Bluetooth::AudioHfpManager::RegisterBluetoothScoListener();
7058 isBtListenerRegistered = true;
7059 const sptr<IStandardAudioService> gsp = RegisterBluetoothDeathCallback();
7060 isBTReconnecting_ = true;
7061 Bluetooth::AudioA2dpManager::CheckA2dpDeviceReconnect();
7062 Bluetooth::AudioHfpManager::CheckHfpDeviceReconnect();
7063 isBTReconnecting_ = false;
7064 #endif
7065 }
7066
UnregisterBluetoothListener()7067 void AudioPolicyService::UnregisterBluetoothListener()
7068 {
7069 #ifdef BLUETOOTH_ENABLE
7070 AUDIO_INFO_LOG("Enter AudioPolicyService::UnregisterBluetoothListener");
7071 Bluetooth::UnregisterDeviceObserver();
7072 Bluetooth::AudioA2dpManager::UnregisterBluetoothA2dpListener();
7073 Bluetooth::AudioHfpManager::UnregisterBluetoothScoListener();
7074 isBtListenerRegistered = false;
7075 #endif
7076 }
7077
SubscribeAccessibilityConfigObserver()7078 void AudioPolicyService::SubscribeAccessibilityConfigObserver()
7079 {
7080 #ifdef ACCESSIBILITY_ENABLE
7081 accessibilityConfigListener_->SubscribeObserver();
7082 AUDIO_INFO_LOG("Subscribe accessibility config observer successfully");
7083 #endif
7084 }
7085
GetMinStreamVolume()7086 float AudioPolicyService::GetMinStreamVolume()
7087 {
7088 return audioPolicyManager_.GetMinStreamVolume();
7089 }
7090
GetMaxStreamVolume()7091 float AudioPolicyService::GetMaxStreamVolume()
7092 {
7093 return audioPolicyManager_.GetMaxStreamVolume();
7094 }
7095
IsVolumeUnadjustable()7096 bool AudioPolicyService::IsVolumeUnadjustable()
7097 {
7098 return audioPolicyManager_.IsVolumeUnadjustable();
7099 }
7100
GetStreamVolumeInfoMap(StreamVolumeInfoMap & streamVolumeInfoMap)7101 void AudioPolicyService::GetStreamVolumeInfoMap(StreamVolumeInfoMap &streamVolumeInfoMap)
7102 {
7103 return audioPolicyManager_.GetStreamVolumeInfoMap(streamVolumeInfoMap);
7104 }
7105
GetSystemVolumeInDb(AudioVolumeType volumeType,int32_t volumeLevel,DeviceType deviceType) const7106 float AudioPolicyService::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel,
7107 DeviceType deviceType) const
7108 {
7109 return audioPolicyManager_.GetSystemVolumeInDb(volumeType, volumeLevel, deviceType);
7110 }
7111
QueryEffectManagerSceneMode(SupportedEffectConfig & supportedEffectConfig)7112 int32_t AudioPolicyService::QueryEffectManagerSceneMode(SupportedEffectConfig& supportedEffectConfig)
7113 {
7114 int32_t ret = audioEffectService_.QueryEffectManagerSceneMode(supportedEffectConfig);
7115 return ret;
7116 }
7117
RegisterDataObserver()7118 void AudioPolicyService::RegisterDataObserver()
7119 {
7120 std::string devicesName = "";
7121 int32_t ret = GetDeviceNameFromDataShareHelper(devicesName);
7122 CHECK_AND_RETURN_LOG(ret == SUCCESS, "RegisterDataObserver get devicesName failed");
7123 SetDisplayName(devicesName, true);
7124 RegisterNameMonitorHelper();
7125 }
7126
IsConnectedOutputDevice(const sptr<AudioDeviceDescriptor> & desc)7127 bool AudioPolicyService::IsConnectedOutputDevice(const sptr<AudioDeviceDescriptor> &desc)
7128 {
7129 DeviceType deviceType = desc->deviceType_;
7130
7131 CHECK_AND_RETURN_RET_LOG(desc->deviceRole_ == DeviceRole::OUTPUT_DEVICE, false,
7132 "Not output device!");
7133
7134 auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &desc) {
7135 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
7136 if (deviceType == DEVICE_TYPE_FILE_SINK) {
7137 return false;
7138 }
7139 return ((deviceType == desc->deviceType_) && (desc->deviceRole_ == DeviceRole::OUTPUT_DEVICE));
7140 };
7141
7142 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
7143 CHECK_AND_RETURN_RET_LOG(itr != connectedDevices_.end(), false, "Device not available");
7144
7145 return true;
7146 }
7147
GetHardwareOutputSamplingRate(const sptr<AudioDeviceDescriptor> & desc)7148 int32_t AudioPolicyService::GetHardwareOutputSamplingRate(const sptr<AudioDeviceDescriptor> &desc)
7149 {
7150 int32_t rate = 48000;
7151
7152 CHECK_AND_RETURN_RET_LOG(desc != nullptr, -1, "desc is null!");
7153
7154 bool ret = IsConnectedOutputDevice(desc);
7155 CHECK_AND_RETURN_RET(ret, -1);
7156
7157 DeviceType clientDevType = desc->deviceType_;
7158 for (const auto &device : deviceClassInfo_) {
7159 auto moduleInfoList = device.second;
7160 for (auto &moduleInfo : moduleInfoList) {
7161 auto serverDevType = GetDeviceType(moduleInfo.name);
7162 if (clientDevType == serverDevType) {
7163 rate = atoi(moduleInfo.rate.c_str());
7164 return rate;
7165 }
7166 }
7167 }
7168
7169 return rate;
7170 }
7171
AddMicrophoneDescriptor(sptr<AudioDeviceDescriptor> & deviceDescriptor)7172 void AudioPolicyService::AddMicrophoneDescriptor(sptr<AudioDeviceDescriptor> &deviceDescriptor)
7173 {
7174 if (deviceDescriptor->deviceRole_ == INPUT_DEVICE &&
7175 deviceDescriptor->deviceType_ != DEVICE_TYPE_FILE_SOURCE) {
7176 auto isPresent = [&deviceDescriptor](const sptr<MicrophoneDescriptor> &desc) {
7177 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
7178 return desc->deviceType_ == deviceDescriptor->deviceType_;
7179 };
7180
7181 auto iter = std::find_if(connectedMicrophones_.begin(), connectedMicrophones_.end(), isPresent);
7182 if (iter == connectedMicrophones_.end()) {
7183 sptr<MicrophoneDescriptor> micDesc = new (std::nothrow) MicrophoneDescriptor(startMicrophoneId++,
7184 deviceDescriptor->deviceType_);
7185 CHECK_AND_RETURN_LOG(micDesc != nullptr, "new MicrophoneDescriptor failed");
7186 connectedMicrophones_.push_back(micDesc);
7187 }
7188 }
7189 }
7190
RemoveMicrophoneDescriptor(sptr<AudioDeviceDescriptor> & deviceDescriptor)7191 void AudioPolicyService::RemoveMicrophoneDescriptor(sptr<AudioDeviceDescriptor> &deviceDescriptor)
7192 {
7193 auto isPresent = [&deviceDescriptor](const sptr<MicrophoneDescriptor> &desc) {
7194 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
7195 return desc->deviceType_ == deviceDescriptor->deviceType_;
7196 };
7197
7198 auto iter = std::find_if(connectedMicrophones_.begin(), connectedMicrophones_.end(), isPresent);
7199 if (iter != connectedMicrophones_.end()) {
7200 connectedMicrophones_.erase(iter);
7201 }
7202 }
7203
AddAudioCapturerMicrophoneDescriptor(int32_t sessionId,DeviceType devType)7204 void AudioPolicyService::AddAudioCapturerMicrophoneDescriptor(int32_t sessionId, DeviceType devType)
7205 {
7206 if (devType == DEVICE_TYPE_NONE) {
7207 audioCaptureMicrophoneDescriptor_[sessionId] = new MicrophoneDescriptor(0, DEVICE_TYPE_INVALID);
7208 return;
7209 }
7210 auto isPresent = [&devType] (const sptr<MicrophoneDescriptor> &desc) {
7211 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid microphone descriptor");
7212 return (devType == desc->deviceType_);
7213 };
7214
7215 auto itr = std::find_if(connectedMicrophones_.begin(), connectedMicrophones_.end(), isPresent);
7216 if (itr != connectedMicrophones_.end()) {
7217 audioCaptureMicrophoneDescriptor_[sessionId] = *itr;
7218 }
7219 }
7220
GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)7221 vector<sptr<MicrophoneDescriptor>> AudioPolicyService::GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)
7222 {
7223 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
7224
7225 vector<sptr<MicrophoneDescriptor>> descList = {};
7226 const auto desc = audioCaptureMicrophoneDescriptor_.find(sessionId);
7227 if (desc != audioCaptureMicrophoneDescriptor_.end()) {
7228 sptr<MicrophoneDescriptor> micDesc = new (std::nothrow) MicrophoneDescriptor(desc->second);
7229 if (micDesc == nullptr) {
7230 AUDIO_ERR_LOG("Create microphone device descriptor failed");
7231 return descList;
7232 }
7233 descList.push_back(micDesc);
7234 }
7235 return descList;
7236 }
7237
GetAvailableMicrophones()7238 vector<sptr<MicrophoneDescriptor>> AudioPolicyService::GetAvailableMicrophones()
7239 {
7240 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
7241 return connectedMicrophones_;
7242 }
7243
UpdateAudioCapturerMicrophoneDescriptor(DeviceType devType)7244 void AudioPolicyService::UpdateAudioCapturerMicrophoneDescriptor(DeviceType devType)
7245 {
7246 auto isPresent = [&devType] (const sptr<MicrophoneDescriptor> &desc) {
7247 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid microphone descriptor");
7248 return (devType == desc->deviceType_);
7249 };
7250
7251 auto itr = std::find_if(connectedMicrophones_.begin(), connectedMicrophones_.end(), isPresent);
7252 if (itr != connectedMicrophones_.end()) {
7253 for (auto& desc : audioCaptureMicrophoneDescriptor_) {
7254 if (desc.second->deviceType_ != devType) {
7255 desc.second = *itr;
7256 }
7257 }
7258 }
7259 }
7260
RemoveAudioCapturerMicrophoneDescriptor(int32_t uid)7261 void AudioPolicyService::RemoveAudioCapturerMicrophoneDescriptor(int32_t uid)
7262 {
7263 vector<unique_ptr<AudioCapturerChangeInfo>> audioCapturerChangeInfos;
7264 streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos);
7265
7266 for (auto &info : audioCapturerChangeInfos) {
7267 if (info->clientUID != uid && info->createrUID != uid) {
7268 continue;
7269 }
7270 audioCaptureMicrophoneDescriptor_.erase(info->sessionId);
7271 }
7272 }
7273
FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo,StreamPropInfo & targetInfo,SourceType & targetSourceType)7274 int32_t AudioPolicyService::FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo, StreamPropInfo &targetInfo,
7275 SourceType &targetSourceType)
7276 {
7277 const PipeInfo *pipeInfoPtr = nullptr;
7278 if (adapterInfoMap_.count(AdaptersType::TYPE_PRIMARY) > 0) {
7279 pipeInfoPtr = adapterInfoMap_.at(AdaptersType::TYPE_PRIMARY).GetPipeByName(PIPE_PRIMARY_INPUT);
7280 }
7281 CHECK_AND_RETURN_RET_LOG(pipeInfoPtr != nullptr, ERROR, "pipeInfoPtr is null");
7282
7283 const auto &streamPropInfoList = pipeInfoPtr->streamPropInfos_;
7284
7285 if (streamPropInfoList.empty()) {
7286 AUDIO_ERR_LOG("supportedRate or supportedChannels is empty");
7287 return ERROR;
7288 }
7289 StreamPropInfo targetStreamPropInfo = *streamPropInfoList.begin();
7290 if (sessionInfo.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION
7291 || sessionInfo.sourceType == SOURCE_TYPE_VOICE_RECOGNITION) {
7292 targetSourceType = sessionInfo.sourceType;
7293 for (const auto &streamPropInfo : streamPropInfoList) {
7294 if (sessionInfo.channels == streamPropInfo.channelLayout_
7295 && sessionInfo.rate == streamPropInfo.sampleRate_) {
7296 targetStreamPropInfo = streamPropInfo;
7297 break;
7298 }
7299 }
7300 } else if (sessionInfo.sourceType == SOURCE_TYPE_VOICE_CALL) {
7301 targetSourceType = SOURCE_TYPE_VOICE_CALL;
7302 } else if (sessionInfo.sourceType == SOURCE_TYPE_CAMCORDER) {
7303 targetSourceType = SOURCE_TYPE_CAMCORDER;
7304 } else {
7305 // For normal sourcetype, continue to use the default value
7306 targetSourceType = SOURCE_TYPE_MIC;
7307 }
7308 targetInfo = targetStreamPropInfo;
7309 return SUCCESS;
7310 }
7311
OnCapturerSessionRemoved(uint64_t sessionID)7312 void AudioPolicyService::OnCapturerSessionRemoved(uint64_t sessionID)
7313 {
7314 if (sessionWithSpecialSourceType_.count(sessionID) > 0) {
7315 if (sessionWithSpecialSourceType_[sessionID].sourceType == SOURCE_TYPE_REMOTE_CAST) {
7316 HandleRemoteCastDevice(false);
7317 }
7318 sessionWithSpecialSourceType_.erase(sessionID);
7319 return;
7320 }
7321
7322 if (sessionWithNormalSourceType_.count(sessionID) > 0) {
7323 sessionWithNormalSourceType_.erase(sessionID);
7324 if (!sessionWithNormalSourceType_.empty()) {
7325 return;
7326 }
7327 ClosePortAndEraseIOHandle(PRIMARY_MIC);
7328 return;
7329 }
7330
7331 AUDIO_INFO_LOG("Sessionid:%{public}" PRIu64 " not added, directly placed into sessionIdisRemovedSet_", sessionID);
7332 sessionIdisRemovedSet_.insert(sessionID);
7333 }
7334
OnCapturerSessionAdded(uint64_t sessionID,SessionInfo sessionInfo,AudioStreamInfo streamInfo)7335 int32_t AudioPolicyService::OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo,
7336 AudioStreamInfo streamInfo)
7337 {
7338 CHECK_AND_RETURN_RET_LOG(isPolicyConfigParsered_ && isPrimaryMicModuleInfoLoaded_, ERROR,
7339 "policyConfig not loaded");
7340 if (sessionIdisRemovedSet_.count(sessionID) > 0) {
7341 sessionIdisRemovedSet_.erase(sessionID);
7342 AUDIO_INFO_LOG("sessionID: %{public}" PRIu64 " had already been removed earlier", sessionID);
7343 return SUCCESS;
7344 }
7345 if (specialSourceTypeSet_.count(sessionInfo.sourceType) == 0) {
7346 StreamPropInfo targetInfo;
7347 SourceType sourcetype;
7348 int32_t res = FetchTargetInfoForSessionAdd(sessionInfo, targetInfo, sourcetype);
7349 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, res,
7350 "FetchTargetInfoForSessionAdd error, maybe device not support recorder");
7351 bool isSourceLoaded = !sessionWithNormalSourceType_.empty();
7352 if (!isSourceLoaded) {
7353 auto moduleInfo = primaryMicModuleInfo_;
7354 // current layout represents the number of channel. This will need to be modify in the future.
7355 moduleInfo.channels = std::to_string(targetInfo.channelLayout_);
7356 moduleInfo.rate = std::to_string(targetInfo.sampleRate_);
7357 moduleInfo.bufferSize = std::to_string(targetInfo.bufferSize_);
7358 moduleInfo.format = targetInfo.format_;
7359 moduleInfo.sourceType = std::to_string(sourcetype);
7360 AUDIO_INFO_LOG("rate:%{public}s, channels:%{public}s, bufferSize:%{public}s format:%{public}s, "
7361 "sourcetype: %{public}s",
7362 moduleInfo.rate.c_str(), moduleInfo.channels.c_str(), moduleInfo.bufferSize.c_str(),
7363 moduleInfo.format.c_str(), moduleInfo.sourceType.c_str());
7364 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
7365 audioPolicyManager_.SetDeviceActive(GetCurrentInputDeviceType(),
7366 moduleInfo.name, true, INPUT_DEVICES_FLAG);
7367 }
7368 sessionWithNormalSourceType_[sessionID] = sessionInfo;
7369 } else if (sessionInfo.sourceType == SOURCE_TYPE_REMOTE_CAST) {
7370 HandleRemoteCastDevice(true, streamInfo);
7371 sessionWithSpecialSourceType_[sessionID] = sessionInfo;
7372 } else {
7373 sessionWithSpecialSourceType_[sessionID] = sessionInfo;
7374 }
7375 AUDIO_INFO_LOG("sessionID: %{public}" PRIu64 " OnCapturerSessionAdded end", sessionID);
7376 return SUCCESS;
7377 }
7378
RectifyModuleInfo(AudioModuleInfo & moduleInfo,std::list<AudioModuleInfo> & moduleInfoList,SourceInfo & targetInfo)7379 void AudioPolicyService::RectifyModuleInfo(AudioModuleInfo &moduleInfo, std::list<AudioModuleInfo> &moduleInfoList,
7380 SourceInfo &targetInfo)
7381 {
7382 auto [targetSourceType, targetRate, targetChannels] = targetInfo;
7383 for (auto &adapterModuleInfo : moduleInfoList) {
7384 if (moduleInfo.role == adapterModuleInfo.role &&
7385 adapterModuleInfo.name.find(MODULE_SINK_OFFLOAD) == std::string::npos) {
7386 CHECK_AND_CONTINUE_LOG(adapterModuleInfo.supportedRate_.count(targetRate) > 0, "rate unmatch.");
7387 CHECK_AND_CONTINUE_LOG(adapterModuleInfo.supportedChannels_.count(targetChannels) > 0, "channels unmatch.");
7388 moduleInfo.rate = std::to_string(targetRate);
7389 moduleInfo.channels = std::to_string(targetChannels);
7390 uint32_t sampleFormatBits = PcmFormatToBits(static_cast<AudioSampleFormat>(
7391 formatFromParserStrToEnum[moduleInfo.format]));
7392 uint32_t bufferSize = (targetRate * targetChannels * sampleFormatBits / BUFFER_CALC_1000MS)
7393 * BUFFER_CALC_20MS;
7394 moduleInfo.bufferSize = std::to_string(bufferSize);
7395 AUDIO_INFO_LOG("match success. rate:%{public}s, channels:%{public}s, bufferSize:%{public}s",
7396 moduleInfo.rate.c_str(), moduleInfo.channels.c_str(), moduleInfo.bufferSize.c_str());
7397 }
7398 }
7399 moduleInfo.sourceType = std::to_string(targetSourceType);
7400 currentRate = targetRate;
7401 currentSourceType = targetSourceType;
7402 }
7403
DeviceFilterByUsageInner(AudioDeviceUsage usage,const std::vector<sptr<AudioDeviceDescriptor>> & descs)7404 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::DeviceFilterByUsageInner(AudioDeviceUsage usage,
7405 const std::vector<sptr<AudioDeviceDescriptor>>& descs)
7406 {
7407 std::vector<unique_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors;
7408
7409 unordered_map<AudioDevicePrivacyType, list<DevicePrivacyInfo>> devicePrivacyMaps =
7410 audioDeviceManager_.GetDevicePrivacyMaps();
7411 for (const auto &dev : descs) {
7412 for (const auto &devicePrivacy : devicePrivacyMaps) {
7413 list<DevicePrivacyInfo> deviceInfos = devicePrivacy.second;
7414 audioDeviceManager_.GetAvailableDevicesWithUsage(usage, deviceInfos, dev, audioDeviceDescriptors);
7415 }
7416 }
7417 std::vector<sptr<AudioDeviceDescriptor>> deviceDescriptors;
7418 for (const auto &dec : audioDeviceDescriptors) {
7419 sptr<AudioDeviceDescriptor> tempDec = new(std::nothrow) AudioDeviceDescriptor(*dec);
7420 deviceDescriptors.push_back(move(tempDec));
7421 }
7422 return deviceDescriptors;
7423 }
7424
TriggerAvailableDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)7425 void AudioPolicyService::TriggerAvailableDeviceChangedCallback(
7426 const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected)
7427 {
7428 Trace trace("AudioPolicyService::TriggerAvailableDeviceChangedCallback");
7429
7430 WriteDeviceChangedSysEvents(desc, isConnected);
7431
7432 if (audioPolicyServerHandler_ != nullptr) {
7433 audioPolicyServerHandler_->SendAvailableDeviceChange(desc, isConnected);
7434 }
7435 }
7436
GetAvailableDevices(AudioDeviceUsage usage)7437 std::vector<unique_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetAvailableDevices(AudioDeviceUsage usage)
7438 {
7439 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
7440
7441 return GetAvailableDevicesInner(usage);
7442 }
7443
GetAvailableDevicesInner(AudioDeviceUsage usage)7444 std::vector<unique_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetAvailableDevicesInner(AudioDeviceUsage usage)
7445 {
7446 std::vector<unique_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors;
7447
7448 audioDeviceDescriptors = audioDeviceManager_.GetAvailableDevicesByUsage(usage);
7449
7450 AUDIO_INFO_LOG("audioDeviceDescriptors size:%{public}zu", audioDeviceDescriptors.size());
7451 return audioDeviceDescriptors;
7452 }
7453
OffloadStartPlaying(const std::vector<int32_t> & sessionIds)7454 int32_t AudioPolicyService::OffloadStartPlaying(const std::vector<int32_t> &sessionIds)
7455 {
7456 #ifdef BLUETOOTH_ENABLE
7457 AUDIO_INFO_LOG("OffloadStartPlaying, a2dpOffloadFlag_: %{public}d, sessionIds: %{public}zu",
7458 a2dpOffloadFlag_, sessionIds.size());
7459 if (a2dpOffloadFlag_ != A2DP_OFFLOAD || sessionIds.size() == 0) {
7460 return SUCCESS;
7461 }
7462 int32_t ret = Bluetooth::AudioA2dpManager::OffloadStartPlaying(sessionIds);
7463 if (audioA2dpOffloadManager_ != nullptr) {
7464 A2dpOffloadConnectionState state = audioA2dpOffloadManager_->GetA2dOffloadConnectionState();
7465 if (ret == SUCCESS && (state != CONNECTION_STATUS_CONNECTED)) {
7466 audioA2dpOffloadManager_->ConnectA2dpOffload(
7467 Bluetooth::AudioA2dpManager::GetActiveA2dpDevice(), sessionIds);
7468 }
7469 }
7470 return ret;
7471 #else
7472 return SUCCESS;
7473 #endif
7474 }
7475
OffloadStopPlaying(const std::vector<int32_t> & sessionIds)7476 int32_t AudioPolicyService::OffloadStopPlaying(const std::vector<int32_t> &sessionIds)
7477 {
7478 #ifdef BLUETOOTH_ENABLE
7479 AUDIO_PRERELEASE_LOGI("OffloadStopPlaying, a2dpOffloadFlag_: %{public}d, sessionIds: %{public}zu",
7480 a2dpOffloadFlag_, sessionIds.size());
7481 if (a2dpOffloadFlag_ != A2DP_OFFLOAD || sessionIds.size() == 0) {
7482 return SUCCESS;
7483 }
7484 return Bluetooth::AudioA2dpManager::OffloadStopPlaying(sessionIds);
7485 #else
7486 return SUCCESS;
7487 #endif
7488 }
7489
OffloadGetRenderPosition(uint32_t & delayValue,uint64_t & sendDataSize,uint32_t & timeStamp)7490 int32_t AudioPolicyService::OffloadGetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp)
7491 {
7492 Trace trace("AudioPolicyService::OffloadGetRenderPosition");
7493 #ifdef BLUETOOTH_ENABLE
7494 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
7495 AUDIO_DEBUG_LOG("GetRenderPosition, deviceType: %{public}d, a2dpOffloadFlag_: %{public}d",
7496 a2dpOffloadFlag_, curOutputDeviceType);
7497 int32_t ret = SUCCESS;
7498 if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP &&
7499 GetCurrentOutputDeviceNetworkId() == LOCAL_NETWORK_ID && a2dpOffloadFlag_ == A2DP_OFFLOAD) {
7500 ret = Bluetooth::AudioA2dpManager::GetRenderPosition(delayValue, sendDataSize, timeStamp);
7501 } else {
7502 delayValue = 0;
7503 sendDataSize = 0;
7504 timeStamp = 0;
7505 }
7506 return ret;
7507 #else
7508 return SUCCESS;
7509 #endif
7510 }
7511
GetAndSaveClientType(uint32_t uid,const std::string & bundleName)7512 int32_t AudioPolicyService::GetAndSaveClientType(uint32_t uid, const std::string &bundleName)
7513 {
7514 #ifdef FEATURE_APPGALLERY
7515 ClientTypeManager::GetInstance()->GetAndSaveClientType(uid, bundleName);
7516 #endif
7517 return SUCCESS;
7518 }
7519
GetA2dpOffloadCodecAndSendToDsp()7520 void AudioPolicyService::GetA2dpOffloadCodecAndSendToDsp()
7521 {
7522 #ifdef BLUETOOTH_ENABLE
7523 if (GetCurrentOutputDeviceType() != DEVICE_TYPE_BLUETOOTH_A2DP) {
7524 return;
7525 }
7526 Bluetooth::BluetoothRemoteDevice bluetoothRemoteDevice_ = Bluetooth::AudioA2dpManager::GetCurrentActiveA2dpDevice();
7527 Bluetooth::A2dpOffloadCodecStatus offloadCodeStatus = Bluetooth::A2dpSource::GetProfile()->
7528 GetOffloadCodecStatus(bluetoothRemoteDevice_);
7529 std::string key = "AUDIO_EXT_PARAM_KEY_A2DP_OFFLOAD_CONFIG";
7530 std::string value = std::to_string(offloadCodeStatus.offloadInfo.mediaPacketHeader) + ","
7531 + std::to_string(offloadCodeStatus.offloadInfo.mPt) + ","
7532 + std::to_string(offloadCodeStatus.offloadInfo.ssrc) + ","
7533 + std::to_string(offloadCodeStatus.offloadInfo.boundaryFlag) + ","
7534 + std::to_string(offloadCodeStatus.offloadInfo.broadcastFlag) + ","
7535 + std::to_string(offloadCodeStatus.offloadInfo.codecType) + ","
7536 + std::to_string(offloadCodeStatus.offloadInfo.maxLatency) + ","
7537 + std::to_string(offloadCodeStatus.offloadInfo.scmsTEnable) + ","
7538 + std::to_string(offloadCodeStatus.offloadInfo.sampleRate) + ","
7539 + std::to_string(offloadCodeStatus.offloadInfo.encodedAudioBitrate) + ","
7540 + std::to_string(offloadCodeStatus.offloadInfo.bitsPerSample) + ","
7541 + std::to_string(offloadCodeStatus.offloadInfo.chMode) + ","
7542 + std::to_string(offloadCodeStatus.offloadInfo.aclHdl) + ","
7543 + std::to_string(offloadCodeStatus.offloadInfo.l2cRcid) + ","
7544 + std::to_string(offloadCodeStatus.offloadInfo.mtu) + ","
7545 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific0) + ","
7546 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific1) + ","
7547 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific2) + ","
7548 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific3) + ","
7549 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific4) + ","
7550 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific5) + ","
7551 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific6) + ","
7552 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific7) + ";";
7553 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
7554 std::string identity = IPCSkeleton::ResetCallingIdentity();
7555 gsp->SetAudioParameter(key, value);
7556 IPCSkeleton::SetCallingIdentity(identity);
7557 AUDIO_DEBUG_LOG("update offloadcodec[%{public}s]", value.c_str());
7558 #endif
7559 }
7560
7561 #ifdef BLUETOOTH_ENABLE
UpdateA2dpOffloadFlag(const std::vector<Bluetooth::A2dpStreamInfo> & allActiveSessions,DeviceType deviceType)7562 void AudioPolicyService::UpdateA2dpOffloadFlag(const std::vector<Bluetooth::A2dpStreamInfo> &allActiveSessions,
7563 DeviceType deviceType)
7564 {
7565 if (allActiveSessions.size() == 0) {
7566 AUDIO_PRERELEASE_LOGI("no active sessions");
7567 return;
7568 }
7569 auto receiveOffloadFlag = NO_A2DP_DEVICE;
7570 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
7571 receiveOffloadFlag = static_cast<BluetoothOffloadState>(Bluetooth::AudioA2dpManager::A2dpOffloadSessionRequest(
7572 allActiveSessions));
7573 } else if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_A2DP &&
7574 GetCurrentOutputDeviceNetworkId() == LOCAL_NETWORK_ID && deviceType == DEVICE_TYPE_NONE) {
7575 receiveOffloadFlag = static_cast<BluetoothOffloadState>(Bluetooth::AudioA2dpManager::A2dpOffloadSessionRequest(
7576 allActiveSessions));
7577 }
7578
7579 std::lock_guard<std::mutex> lock(switchA2dpOffloadMutex_);
7580 AUDIO_PRERELEASE_LOGI("deviceType: %{public}d, currentActiveDevice_: %{public}d, allActiveSessions: %{public}zu, "
7581 "a2dpOffloadFlag_: %{public}d, receiveOffloadFlag: %{public}d",
7582 deviceType, GetCurrentOutputDeviceType(), allActiveSessions.size(), a2dpOffloadFlag_,
7583 receiveOffloadFlag);
7584
7585 if (receiveOffloadFlag == NO_A2DP_DEVICE) {
7586 UpdateOffloadWhenActiveDeviceSwitchFromA2dp();
7587 } else if (receiveOffloadFlag != a2dpOffloadFlag_) {
7588 if (a2dpOffloadFlag_ == A2DP_OFFLOAD) {
7589 HandleA2dpDeviceOutOffload(receiveOffloadFlag);
7590 } else if (receiveOffloadFlag == A2DP_OFFLOAD) {
7591 HandleA2dpDeviceInOffload(receiveOffloadFlag);
7592 } else {
7593 AUDIO_INFO_LOG("a2dpOffloadFlag_ change from %{public}d to %{public}d", a2dpOffloadFlag_,
7594 receiveOffloadFlag);
7595 a2dpOffloadFlag_ = receiveOffloadFlag;
7596 }
7597 } else if (a2dpOffloadFlag_ == A2DP_OFFLOAD) {
7598 std::vector<int32_t> allSessions;
7599 GetAllRunningStreamSession(allSessions);
7600 OffloadStartPlaying(allSessions);
7601 UpdateEffectBtOffloadSupported(true);
7602 ResetOffloadModeOnSpatializationChanged(allSessions);
7603 GetA2dpOffloadCodecAndSendToDsp();
7604 std::string activePort = BLUETOOTH_SPEAKER;
7605 audioPolicyManager_.SuspendAudioDevice(activePort, true);
7606 }
7607 }
7608
ResetOffloadModeOnSpatializationChanged(std::vector<int32_t> & allSessions)7609 void AudioPolicyService::ResetOffloadModeOnSpatializationChanged(std::vector<int32_t> &allSessions)
7610 {
7611 AudioSpatializationState spatialState =
7612 AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState();
7613 bool effectOffloadFlag = GetAudioEffectOffloadFlag();
7614 AUDIO_INFO_LOG("spatialization: %{public}d, headTracking: %{public}d, effectOffloadFlag: %{public}d",
7615 spatialState.spatializationEnabled, spatialState.headTrackingEnabled, effectOffloadFlag);
7616 if (spatialState.spatializationEnabled) {
7617 if (effectOffloadFlag) {
7618 for (auto it = allSessions.begin(); it != allSessions.end(); it++) {
7619 OffloadStreamSetCheck(*it);
7620 }
7621 } else {
7622 OffloadStreamReleaseCheck(*offloadSessionID_);
7623 }
7624 }
7625 }
7626 #endif
7627
HandleA2dpDeviceOutOffload(BluetoothOffloadState a2dpOffloadFlag)7628 int32_t AudioPolicyService::HandleA2dpDeviceOutOffload(BluetoothOffloadState a2dpOffloadFlag)
7629 {
7630 #ifdef BLUETOOTH_ENABLE
7631 AUDIO_INFO_LOG("a2dpOffloadFlag_ change from %{public}d to %{public}d", a2dpOffloadFlag_, a2dpOffloadFlag);
7632 std::vector<int32_t> allSessions;
7633 GetAllRunningStreamSession(allSessions);
7634 OffloadStopPlaying(allSessions);
7635 a2dpOffloadFlag_ = a2dpOffloadFlag;
7636
7637 DeviceType dev = GetActiveOutputDevice();
7638 UpdateEffectDefaultSink(dev);
7639 AUDIO_INFO_LOG("Handle A2dpDevice Out Offload");
7640
7641 FetchStreamForA2dpOffload(true);
7642
7643 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_A2DP) {
7644 return HandleActiveDevice(DEVICE_TYPE_BLUETOOTH_A2DP);
7645 } else {
7646 return SUCCESS;
7647 }
7648 #else
7649 return ERROR;
7650 #endif
7651 }
7652
HandleA2dpDeviceInOffload(BluetoothOffloadState a2dpOffloadFlag)7653 int32_t AudioPolicyService::HandleA2dpDeviceInOffload(BluetoothOffloadState a2dpOffloadFlag)
7654 {
7655 #ifdef BLUETOOTH_ENABLE
7656 AUDIO_INFO_LOG("a2dpOffloadFlag_ change from %{public}d to %{public}d", a2dpOffloadFlag_, a2dpOffloadFlag);
7657 a2dpOffloadFlag_ = a2dpOffloadFlag;
7658 GetA2dpOffloadCodecAndSendToDsp();
7659 std::vector<int32_t> allSessions;
7660 GetAllRunningStreamSession(allSessions);
7661 OffloadStartPlaying(allSessions);
7662
7663 DeviceType dev = GetActiveOutputDevice();
7664 UpdateEffectDefaultSink(dev);
7665 AUDIO_INFO_LOG("Handle A2dpDevice In Offload");
7666 UpdateEffectBtOffloadSupported(true);
7667
7668 if (IsA2dpOffloadConnected()) {
7669 AUDIO_INFO_LOG("A2dpOffload has been connected, Fetch stream");
7670 FetchStreamForA2dpOffload(true);
7671 }
7672
7673 std::string activePort = BLUETOOTH_SPEAKER;
7674 audioPolicyManager_.SuspendAudioDevice(activePort, true);
7675 return SUCCESS;
7676 #else
7677 return ERROR;
7678 #endif
7679 }
7680
GetAllRunningStreamSession(std::vector<int32_t> & allSessions,bool doStop)7681 void AudioPolicyService::GetAllRunningStreamSession(std::vector<int32_t> &allSessions, bool doStop)
7682 {
7683 #ifdef BLUETOOTH_ENABLE
7684 vector<unique_ptr<AudioRendererChangeInfo>> rendererChangeInfos;
7685 streamCollector_.GetCurrentRendererChangeInfos(rendererChangeInfos);
7686 std::vector<int32_t> stopPlayingStream(0);
7687 for (auto &changeInfo : rendererChangeInfos) {
7688 if (changeInfo->rendererState != RENDERER_RUNNING) {
7689 if (doStop) {
7690 stopPlayingStream.push_back(changeInfo->sessionId);
7691 }
7692 continue;
7693 }
7694 allSessions.push_back(changeInfo->sessionId);
7695 }
7696 if (doStop && stopPlayingStream.size() > 0) {
7697 OffloadStopPlaying(stopPlayingStream);
7698 }
7699 #endif
7700 }
7701
UpdateAllUserSelectDevice(vector<unique_ptr<AudioDeviceDescriptor>> & userSelectDeviceMap,AudioDeviceDescriptor & desc,const sptr<AudioDeviceDescriptor> & selectDesc)7702 void AudioPolicyService::UpdateAllUserSelectDevice(vector<unique_ptr<AudioDeviceDescriptor>> &userSelectDeviceMap,
7703 AudioDeviceDescriptor &desc, const sptr<AudioDeviceDescriptor> &selectDesc)
7704 {
7705 if (userSelectDeviceMap[MEDIA_RENDER_ID]->deviceType_ == desc.deviceType_ &&
7706 userSelectDeviceMap[MEDIA_RENDER_ID]->macAddress_ == desc.macAddress_) {
7707 if (userSelectDeviceMap[MEDIA_RENDER_ID]->connectState_ != VIRTUAL_CONNECTED) {
7708 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor(selectDesc));
7709 } else {
7710 audioStateManager_.UpdatePreferredMediaRenderDeviceConnectState(desc.connectState_);
7711 }
7712 }
7713 if (userSelectDeviceMap[CALL_RENDER_ID]->deviceType_ == desc.deviceType_ &&
7714 userSelectDeviceMap[CALL_RENDER_ID]->macAddress_ == desc.macAddress_) {
7715 if (userSelectDeviceMap[CALL_RENDER_ID]->connectState_ != VIRTUAL_CONNECTED) {
7716 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor(selectDesc));
7717 } else {
7718 audioStateManager_.UpdatePreferredCallRenderDeviceConnectState(desc.connectState_);
7719 }
7720 }
7721 if (userSelectDeviceMap[CALL_CAPTURE_ID]->deviceType_ == desc.deviceType_ &&
7722 userSelectDeviceMap[CALL_CAPTURE_ID]->macAddress_ == desc.macAddress_) {
7723 if (userSelectDeviceMap[CALL_CAPTURE_ID]->connectState_ != VIRTUAL_CONNECTED) {
7724 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor(selectDesc));
7725 } else {
7726 audioStateManager_.UpdatePreferredCallCaptureDeviceConnectState(desc.connectState_);
7727 }
7728 }
7729 if (userSelectDeviceMap[RECORD_CAPTURE_ID]->deviceType_ == desc.deviceType_ &&
7730 userSelectDeviceMap[RECORD_CAPTURE_ID]->macAddress_ == desc.macAddress_) {
7731 if (userSelectDeviceMap[RECORD_CAPTURE_ID]->connectState_ != VIRTUAL_CONNECTED) {
7732 SetPreferredDevice(AUDIO_RECORD_CAPTURE, new(std::nothrow) AudioDeviceDescriptor(selectDesc));
7733 } else {
7734 audioStateManager_.UpdatePreferredRecordCaptureDeviceConnectState(desc.connectState_);
7735 }
7736 }
7737 }
7738
OnPreferredStateUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand updateCommand,AudioStreamDeviceChangeReasonExt & reason)7739 void AudioPolicyService::OnPreferredStateUpdated(AudioDeviceDescriptor &desc,
7740 const DeviceInfoUpdateCommand updateCommand, AudioStreamDeviceChangeReasonExt &reason)
7741 {
7742 AudioStateManager& stateManager = AudioStateManager::GetAudioStateManager();
7743 unique_ptr<AudioDeviceDescriptor> userSelectMediaRenderDevice = stateManager.GetPreferredMediaRenderDevice();
7744 unique_ptr<AudioDeviceDescriptor> userSelectCallRenderDevice = stateManager.GetPreferredCallRenderDevice();
7745 unique_ptr<AudioDeviceDescriptor> userSelectCallCaptureDevice = stateManager.GetPreferredCallCaptureDevice();
7746 unique_ptr<AudioDeviceDescriptor> userSelectRecordCaptureDevice = stateManager.GetPreferredRecordCaptureDevice();
7747 vector<unique_ptr<AudioDeviceDescriptor>> userSelectDeviceMap;
7748 userSelectDeviceMap.push_back(make_unique<AudioDeviceDescriptor>(*userSelectMediaRenderDevice));
7749 userSelectDeviceMap.push_back(make_unique<AudioDeviceDescriptor>(*userSelectCallRenderDevice));
7750 userSelectDeviceMap.push_back(make_unique<AudioDeviceDescriptor>(*userSelectCallCaptureDevice));
7751 userSelectDeviceMap.push_back(make_unique<AudioDeviceDescriptor>(*userSelectRecordCaptureDevice));
7752 if (updateCommand == CATEGORY_UPDATE) {
7753 if (desc.deviceCategory_ == BT_UNWEAR_HEADPHONE) {
7754 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
7755 UpdateAllUserSelectDevice(userSelectDeviceMap, desc, new(std::nothrow) AudioDeviceDescriptor());
7756 #ifdef BLUETOOTH_ENABLE
7757 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
7758 desc.macAddress_ == GetCurrentOutputDeviceMacAddr()) {
7759 Bluetooth::AudioA2dpManager::SetActiveA2dpDevice("");
7760 } else if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO &&
7761 desc.macAddress_ == GetCurrentOutputDeviceMacAddr()) {
7762 Bluetooth::AudioHfpManager::DisconnectSco();
7763 }
7764 #endif
7765 } else {
7766 reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE;
7767 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
7768 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor());
7769 SetPreferredDevice(AUDIO_RECORD_CAPTURE, new(std::nothrow) AudioDeviceDescriptor());
7770 } else {
7771 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor());
7772 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor());
7773 ClearScoDeviceSuspendState(desc.macAddress_);
7774 #ifdef BLUETOOTH_ENABLE
7775 CheckAndActiveHfpDevice(desc);
7776 #endif
7777 }
7778 }
7779 } else if (updateCommand == ENABLE_UPDATE) {
7780 UpdateAllUserSelectDevice(userSelectDeviceMap, desc, new(std::nothrow) AudioDeviceDescriptor(desc));
7781 reason = desc.isEnable_ ? AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE :
7782 AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
7783 }
7784 }
7785
7786 #ifdef BLUETOOTH_ENABLE
CheckAndActiveHfpDevice(AudioDeviceDescriptor & desc)7787 void AudioPolicyService::CheckAndActiveHfpDevice(AudioDeviceDescriptor &desc)
7788 {
7789 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
7790 AudioRendererInfo rendererInfo = {};
7791 rendererInfo.streamUsage = STREAM_USAGE_VOICE_COMMUNICATION;
7792 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList =
7793 GetPreferredOutputDeviceDescInner(rendererInfo);
7794 if (preferredDeviceList.size() > 0 &&
7795 preferredDeviceList[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
7796 Bluetooth::AudioHfpManager::SetActiveHfpDevice(preferredDeviceList[0]->macAddress_);
7797 }
7798 }
7799 }
7800 #endif
7801
OnDeviceInfoUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand command)7802 void AudioPolicyService::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command)
7803 {
7804 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
7805
7806 AUDIO_WARNING_LOG("[%{public}s] type[%{public}d] command: %{public}d category[%{public}d] " \
7807 "connectState[%{public}d] isEnable[%{public}d]", GetEncryptAddr(desc.macAddress_).c_str(),
7808 desc.deviceType_, command, desc.deviceCategory_, desc.connectState_, desc.isEnable_);
7809 DeviceUpdateClearRecongnitionStatus(desc);
7810 if (command == ENABLE_UPDATE && desc.isEnable_ == true) {
7811 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
7812 ClearScoDeviceSuspendState(desc.macAddress_);
7813 }
7814 unique_ptr<AudioDeviceDescriptor> userSelectMediaDevice =
7815 AudioStateManager::GetAudioStateManager().GetPreferredMediaRenderDevice();
7816 unique_ptr<AudioDeviceDescriptor> userSelectCallDevice =
7817 AudioStateManager::GetAudioStateManager().GetPreferredCallRenderDevice();
7818 if ((userSelectMediaDevice->deviceType_ == desc.deviceType_ &&
7819 userSelectMediaDevice->macAddress_ == desc.macAddress_ &&
7820 userSelectMediaDevice->isEnable_ == desc.isEnable_) ||
7821 (userSelectCallDevice->deviceType_ == desc.deviceType_ &&
7822 userSelectCallDevice->macAddress_ == desc.macAddress_ &&
7823 userSelectCallDevice->isEnable_ == desc.isEnable_)) {
7824 AUDIO_INFO_LOG("Current enable state has been set true during user selection, no need to be set again.");
7825 return;
7826 }
7827 } else if (command == ENABLE_UPDATE && !desc.isEnable_ && desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
7828 GetCurrentOutputDeviceMacAddr() == desc.macAddress_) {
7829 UnloadA2dpModule();
7830 }
7831 sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(desc);
7832 audioDeviceManager_.UpdateDevicesListInfo(audioDescriptor, command);
7833 CheckForA2dpSuspend(desc);
7834
7835 // VGS feature
7836 if ((desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) && (desc.connectState_ == ConnectState::CONNECTED)) {
7837 // 鎶婃槸鍚︽敮鎸乂GS淇濆瓨鍒伴煶棰戝唴閮?
7838 audioPolicyManager_.SetVgsVolumeSupported(desc.isVgsSupported_);
7839 if (desc.isVgsSupported_) {
7840 int currentVolume = GetSystemVolumeLevel(STREAM_VOICE_CALL);
7841 AUDIO_INFO_LOG("currentVolume: %{public}d", currentVolume);
7842 SetSystemVolumeLevel(STREAM_VOICE_CALL, currentVolume);
7843 }
7844 } else {
7845 audioPolicyManager_.SetVgsVolumeSupported(false);
7846 }
7847
7848 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN;
7849 OnPreferredStateUpdated(desc, command, reason);
7850 FetchDevice(true, reason);
7851 FetchDevice(false);
7852 UpdateA2dpOffloadFlagForAllStream();
7853 }
7854
DeviceUpdateClearRecongnitionStatus(AudioDeviceDescriptor & desc)7855 void AudioPolicyService::DeviceUpdateClearRecongnitionStatus(AudioDeviceDescriptor &desc)
7856 {
7857 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && (desc.deviceCategory_ == BT_UNWEAR_HEADPHONE ||
7858 desc.connectState_ == DEACTIVE_CONNECTED || desc.connectState_ == SUSPEND_CONNECTED || !desc.isEnable_)) {
7859 BluetoothScoDisconectForRecongnition();
7860 Bluetooth::AudioHfpManager::ClearRecongnitionStatus();
7861 }
7862 }
7863
CheckForA2dpSuspend(AudioDeviceDescriptor & desc)7864 void AudioPolicyService::CheckForA2dpSuspend(AudioDeviceDescriptor &desc)
7865 {
7866 if (desc.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO) {
7867 return;
7868 }
7869
7870 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
7871 CHECK_AND_RETURN_LOG(gsp != nullptr, "Service proxy unavailable");
7872
7873 std::string identity = IPCSkeleton::ResetCallingIdentity();
7874 if (audioDeviceManager_.GetScoState()) {
7875 gsp->SuspendRenderSink("a2dp");
7876 } else {
7877 gsp->RestoreRenderSink("a2dp");
7878 }
7879 IPCSkeleton::SetCallingIdentity(identity);
7880 }
7881
UpdateOffloadWhenActiveDeviceSwitchFromA2dp()7882 void AudioPolicyService::UpdateOffloadWhenActiveDeviceSwitchFromA2dp()
7883 {
7884 AUDIO_PRERELEASE_LOGI("a2dpOffloadFlag_ change from %{public}d to %{public}d", a2dpOffloadFlag_, NO_A2DP_DEVICE);
7885 std::vector<int32_t> allSessions;
7886 GetAllRunningStreamSession(allSessions);
7887 OffloadStopPlaying(allSessions);
7888 a2dpOffloadFlag_ = NO_A2DP_DEVICE;
7889 for (auto it = allSessions.begin(); it != allSessions.end(); ++it) {
7890 ResetOffloadMode(*it);
7891 }
7892 }
7893
SetCallDeviceActive(InternalDeviceType deviceType,bool active,std::string address)7894 int32_t AudioPolicyService::SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address)
7895 {
7896 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
7897
7898 AUDIO_WARNING_LOG("Device type[%{public}d] flag[%{public}d] address[%{public}s]",
7899 deviceType, active, GetEncryptAddr(address).c_str());
7900 CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
7901
7902 // Activate new device if its already connected
7903 auto isPresent = [&deviceType, &address] (const unique_ptr<AudioDeviceDescriptor> &desc) {
7904 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
7905 return ((deviceType == desc->deviceType_) && (address == desc->macAddress_));
7906 };
7907
7908 vector<unique_ptr<AudioDeviceDescriptor>> callDevices = GetAvailableDevicesInner(CALL_OUTPUT_DEVICES);
7909
7910 auto itr = std::find_if(callDevices.begin(), callDevices.end(), isPresent);
7911 CHECK_AND_RETURN_RET_LOG(itr != callDevices.end(), ERR_OPERATION_FAILED,
7912 "Requested device not available %{public}d ", deviceType);
7913 if (active) {
7914 if (deviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
7915 (*itr)->isEnable_ = true;
7916 audioDeviceManager_.UpdateDevicesListInfo(new(std::nothrow) AudioDeviceDescriptor(**itr), ENABLE_UPDATE);
7917 ClearScoDeviceSuspendState(address);
7918 }
7919 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor(**itr));
7920 #ifdef BLUETOOTH_ENABLE
7921 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_SCO &&
7922 deviceType != DEVICE_TYPE_BLUETOOTH_SCO) {
7923 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO,
7924 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT);
7925 Bluetooth::AudioHfpManager::DisconnectSco();
7926 }
7927 if (GetCurrentOutputDeviceType() != DEVICE_TYPE_BLUETOOTH_SCO &&
7928 deviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
7929 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO,
7930 (*itr)->macAddress_, USER_SELECT_BT);
7931 }
7932 #endif
7933 } else {
7934 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor());
7935 #ifdef BLUETOOTH_ENABLE
7936 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_SCO &&
7937 deviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
7938 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO,
7939 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT);
7940 Bluetooth::AudioHfpManager::DisconnectSco();
7941 }
7942 #endif
7943 }
7944 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
7945 return SUCCESS;
7946 }
7947
GetActiveBluetoothDevice()7948 std::unique_ptr<AudioDeviceDescriptor> AudioPolicyService::GetActiveBluetoothDevice()
7949 {
7950 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
7951
7952 unique_ptr<AudioDeviceDescriptor> preferredDesc = audioStateManager_.GetPreferredCallRenderDevice();
7953 if (preferredDesc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
7954 return preferredDesc;
7955 }
7956
7957 std::vector<unique_ptr<AudioDeviceDescriptor>> audioPrivacyDeviceDescriptors =
7958 audioDeviceManager_.GetCommRenderPrivacyDevices();
7959 std::vector<unique_ptr<AudioDeviceDescriptor>> activeDeviceDescriptors;
7960
7961 for (auto &desc : audioPrivacyDeviceDescriptors) {
7962 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && desc->isEnable_) {
7963 activeDeviceDescriptors.push_back(make_unique<AudioDeviceDescriptor>(*desc));
7964 }
7965 }
7966
7967 uint32_t btDeviceSize = activeDeviceDescriptors.size();
7968 if (btDeviceSize == 0) {
7969 activeDeviceDescriptors = audioDeviceManager_.GetCommRenderBTCarDevices();
7970 }
7971 btDeviceSize = activeDeviceDescriptors.size();
7972 if (btDeviceSize == 0) {
7973 return make_unique<AudioDeviceDescriptor>();
7974 } else if (btDeviceSize == 1) {
7975 unique_ptr<AudioDeviceDescriptor> res = std::move(activeDeviceDescriptors[0]);
7976 return res;
7977 }
7978
7979 uint32_t index = 0;
7980 for (uint32_t i = 1; i < btDeviceSize; ++i) {
7981 if (activeDeviceDescriptors[i]->connectTimeStamp_ >
7982 activeDeviceDescriptors[index]->connectTimeStamp_) {
7983 index = i;
7984 }
7985 }
7986 unique_ptr<AudioDeviceDescriptor> res = std::move(activeDeviceDescriptors[index]);
7987 return res;
7988 }
7989
GetConverterConfig()7990 ConverterConfig AudioPolicyService::GetConverterConfig()
7991 {
7992 AudioConverterParser &converterParser = AudioConverterParser::GetInstance();
7993 return converterParser.LoadConfig();
7994 }
7995
ClearScoDeviceSuspendState(string macAddress)7996 void AudioPolicyService::ClearScoDeviceSuspendState(string macAddress)
7997 {
7998 AUDIO_DEBUG_LOG("Clear sco suspend state %{public}s", GetEncryptAddr(macAddress).c_str());
7999 vector<shared_ptr<AudioDeviceDescriptor>> descs = audioDeviceManager_.GetDevicesByFilter(
8000 DEVICE_TYPE_BLUETOOTH_SCO, DEVICE_ROLE_NONE, macAddress, "", SUSPEND_CONNECTED);
8001 for (auto &desc : descs) {
8002 desc->connectState_ = DEACTIVE_CONNECTED;
8003 }
8004 }
8005
GetMaxAmplitude(const int32_t deviceId)8006 float AudioPolicyService::GetMaxAmplitude(const int32_t deviceId)
8007 {
8008 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
8009 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, 0, "Service proxy unavailable");
8010
8011 if (deviceId == GetCurrentOutputDevice().deviceId_) {
8012 std::string identity = IPCSkeleton::ResetCallingIdentity();
8013 float outputMaxAmplitude = gsp->GetMaxAmplitude(true, GetCurrentOutputDeviceType());
8014 IPCSkeleton::SetCallingIdentity(identity);
8015 return outputMaxAmplitude;
8016 }
8017
8018 if (deviceId == GetCurrentInputDevice().deviceId_) {
8019 std::string identity = IPCSkeleton::ResetCallingIdentity();
8020 float inputMaxAmplitude = gsp->GetMaxAmplitude(false, GetCurrentInputDeviceType());
8021 IPCSkeleton::SetCallingIdentity(identity);
8022 return inputMaxAmplitude;
8023 }
8024
8025 return 0;
8026 }
8027
OpenPortAndInsertIOHandle(const std::string & moduleName,const AudioModuleInfo & moduleInfo)8028 int32_t AudioPolicyService::OpenPortAndInsertIOHandle(const std::string &moduleName,
8029 const AudioModuleInfo &moduleInfo)
8030 {
8031 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
8032 CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_INVALID_HANDLE, "OpenAudioPort failed %{public}d",
8033 ioHandle);
8034
8035 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
8036 IOHandles_[moduleName] = ioHandle;
8037
8038 return SUCCESS;
8039 }
8040
ClosePortAndEraseIOHandle(const std::string & moduleName)8041 int32_t AudioPolicyService::ClosePortAndEraseIOHandle(const std::string &moduleName)
8042 {
8043 AudioIOHandle ioHandle;
8044 {
8045 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
8046 auto ioHandleIter = IOHandles_.find(moduleName);
8047 CHECK_AND_RETURN_RET_LOG(ioHandleIter != IOHandles_.end(), ERROR,
8048 "can not find %{public}s in io map", moduleName.c_str());
8049 ioHandle = ioHandleIter->second;
8050 IOHandles_.erase(moduleName);
8051 }
8052 AUDIO_INFO_LOG("[close-module] %{public}s,id:%{public}d", moduleName.c_str(), ioHandle);
8053 int32_t result = audioPolicyManager_.CloseAudioPort(ioHandle);
8054 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "CloseAudioPort failed %{public}d", result);
8055 return SUCCESS;
8056 }
8057
GetDeviceUsage(const AudioDeviceDescriptor & desc)8058 DeviceUsage AudioPolicyService::GetDeviceUsage(const AudioDeviceDescriptor &desc)
8059 {
8060 return audioDeviceManager_.GetDeviceUsage(desc);
8061 }
8062
HandleRemoteCastDevice(bool isConnected,AudioStreamInfo streamInfo)8063 void AudioPolicyService::HandleRemoteCastDevice(bool isConnected, AudioStreamInfo streamInfo)
8064 {
8065 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
8066
8067 AudioDeviceDescriptor updatedDesc = AudioDeviceDescriptor(DEVICE_TYPE_REMOTE_CAST,
8068 GetDeviceRole(DEVICE_TYPE_REMOTE_CAST));
8069 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {};
8070 auto isPresent = [&updatedDesc] (const sptr<AudioDeviceDescriptor> &descriptor) {
8071 return descriptor->deviceType_ == updatedDesc.deviceType_ &&
8072 descriptor->macAddress_ == updatedDesc.macAddress_ &&
8073 descriptor->networkId_ == updatedDesc.networkId_;
8074 };
8075 if (isConnected) {
8076 // If device already in list, remove it else do not modify the list
8077 connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent),
8078 connectedDevices_.end());
8079 UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb);
8080 LoadInnerCapturerSink(REMOTE_CAST_INNER_CAPTURER_SINK_NAME, streamInfo);
8081 audioPolicyManager_.ResetRemoteCastDeviceVolume();
8082 } else {
8083 UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb);
8084 FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::OLD_DEVICE_UNAVALIABLE_EXT);
8085 UnloadInnerCapturerSink(REMOTE_CAST_INNER_CAPTURER_SINK_NAME);
8086 }
8087 FetchDevice(true);
8088 FetchDevice(false);
8089
8090 // update a2dp offload
8091 UpdateA2dpOffloadFlagForAllStream();
8092 }
8093
TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)8094 int32_t AudioPolicyService::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)
8095 {
8096 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
8097 FetchDevice(true, reason);
8098 FetchDevice(false, reason);
8099
8100 // update a2dp offload
8101 UpdateA2dpOffloadFlagForAllStream();
8102 return SUCCESS;
8103 }
8104
SetDeviceSafeVolumeStatus()8105 void AudioPolicyService::SetDeviceSafeVolumeStatus()
8106 {
8107 if (!userSelect_) {
8108 return;
8109 }
8110
8111 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType();
8112 switch (curOutputDeviceType) {
8113 case DEVICE_TYPE_BLUETOOTH_A2DP:
8114 case DEVICE_TYPE_BLUETOOTH_SCO:
8115 safeStatusBt_ = SAFE_INACTIVE;
8116 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_);
8117 CreateCheckMusicActiveThread();
8118 break;
8119 case DEVICE_TYPE_WIRED_HEADSET:
8120 case DEVICE_TYPE_WIRED_HEADPHONES:
8121 case DEVICE_TYPE_USB_HEADSET:
8122 case DEVICE_TYPE_USB_ARM_HEADSET:
8123 case DEVICE_TYPE_DP:
8124 safeStatus_ = SAFE_INACTIVE;
8125 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_);
8126 CreateCheckMusicActiveThread();
8127 break;
8128 default:
8129 AUDIO_INFO_LOG("safeVolume unsupported device:%{public}d", curOutputDeviceType);
8130 break;
8131 }
8132 }
8133
DisableSafeMediaVolume()8134 int32_t AudioPolicyService::DisableSafeMediaVolume()
8135 {
8136 AUDIO_INFO_LOG("Enter");
8137 std::lock_guard<std::mutex> lock(dialogMutex_);
8138 userSelect_ = true;
8139 isDialogSelectDestroy_.store(true);
8140 dialogSelectCondition_.notify_all();
8141 SetDeviceSafeVolumeStatus();
8142 return SUCCESS;
8143 }
8144
SafeVolumeDialogDisapper()8145 int32_t AudioPolicyService::SafeVolumeDialogDisapper()
8146 {
8147 AUDIO_INFO_LOG("Enter");
8148 std::lock_guard<std::mutex> lock(dialogMutex_);
8149 isSafeVolumeDialogShowing_.store(false);
8150 dialogSelectCondition_.notify_all();
8151 SetDeviceSafeVolumeStatus();
8152 return SUCCESS;
8153 }
8154
GetSafeVolumeDump(std::string & dumpString)8155 void AudioPolicyService::GetSafeVolumeDump(std::string &dumpString)
8156 {
8157 audioPolicyManager_.SafeVolumeDump(dumpString);
8158 }
8159
DevicesInfoDump(std::string & dumpString)8160 void AudioPolicyService::DevicesInfoDump(std::string &dumpString)
8161 {
8162 std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors;
8163
8164 dumpString += "\nInput local Devices:\n";
8165 audioDeviceDescriptors = GetDumpDeviceInfo(dumpString, INPUT_DEVICES_FLAG);
8166 AppendFormat(dumpString, "- %zu Input Devices (s) available\n", audioDeviceDescriptors.size());
8167
8168 dumpString += "\nOutput local Devices:\n";
8169 audioDeviceDescriptors = GetDumpDeviceInfo(dumpString, OUTPUT_DEVICES_FLAG);
8170 AppendFormat(dumpString, "- %zu output Devices (s) available\n", audioDeviceDescriptors.size());
8171
8172 dumpString += "\nInput distributed Devices:\n";
8173 audioDeviceDescriptors = GetDumpDeviceInfo(dumpString, DISTRIBUTED_INPUT_DEVICES_FLAG);
8174 AppendFormat(dumpString, "- %zu output Devices (s) available\n", audioDeviceDescriptors.size());
8175
8176 dumpString += "\nOutput distributed Devices:\n";
8177 audioDeviceDescriptors = GetDumpDeviceInfo(dumpString, DISTRIBUTED_OUTPUT_DEVICES_FLAG);
8178 AppendFormat(dumpString, "- %zu output Devices (s) available\n", audioDeviceDescriptors.size());
8179
8180 priorityOutputDevice_ = GetActiveOutputDevice();
8181 priorityInputDevice_ = GetActiveInputDevice();
8182 AppendFormat(dumpString, "\nHighest priority output device: %s",
8183 AudioInfoDumpUtils::GetDeviceTypeName(priorityOutputDevice_).c_str());
8184 AppendFormat(dumpString, "\nHighest priority input device: %s \n",
8185 AudioInfoDumpUtils::GetDeviceTypeName(priorityInputDevice_).c_str());
8186
8187 GetMicrophoneDescriptorsDump(dumpString);
8188 GetOffloadStatusDump(dumpString);
8189 }
8190
GetDumpDeviceInfo(std::string & dumpString,DeviceFlag deviceFlag)8191 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDumpDeviceInfo(std::string &dumpString,
8192 DeviceFlag deviceFlag)
8193 {
8194 std::vector<sptr<AudioDeviceDescriptor>> deviceDescs = GetDumpDevices(deviceFlag);
8195
8196 for (auto &desc : deviceDescs) {
8197 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc);
8198 dumpString += "\n";
8199 AppendFormat(dumpString, " - device name:%s\n",
8200 AudioInfoDumpUtils::GetDeviceTypeName(devDesc->deviceType_).c_str());
8201 AppendFormat(dumpString, " - device type:%d\n", devDesc->deviceType_);
8202 AppendFormat(dumpString, " - device id:%d\n", devDesc->deviceId_);
8203 AppendFormat(dumpString, " - device role:%d\n", devDesc->deviceRole_);
8204 AppendFormat(dumpString, " - device name:%s\n", devDesc->deviceName_.c_str());
8205 AppendFormat(dumpString, " - device mac:%s\n", GetEncryptAddr(devDesc->macAddress_).c_str());
8206 AppendFormat(dumpString, " - device network:%s\n", devDesc->networkId_.c_str());
8207 if (deviceFlag == DeviceFlag::INPUT_DEVICES_FLAG || deviceFlag == DeviceFlag::OUTPUT_DEVICES_FLAG) {
8208 conneceType_ = CONNECT_TYPE_LOCAL;
8209 } else if (deviceFlag == DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG ||
8210 deviceFlag == DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG) {
8211 conneceType_ = CONNECT_TYPE_DISTRIBUTED;
8212 }
8213 AppendFormat(dumpString, " - connect type:%s\n", AudioInfoDumpUtils::GetConnectTypeName(conneceType_).c_str());
8214 for (auto &samplingRate : devDesc->audioStreamInfo_.samplingRate) {
8215 AppendFormat(dumpString, " - device sampleRates:%d\n", samplingRate);
8216 }
8217 for (auto &channel : devDesc->audioStreamInfo_.channels) {
8218 AppendFormat(dumpString, " - device channels:%d\n", channel);
8219 }
8220 AppendFormat(dumpString, " - device format:%d\n", devDesc->audioStreamInfo_.format);
8221 }
8222 return deviceDescs;
8223 }
8224
GetDumpDevices(DeviceFlag deviceFlag)8225 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDumpDevices(DeviceFlag deviceFlag)
8226 {
8227 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
8228 switch (deviceFlag) {
8229 case NONE_DEVICES_FLAG:
8230 case DISTRIBUTED_OUTPUT_DEVICES_FLAG:
8231 case DISTRIBUTED_INPUT_DEVICES_FLAG:
8232 case ALL_DISTRIBUTED_DEVICES_FLAG:
8233 case ALL_L_D_DEVICES_FLAG:
8234 if (!hasSystemPermission) {
8235 AUDIO_ERR_LOG("GetDevices: No system permission");
8236 std::vector<sptr<AudioDeviceDescriptor>> info = {};
8237 return info;
8238 }
8239 break;
8240 default:
8241 break;
8242 }
8243
8244 std::vector<sptr<AudioDeviceDescriptor>> deviceDescs = GetDevices(deviceFlag);
8245
8246 if (!hasSystemPermission) {
8247 for (sptr<AudioDeviceDescriptor> desc : deviceDescs) {
8248 desc->networkId_ = "";
8249 desc->interruptGroupId_ = GROUP_ID_NONE;
8250 desc->volumeGroupId_ = GROUP_ID_NONE;
8251 }
8252 }
8253 return deviceDescs;
8254 }
8255
AudioModeDump(std::string & dumpString)8256 void AudioPolicyService::AudioModeDump(std::string &dumpString)
8257 {
8258 GetCallStatusDump(dumpString);
8259 GetRingerModeDump(dumpString);
8260 }
8261
GetCallStatusDump(std::string & dumpString)8262 void AudioPolicyService::GetCallStatusDump(std::string &dumpString)
8263 {
8264 dumpString += "\nAudio Scene:";
8265 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
8266 AudioScene callStatus = GetAudioScene(hasSystemPermission);
8267 switch (callStatus) {
8268 case AUDIO_SCENE_DEFAULT:
8269 dumpString += "DEFAULT";
8270 break;
8271 case AUDIO_SCENE_RINGING:
8272 dumpString += "RINGING";
8273 break;
8274 case AUDIO_SCENE_PHONE_CALL:
8275 dumpString += "PHONE_CALL";
8276 break;
8277 case AUDIO_SCENE_PHONE_CHAT:
8278 dumpString += "PHONE_CHAT";
8279 break;
8280 default:
8281 dumpString += "UNKNOWN";
8282 }
8283 dumpString += "\n";
8284 }
8285
GetRingerModeDump(std::string & dumpString)8286 void AudioPolicyService::GetRingerModeDump(std::string &dumpString)
8287 {
8288 dumpString += "Ringer Mode:";
8289 AudioRingerMode ringerMode = GetRingerMode();
8290 switch (ringerMode) {
8291 case RINGER_MODE_NORMAL:
8292 dumpString += "NORMAL";
8293 break;
8294 case RINGER_MODE_SILENT:
8295 dumpString += "SILENT";
8296 break;
8297 case RINGER_MODE_VIBRATE:
8298 dumpString += "VIBRATE";
8299 break;
8300 default:
8301 dumpString += "UNKNOWN";
8302 }
8303 dumpString += "\n\n";
8304 }
8305
GetMicrophoneDescriptorsDump(std::string & dumpString)8306 void AudioPolicyService::GetMicrophoneDescriptorsDump(std::string &dumpString)
8307 {
8308 dumpString += "\nAvailable MicrophoneDescriptors:\n";
8309
8310 std::vector<sptr<MicrophoneDescriptor>> micDescs = GetAvailableMicrophones();
8311 for (auto it = micDescs.begin();
8312 it != micDescs.end(); ++it) {
8313 AppendFormat(dumpString, " - id:%d \n", (*it)->micId_);
8314 AppendFormat(dumpString, " - device type:%d \n", (*it)->deviceType_);
8315 AppendFormat(dumpString, " - group id:%d \n", (*it)->groupId_);
8316 AppendFormat(dumpString, " - sensitivity:%d \n", (*it)->sensitivity_);
8317 AppendFormat(dumpString, " - position:%f %f %f (x, y, z)\n",
8318 (*it)->position_.x, (*it)->position_.y, (*it)->position_.z);
8319 AppendFormat(dumpString, " - orientation:%f %f %f (x, y, z)\n",
8320 (*it)->orientation_.x, (*it)->orientation_.y, (*it)->orientation_.z);
8321 }
8322 }
8323
AudioPolicyParserDump(std::string & dumpString)8324 void AudioPolicyService::AudioPolicyParserDump(std::string &dumpString)
8325 {
8326 dumpString += "\nAudioPolicyParser:\n";
8327 GetAudioAdapterInfos(adapterInfoMap_);
8328 GetVolumeGroupData(volumeGroupData_);
8329 GetInterruptGroupData(interruptGroupData_);
8330 GetGlobalConfigs(globalConfigs_);
8331 for (auto &[adapterType, adapterInfo] : adapterInfoMap_) {
8332 AppendFormat(dumpString, " - adapter : %s -- adapterType:%u\n", adapterInfo.adapterName_.c_str(), adapterType);
8333 for (auto &deviceInfo : adapterInfo.deviceInfos_) {
8334 AppendFormat(dumpString, " - device -- name:%s, pin:%s, type:%s, role:%s\n", deviceInfo.name_.c_str(),
8335 deviceInfo.pin_.c_str(), deviceInfo.type_.c_str(), deviceInfo.role_.c_str());
8336 }
8337 for (auto &pipeInfo : adapterInfo.pipeInfos_) {
8338 AppendFormat(dumpString, " - module : -- name:%s, pipeRole:%s, pipeFlags:%s, lib:%s, paPropRole:%s, "
8339 "fixedLatency:%s, renderInIdleState:%s\n", pipeInfo.name_.c_str(),
8340 pipeInfo.pipeRole_.c_str(), pipeInfo.pipeFlags_.c_str(), pipeInfo.lib_.c_str(),
8341 pipeInfo.paPropRole_.c_str(), pipeInfo.fixedLatency_.c_str(), pipeInfo.renderInIdleState_.c_str());
8342
8343 for (auto &configInfo : pipeInfo.configInfos_) {
8344 AppendFormat(dumpString, " - config : -- name:%s, value:%s\n", configInfo.name_.c_str(),
8345 configInfo.value_.c_str());
8346 }
8347 }
8348 }
8349 for (auto& volume : volumeGroupData_) {
8350 AppendFormat(dumpString, " - volumeGroupMap_ first:%s, second:%s\n\n", volume.first.c_str(),
8351 volume.second.c_str());
8352 }
8353 for (auto& interrupt : interruptGroupData_) {
8354 AppendFormat(dumpString, " - interruptGroupMap_ first:%s, second:%s\n", interrupt.first.c_str(),
8355 interrupt.second.c_str());
8356 }
8357 AppendFormat(dumpString, " - globalConfig adapter:%s, pipe:%s, device:%s, updateRouteSupport:%d, "
8358 "audioLatency:%s, sinkLatency:%s\n", globalConfigs_.adapter_.c_str(),
8359 globalConfigs_.pipe_.c_str(), globalConfigs_.device_.c_str(),
8360 globalConfigs_.updateRouteSupport_,
8361 globalConfigs_.globalPaConfigs_.audioLatency_.c_str(),
8362 globalConfigs_.globalPaConfigs_.sinkLatency_.c_str());
8363 for (auto &outputConfig : globalConfigs_.outputConfigInfos_) {
8364 AppendFormat(dumpString, " - output config name:%s, type:%s, value:%s\n", outputConfig.name_.c_str(),
8365 outputConfig.type_.c_str(), outputConfig.value_.c_str());
8366 }
8367 for (auto &inputConfig : globalConfigs_.inputConfigInfos_) {
8368 AppendFormat(dumpString, " - input config name:%s, type_%s, value:%s\n\n", inputConfig.name_.c_str(),
8369 inputConfig.type_.c_str(), inputConfig.value_.c_str());
8370 }
8371 AppendFormat(dumpString, " - module curActiveCount:%d\n\n", GetCurActivateCount());
8372 }
8373
XmlParsedDataMapDump(std::string & dumpString)8374 void AudioPolicyService::XmlParsedDataMapDump(std::string &dumpString)
8375 {
8376 dumpString += "\nXmlParsedDataParser:\n";
8377
8378 GetDeviceClassInfo(deviceClassInfo_);
8379
8380 for (auto &[adapterType, deviceClassInfos] : deviceClassInfo_) {
8381 AppendFormat(dumpString, " - DeviceClassInfo type %d\n", adapterType);
8382 for (auto &deviceClassInfo : deviceClassInfos) {
8383 AppendFormat(dumpString, " - Data : className:%s, name:%s, adapter:%s, id:%s, lib:%s, role:%s, rate:%s\n",
8384 deviceClassInfo.className.c_str(), deviceClassInfo.name.c_str(),
8385 deviceClassInfo.adapterName.c_str(), deviceClassInfo.id.c_str(),
8386 deviceClassInfo.lib.c_str(), deviceClassInfo.role.c_str(), deviceClassInfo.rate.c_str());
8387
8388 for (auto rate : deviceClassInfo.supportedRate_) {
8389 AppendFormat(dumpString, " - rate:%u\n", rate);
8390 }
8391
8392 for (auto supportedChannel : deviceClassInfo.supportedChannels_) {
8393 AppendFormat(dumpString, " - supportedChannel:%u\n", supportedChannel);
8394 }
8395
8396 AppendFormat(dumpString, " -DeviceClassInfo : format:%s, channels:%s, bufferSize:%s, fixedLatency:%s, "
8397 " sinkLatency:%s, renderInIdleState:%s, OpenMicSpeaker:%s, fileName:%s, networkId:%s, "
8398 "deviceType:%s, sceneName:%s, sourceType:%s, offloadEnable:%s\n",
8399 deviceClassInfo.format.c_str(), deviceClassInfo.channels.c_str(), deviceClassInfo.bufferSize.c_str(),
8400 deviceClassInfo.fixedLatency.c_str(), deviceClassInfo.sinkLatency.c_str(),
8401 deviceClassInfo.renderInIdleState.c_str(), deviceClassInfo.OpenMicSpeaker.c_str(),
8402 deviceClassInfo.fileName.c_str(), deviceClassInfo.networkId.c_str(), deviceClassInfo.deviceType.c_str(),
8403 deviceClassInfo.sceneName.c_str(), deviceClassInfo.sourceType.c_str(),
8404 deviceClassInfo.offloadEnable.c_str());
8405 }
8406 AppendFormat(dumpString, "-----EndOfXmlParsedDataMap-----\n");
8407 }
8408 }
8409
StreamEffectSceneInfoDump(string & dumpString,const ProcessNew & processNew,const string processType)8410 static void StreamEffectSceneInfoDump(string &dumpString, const ProcessNew &processNew, const string processType)
8411 {
8412 int32_t count;
8413 AppendFormat(dumpString, "- %zu %s supported :\n", processNew.stream.size(), processType.c_str());
8414
8415 for (Stream x : processNew.stream) {
8416 AppendFormat(dumpString, " %s stream scene = %s \n", processType.c_str(), x.scene.c_str());
8417 count = 0;
8418 for (StreamEffectMode mode : x.streamEffectMode) {
8419 count++;
8420 AppendFormat(dumpString, " - modeName%d = %s \n", count, mode.mode.c_str());
8421 int32_t n = 0;
8422 for (Device deviceInfo : mode.devicePort) {
8423 n++;
8424 AppendFormat(dumpString, " - device%d type = %s \n", n, deviceInfo.type.c_str());
8425 AppendFormat(dumpString, " - device%d chain = %s \n", n, deviceInfo.chain.c_str());
8426 }
8427 }
8428 dumpString += "\n";
8429 }
8430 }
8431
EffectManagerInfoDump(string & dumpString)8432 void AudioPolicyService::EffectManagerInfoDump(string &dumpString)
8433 {
8434 int32_t count = 0;
8435 GetEffectManagerInfo();
8436 GetAudioAdapterInfos(adapterInfoMap_);
8437
8438 dumpString += "==== Audio Effect Manager INFO ====\n";
8439
8440 // effectChain info
8441 count = 0;
8442 AppendFormat(dumpString, "- system support %d effectChain(s):\n",
8443 supportedEffectConfig_.effectChains.size());
8444 for (EffectChain x : supportedEffectConfig_.effectChains) {
8445 count++;
8446 AppendFormat(dumpString, " effectChain%d :\n", count);
8447 AppendFormat(dumpString, " - effectChain name = %s \n", x.name.c_str());
8448 int32_t countEffect = 0;
8449 for (string effectUnit : x.apply) {
8450 countEffect++;
8451 AppendFormat(dumpString, " - effectUnit%d = %s \n", countEffect, effectUnit.c_str());
8452 }
8453 dumpString += "\n";
8454 }
8455
8456 // converter info
8457 AppendFormat(dumpString, "- system support audio converter for special streams:\n");
8458 AppendFormat(dumpString, " - converter name: %s\n", converterConfig_.library.name.c_str());
8459 AppendFormat(dumpString, " - converter out channel layout: %" PRId64 "\n",
8460 converterConfig_.outChannelLayout);
8461 dumpString += "\n";
8462
8463 // preProcess info
8464 StreamEffectSceneInfoDump(dumpString, supportedEffectConfig_.preProcessNew, "preProcess");
8465 dumpString += "\n";
8466 // postProcess info
8467 StreamEffectSceneInfoDump(dumpString, supportedEffectConfig_.postProcessNew, "postProcess");
8468
8469 // postProcess scene maping
8470 AppendFormat(dumpString, "- postProcess scene maping config:\n");
8471 for (SceneMappingItem it: supportedEffectConfig_.postProcessSceneMap) {
8472 AppendFormat(dumpString, " - streamUsage: %s = %s \n", it.name.c_str(), it.sceneType.c_str());
8473 }
8474 dumpString += "\n";
8475 }
8476
MicrophoneMuteInfoDump(string & dumpString)8477 void AudioPolicyService::MicrophoneMuteInfoDump(string &dumpString)
8478 {
8479 dumpString += "==== Microphone Mute INFO ====\n";
8480 // non-persistent microphone mute info
8481 AppendFormat(dumpString, " - non-persistent microphone isMuted: %d \n", isMicrophoneMuteTemporary_);
8482 // persistent microphone mute info
8483 AppendFormat(dumpString, " - persistent microphone isMuted: %d \n", isMicrophoneMutePersistent_);
8484 dumpString += "\n";
8485 }
8486
GetGroupInfoDump(std::string & dumpString)8487 void AudioPolicyService::GetGroupInfoDump(std::string &dumpString)
8488 {
8489 dumpString += "\nVolume GroupInfo:\n";
8490 // Get group info
8491 std::vector<sptr<VolumeGroupInfo>> groupInfos = GetVolumeGroupInfos();
8492 AppendFormat(dumpString, "- %zu Group Infos (s) available :\n", groupInfos.size());
8493
8494 for (auto it = groupInfos.begin(); it != groupInfos.end(); it++) {
8495 AppendFormat(dumpString, " Group Infos %d\n", it - groupInfos.begin() + 1);
8496 AppendFormat(dumpString, " - ConnectType(0 for Local, 1 for Remote): %d\n", (*it)->connectType_);
8497 AppendFormat(dumpString, " - Name: %s\n", (*it)->groupName_.c_str());
8498 AppendFormat(dumpString, " - Id: %d\n", (*it)->volumeGroupId_);
8499 }
8500 dumpString += "\n";
8501 }
8502
StreamVolumesDump(std::string & dumpString)8503 void AudioPolicyService::StreamVolumesDump(std::string &dumpString)
8504 {
8505 dumpString += "\nStream Volumes:\n";
8506 // Get stream volumes
8507 std::map<AudioStreamType, int32_t> streamVolumes_;
8508 for (int stream = AudioStreamType::STREAM_VOICE_CALL; stream <= AudioStreamType::STREAM_TYPE_MAX; stream++) {
8509 AudioStreamType streamType = (AudioStreamType)stream;
8510
8511 if (IsStreamSupported(streamType)) {
8512 if (streamType == STREAM_ALL) {
8513 streamType = STREAM_MUSIC;
8514 AUDIO_DEBUG_LOG("GetVolume of STREAM_ALL for streamType = %{public}d ", streamType);
8515 }
8516 int32_t volume = GetSystemVolumeLevel(streamType);
8517 streamVolumes_.insert({ streamType, volume });
8518 }
8519 }
8520 AppendFormat(dumpString, " [StreamName]: [Volume]\n");
8521 for (auto it = streamVolumes_.cbegin(); it != streamVolumes_.cend();
8522 ++it) {
8523 AppendFormat(dumpString, " - %s: %d\n", AudioInfoDumpUtils::GetStreamName(it->first).c_str(), it->second);
8524 }
8525 GetVolumeConfigDump(dumpString);
8526 GetGroupInfoDump(dumpString);
8527 GetSafeVolumeDump(dumpString);
8528 }
8529
IsStreamSupported(AudioStreamType streamType)8530 bool AudioPolicyService::IsStreamSupported(AudioStreamType streamType)
8531 {
8532 switch (streamType) {
8533 case STREAM_MUSIC:
8534 case STREAM_RING:
8535 case STREAM_VOICE_CALL:
8536 case STREAM_VOICE_COMMUNICATION:
8537 case STREAM_VOICE_ASSISTANT:
8538 case STREAM_WAKEUP:
8539 case STREAM_CAMCORDER:
8540 return true;
8541 default:
8542 return false;
8543 }
8544 }
8545
GetVolumeConfigDump(std::string & dumpString)8546 void AudioPolicyService::GetVolumeConfigDump(std::string &dumpString)
8547 {
8548 dumpString += "\nVolume config of streams:\n";
8549
8550 StreamVolumeInfoMap streamVolumeInfos;
8551 GetStreamVolumeInfoMap(streamVolumeInfos);
8552 for (auto it = streamVolumeInfos.cbegin();
8553 it != streamVolumeInfos.cend(); ++it) {
8554 auto streamType = it->first;
8555 AppendFormat(dumpString, " %s: ", AudioInfoDumpUtils::GetStreamName(streamType).c_str());
8556 if (streamType == STREAM_ALL) {
8557 streamType = STREAM_MUSIC;
8558 AUDIO_INFO_LOG("GetStreamMute of STREAM_ALL for streamType = %{public}d ", streamType);
8559 }
8560 AppendFormat(dumpString, "mute = %d ", GetStreamMute(streamType));
8561 auto streamVolumeInfo = it->second;
8562 AppendFormat(dumpString, "minLevel = %d ", streamVolumeInfo->minLevel);
8563 AppendFormat(dumpString, "maxLevel = %d ", streamVolumeInfo->maxLevel);
8564 AppendFormat(dumpString, "defaultLevel = %d\n", streamVolumeInfo->defaultLevel);
8565 DeviceVolumeInfosDump(dumpString, streamVolumeInfo->deviceVolumeInfos);
8566 }
8567 }
8568
DeviceVolumeInfosDump(std::string & dumpString,DeviceVolumeInfoMap & deviceVolumeInfos)8569 void AudioPolicyService::DeviceVolumeInfosDump(std::string &dumpString, DeviceVolumeInfoMap &deviceVolumeInfos)
8570 {
8571 for (auto iter = deviceVolumeInfos.cbegin(); iter != deviceVolumeInfos.cend(); ++iter) {
8572 AppendFormat(dumpString, " %s : {", AudioInfoDumpUtils::GetDeviceVolumeTypeName(iter->first).c_str());
8573 auto volumePoints = iter->second->volumePoints;
8574 for (auto volPoint = volumePoints.cbegin(); volPoint != volumePoints.cend(); ++volPoint) {
8575 AppendFormat(dumpString, "[%u, %d]", volPoint->index, volPoint->dbValue);
8576 if (volPoint + 1 != volumePoints.cend()) {
8577 dumpString += ", ";
8578 }
8579 }
8580 dumpString += "}\n";
8581 }
8582 }
8583
AudioStreamDump(std::string & dumpString)8584 void AudioPolicyService::AudioStreamDump(std::string &dumpString)
8585 {
8586 dumpString += "\nAudioRenderer stream:\n";
8587 vector<unique_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos;
8588 streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
8589
8590 AppendFormat(dumpString, " - audiorenderer stream size : %zu\n", audioRendererChangeInfos.size());
8591 for (auto it = audioRendererChangeInfos.begin(); it != audioRendererChangeInfos.end(); it++) {
8592 if ((*it)->rendererInfo.rendererFlags == STREAM_FLAG_NORMAL) {
8593 AppendFormat(dumpString, " - normal audiorenderer stream:\n");
8594 } else if ((*it)->rendererInfo.rendererFlags == STREAM_FLAG_FAST) {
8595 AppendFormat(dumpString, " - fast audiorenderer stream:\n");
8596 }
8597 AppendFormat(dumpString, " - clientUID : %d\n", (*it)->clientUID);
8598 AppendFormat(dumpString, " - streamId : %d\n", (*it)->sessionId);
8599 AppendFormat(dumpString, " - deviceType : %d\n", (*it)->outputDeviceInfo.deviceType_);
8600 AppendFormat(dumpString, " - contentType : %d\n", (*it)->rendererInfo.contentType);
8601 AppendFormat(dumpString, " - streamUsage : %d\n", (*it)->rendererInfo.streamUsage);
8602 AppendFormat(dumpString, " - samplingRate : %d\n", (*it)->rendererInfo.samplingRate);
8603 AudioStreamType streamType = GetStreamType((*it)->sessionId);
8604 AppendFormat(dumpString, " - volume : %f\n", GetSystemVolumeDb(streamType));
8605 AppendFormat(dumpString, " - pipeType : %d\n", (*it)->rendererInfo.pipeType);
8606 }
8607 GetCapturerStreamDump(dumpString);
8608 }
8609
GetCapturerStreamDump(std::string & dumpString)8610 void AudioPolicyService::GetCapturerStreamDump(std::string &dumpString)
8611 {
8612 dumpString += "\nAudioCapturer stream:\n";
8613 vector<unique_ptr<AudioCapturerChangeInfo>> audioCapturerChangeInfos;
8614 streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos);
8615 AppendFormat(dumpString, " - audiocapturer stream size : %zu\n", audioCapturerChangeInfos.size());
8616 for (auto it = audioCapturerChangeInfos.begin(); it != audioCapturerChangeInfos.end(); it++) {
8617 if ((*it)->capturerInfo.capturerFlags == STREAM_FLAG_NORMAL) {
8618 AppendFormat(dumpString, " - normal audiocapturer stream:\n");
8619 } else if ((*it)->capturerInfo.capturerFlags == STREAM_FLAG_FAST) {
8620 AppendFormat(dumpString, " - fast audiocapturer stream:\n");
8621 }
8622 AppendFormat(dumpString, " - clientUID : %d\n", (*it)->clientUID);
8623 AppendFormat(dumpString, " - streamId : %d\n", (*it)->sessionId);
8624 AppendFormat(dumpString, " - is muted : %s\n", (*it)->muted ? "true" : "false");
8625 AppendFormat(dumpString, " - deviceType : %d\n", (*it)->inputDeviceInfo.deviceType_);
8626 AppendFormat(dumpString, " - samplingRate : %d\n", (*it)->capturerInfo.samplingRate);
8627 AppendFormat(dumpString, " - pipeType : %d\n", (*it)->capturerInfo.pipeType);
8628 }
8629 }
8630
GetOffloadStatusDump(std::string & dumpString)8631 void AudioPolicyService::GetOffloadStatusDump(std::string &dumpString)
8632 {
8633 dumpString += "\nOffload status:";
8634 DeviceType dev = GetActiveOutputDevice();
8635 if (dev != DEVICE_TYPE_SPEAKER && dev != DEVICE_TYPE_USB_HEADSET && dev != DEVICE_TYPE_BLUETOOTH_A2DP) {
8636 AppendFormat(dumpString, " - current device do not supportted offload: %d\n", dev);
8637 }
8638 dumpString += "\nPrimary Offload\n";
8639 if (dev == DEVICE_TYPE_SPEAKER || dev == DEVICE_TYPE_USB_HEADSET) {
8640 AppendFormat(dumpString, " - primary deviceType : %d\n", dev);
8641 AppendFormat(dumpString, " - primary offloadEnable : %d\n", GetOffloadAvailableFromXml());
8642 } else {
8643 AppendFormat(dumpString, " - current device is not primary\n");
8644 }
8645 dumpString += "\nA2DP offload\n";
8646 if (dev == DEVICE_TYPE_BLUETOOTH_A2DP) {
8647 AppendFormat(dumpString, " - A2DP deviceType: %d\n", dev);
8648 AppendFormat(dumpString, " - A2DP offloadstatus : %d\n", a2dpOffloadFlag_);
8649 } else {
8650 AppendFormat(dumpString, " - current device is not A2DP\n");
8651 }
8652 AppendFormat(dumpString, "\n");
8653 }
8654
GetCurActivateCount()8655 int32_t AudioPolicyService::GetCurActivateCount()
8656 {
8657 return audioPolicyManager_.GetCurActivateCount();
8658 }
8659
NotifyAccountsChanged(const int & id)8660 void AudioPolicyService::NotifyAccountsChanged(const int &id)
8661 {
8662 audioPolicyManager_.NotifyAccountsChanged(id);
8663 }
8664
WriteServiceStartupError(string reason)8665 void AudioPolicyService::WriteServiceStartupError(string reason)
8666 {
8667 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
8668 Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::AUDIO_SERVICE_STARTUP_ERROR,
8669 Media::MediaMonitor::EventType::FAULT_EVENT);
8670 bean->Add("SERVICE_ID", static_cast<int32_t>(Media::MediaMonitor::AUDIO_POLICY_SERVICE_ID));
8671 bean->Add("ERROR_CODE", static_cast<int32_t>(Media::MediaMonitor::AUDIO_POLICY_SERVER));
8672 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
8673 }
8674
LoadToneDtmfConfig()8675 bool AudioPolicyService::LoadToneDtmfConfig()
8676 {
8677 AUDIO_INFO_LOG("Enter");
8678 std::unique_ptr<AudioToneParser> audioToneParser = make_unique<AudioToneParser>();
8679 if (audioToneParser == nullptr) {
8680 WriteServiceStartupError("Audio Tone Load Configuration failed");
8681 }
8682 CHECK_AND_RETURN_RET_LOG(audioToneParser != nullptr, false, "Failed to create AudioToneParser");
8683 std::string AUDIO_TONE_CONFIG_FILE = "system/etc/audio/audio_tone_dtmf_config.xml";
8684
8685 if (audioToneParser->LoadConfig(toneDescriptorMap)) {
8686 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
8687 Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::LOAD_CONFIG_ERROR,
8688 Media::MediaMonitor::EventType::FAULT_EVENT);
8689 bean->Add("CATEGORY", Media::MediaMonitor::AUDIO_TONE_DTMF_CONFIG);
8690 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
8691 WriteServiceStartupError("Audio Tone Load Configuration failed");
8692 AUDIO_ERR_LOG("Audio Tone Load Configuration failed");
8693 return false;
8694 }
8695 AUDIO_INFO_LOG("Done");
8696 return true;
8697 }
8698
SetAudioConcurrencyCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object)8699 int32_t AudioPolicyService::SetAudioConcurrencyCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object)
8700 {
8701 return streamCollector_.SetAudioConcurrencyCallback(sessionID, object);
8702 }
8703
UnsetAudioConcurrencyCallback(const uint32_t sessionID)8704 int32_t AudioPolicyService::UnsetAudioConcurrencyCallback(const uint32_t sessionID)
8705 {
8706 return streamCollector_.UnsetAudioConcurrencyCallback(sessionID);
8707 }
8708
ActivateAudioConcurrency(const AudioPipeType & pipeType)8709 int32_t AudioPolicyService::ActivateAudioConcurrency(const AudioPipeType &pipeType)
8710 {
8711 return streamCollector_.ActivateAudioConcurrency(pipeType);
8712 }
8713
OnReceiveBluetoothEvent(const std::string macAddress,const std::string deviceName)8714 void AudioPolicyService::OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName)
8715 {
8716 std::lock_guard<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_);
8717 audioDeviceManager_.OnReceiveBluetoothEvent(macAddress, deviceName);
8718 for (auto device : connectedDevices_) {
8719 if (device->macAddress_ == macAddress) {
8720 device->deviceName_ = deviceName;
8721 int32_t bluetoothId_ = device->deviceId_;
8722 std::string name_ = device->deviceName_;
8723 AUDIO_INFO_LOG("bluetoothId %{public}d alias name changing to %{public}s", bluetoothId_, name_.c_str());
8724 }
8725 }
8726 }
8727
UpdateRoute(unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & outputDevices)8728 void AudioPolicyService::UpdateRoute(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
8729 vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices)
8730 {
8731 StreamUsage streamUsage = rendererChangeInfo->rendererInfo.streamUsage;
8732 InternalDeviceType deviceType = outputDevices.front()->deviceType_;
8733 AUDIO_INFO_LOG("update route, streamUsage:%{public}d, 1st devicetype:%{public}d", streamUsage, deviceType);
8734 if (Util::IsRingerOrAlarmerStreamUsage(streamUsage) && IsRingerOrAlarmerDualDevicesRange(deviceType)) {
8735 if (!SelectRingerOrAlarmDevices(outputDevices, rendererChangeInfo)) {
8736 UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG);
8737 }
8738
8739 AudioRingerMode ringerMode = audioPolicyManager_.GetRingerMode();
8740 if (ringerMode != RINGER_MODE_NORMAL && IsRingerOrAlarmerDualDevicesRange(outputDevices.front()->getType()) &&
8741 outputDevices.front()->getType() != DEVICE_TYPE_SPEAKER) {
8742 audioPolicyManager_.SetStreamMute(STREAM_RING, false, streamUsage);
8743 ringerModeMute_.store(false);
8744 if (audioPolicyManager_.GetSystemVolumeLevel(STREAM_RING) <
8745 audioPolicyManager_.GetMaxVolumeLevel(STREAM_RING) / VOLUME_LEVEL_DEFAULT_SIZE) {
8746 audioPolicyManager_.SetDoubleRingVolumeDb(STREAM_RING,
8747 audioPolicyManager_.GetMaxVolumeLevel(STREAM_RING) / VOLUME_LEVEL_DEFAULT_SIZE);
8748 }
8749 } else {
8750 ringerModeMute_.store(true);
8751 }
8752 shouldUpdateDeviceDueToDualTone_ = true;
8753 } else {
8754 if (enableDualHalToneState_) {
8755 AUDIO_INFO_LOG("disable dual hal tone for not ringer/alarm.");
8756 UpdateDualToneState(false, enableDualHalToneSessionId_);
8757 }
8758 ringerModeMute_.store(true);
8759 UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG);
8760 shouldUpdateDeviceDueToDualTone_ = false;
8761 }
8762 }
8763
IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType & deviceType)8764 bool AudioPolicyService::IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType &deviceType)
8765 {
8766 switch (deviceType) {
8767 case DEVICE_TYPE_SPEAKER:
8768 case DEVICE_TYPE_WIRED_HEADSET:
8769 case DEVICE_TYPE_WIRED_HEADPHONES:
8770 case DEVICE_TYPE_BLUETOOTH_SCO:
8771 case DEVICE_TYPE_BLUETOOTH_A2DP:
8772 case DEVICE_TYPE_USB_HEADSET:
8773 case DEVICE_TYPE_USB_ARM_HEADSET:
8774 return true;
8775 default:
8776 return false;
8777 }
8778 }
8779
IsA2dpOrArmUsbDevice(const InternalDeviceType & deviceType)8780 bool AudioPolicyService::IsA2dpOrArmUsbDevice(const InternalDeviceType &deviceType)
8781 {
8782 switch (deviceType) {
8783 case DEVICE_TYPE_BLUETOOTH_A2DP:
8784 case DEVICE_TYPE_USB_ARM_HEADSET:
8785 return true;
8786 default: {
8787 return false;
8788 }
8789 }
8790 }
8791
SelectRingerOrAlarmDevices(const vector<std::unique_ptr<AudioDeviceDescriptor>> & descs,const unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo)8792 bool AudioPolicyService::SelectRingerOrAlarmDevices(const vector<std::unique_ptr<AudioDeviceDescriptor>> &descs,
8793 const unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo)
8794 {
8795 CHECK_AND_RETURN_RET_LOG(descs.size() > 0 && descs.size() <= AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT, false,
8796 "audio devices not in range for ringer or alarmer.");
8797 const int32_t sessionId = rendererChangeInfo->sessionId;
8798 const StreamUsage streamUsage = rendererChangeInfo->rendererInfo.streamUsage;
8799 bool allDevicesInDualDevicesRange = true;
8800 std::vector<std::pair<InternalDeviceType, DeviceFlag>> activeDevices;
8801 for (size_t i = 0; i < descs.size(); i++) {
8802 if (IsRingerOrAlarmerDualDevicesRange(descs[i]->deviceType_)) {
8803 activeDevices.push_back(make_pair(descs[i]->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG));
8804 AUDIO_INFO_LOG("select ringer/alarm devices devicetype[%{public}zu]:%{public}d", i, descs[i]->deviceType_);
8805 } else {
8806 allDevicesInDualDevicesRange = false;
8807 break;
8808 }
8809 }
8810
8811 AUDIO_INFO_LOG("select ringer/alarm sessionId:%{public}d, streamUsage:%{public}d", sessionId, streamUsage);
8812 if (!descs.empty() && allDevicesInDualDevicesRange) {
8813 if (descs.size() == AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT &&
8814 GetSinkName(*descs.front(), sessionId) != GetSinkName(*descs.back(), sessionId)) {
8815 AUDIO_INFO_LOG("set dual hal tone, reset primary sink to default before.");
8816 UpdateActiveDeviceRoute(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG);
8817 if (enableDualHalToneState_ && enableDualHalToneSessionId_ != sessionId) {
8818 AUDIO_INFO_LOG("sesion changed, disable old dual hal tone.");
8819 UpdateDualToneState(false, enableDualHalToneSessionId_);
8820 }
8821
8822 if ((GetRingerMode() != RINGER_MODE_NORMAL) && (streamUsage != STREAM_USAGE_ALARM)) {
8823 AUDIO_INFO_LOG("no normal ringer mode and no alarm, dont dual hal tone.");
8824 return false;
8825 }
8826 UpdateDualToneState(true, sessionId);
8827 } else {
8828 UpdateActiveDevicesRoute(activeDevices);
8829 }
8830 return true;
8831 }
8832 return false;
8833 }
8834
DealAudioSceneOutputDevices(const AudioScene & audioScene,std::vector<DeviceType> & activeOutputDevices,bool & haveArmUsbDevice)8835 void AudioPolicyService::DealAudioSceneOutputDevices(const AudioScene &audioScene,
8836 std::vector<DeviceType> &activeOutputDevices, bool &haveArmUsbDevice)
8837 {
8838 vector<std::unique_ptr<AudioDeviceDescriptor>> descs {};
8839 switch (audioScene) {
8840 case AUDIO_SCENE_RINGING:
8841 descs = audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_RINGTONE, -1);
8842 if (!descs.empty()) {
8843 SetCurrentOutputDeviceType(descs.front()->getType());
8844 }
8845 break;
8846 case AUDIO_SCENE_VOICE_RINGING:
8847 descs = audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_VOICE_RINGTONE, -1);
8848 if (!descs.empty()) {
8849 SetCurrentOutputDeviceType(descs.front()->getType());
8850 }
8851 break;
8852 default:
8853 AUDIO_INFO_LOG("No ringing scene:%{public}d", audioScene);
8854 break;
8855 }
8856
8857 if (!descs.empty()) {
8858 for (size_t i = 0; i < descs.size(); i++) {
8859 if (descs[i]->getType() == DEVICE_TYPE_USB_ARM_HEADSET) {
8860 AUDIO_INFO_LOG("usb headset is arm device.");
8861 activeOutputDevices.push_back(DEVICE_TYPE_USB_ARM_HEADSET);
8862 haveArmUsbDevice = true;
8863 } else {
8864 activeOutputDevices.push_back(descs[i]->getType());
8865 }
8866 }
8867 } else {
8868 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_USB_ARM_HEADSET) {
8869 activeOutputDevices.push_back(DEVICE_TYPE_USB_ARM_HEADSET);
8870 haveArmUsbDevice = true;
8871 } else {
8872 activeOutputDevices.push_back(GetCurrentOutputDeviceType());
8873 }
8874 }
8875 }
8876
ResetRingerModeMute()8877 int32_t AudioPolicyService::ResetRingerModeMute()
8878 {
8879 if (!ringerModeMute_.load()) {
8880 std::unique_lock<std::mutex> lock(ringerModeMuteMutex_);
8881 bool resetWaiting = ringerModeMuteCondition_.wait_for(lock,
8882 std::chrono::milliseconds(WAIT_RINGER_MODE_MUTE_RESET_TIME_MS),
8883 [this] { return !ringerModeMute_.load(); }
8884 );
8885 if (!resetWaiting || audioScene_ == AUDIO_SCENE_DEFAULT) {
8886 AUDIO_INFO_LOG("reset ringer mode mute");
8887 if (audioPolicyManager_.SetStreamMute(STREAM_RING, true) == SUCCESS) {
8888 ringerModeMute_.store(true);
8889 }
8890 }
8891 }
8892 return SUCCESS;
8893 }
8894
IsRingerModeMute()8895 bool AudioPolicyService::IsRingerModeMute()
8896 {
8897 return ringerModeMute_.load();
8898 }
8899
LoadHdiEffectModel()8900 void AudioPolicyService::LoadHdiEffectModel()
8901 {
8902 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
8903 CHECK_AND_RETURN_LOG(gsp != nullptr, "Audio Server Proxy is null");
8904
8905 std::string identity = IPCSkeleton::ResetCallingIdentity();
8906 gsp->LoadHdiEffectModel();
8907 IPCSkeleton::SetCallingIdentity(identity);
8908 }
8909
GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)8910 int32_t AudioPolicyService::GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
8911 {
8912 return AUDIO_OK;
8913 }
8914
SetAudioEffectProperty(const AudioEffectPropertyArrayV3 & propertyArray)8915 int32_t AudioPolicyService::SetAudioEffectProperty(const AudioEffectPropertyArrayV3 &propertyArray)
8916 {
8917 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
8918 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_INVALID_HANDLE, "Service proxy unavailable");
8919 std::string identity = IPCSkeleton::ResetCallingIdentity();
8920 int32_t ret = gsp->SetAudioEffectProperty(propertyArray);
8921 IPCSkeleton::SetCallingIdentity(identity);
8922 return ret;
8923 }
8924
GetAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)8925 int32_t AudioPolicyService::GetAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
8926 {
8927 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
8928 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_INVALID_HANDLE, "Service proxy unavailable");
8929 std::string identity = IPCSkeleton::ResetCallingIdentity();
8930 int32_t ret = gsp->GetAudioEffectProperty(propertyArray);
8931 IPCSkeleton::SetCallingIdentity(identity);
8932 return ret;
8933 }
8934
UpdateEffectBtOffloadSupported(const bool & isSupported)8935 void AudioPolicyService::UpdateEffectBtOffloadSupported(const bool &isSupported)
8936 {
8937 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
8938 CHECK_AND_RETURN_LOG(gsp != nullptr, "Audio Server Proxy is null");
8939
8940 std::string identity = IPCSkeleton::ResetCallingIdentity();
8941 gsp->UpdateEffectBtOffloadSupported(isSupported);
8942 IPCSkeleton::SetCallingIdentity(identity);
8943 return;
8944 }
8945
ScoInputDeviceFetchedForRecongnition(bool handleFlag,const std::string & address,ConnectState connectState)8946 int32_t AudioPolicyService::ScoInputDeviceFetchedForRecongnition(bool handleFlag, const std::string &address,
8947 ConnectState connectState)
8948 {
8949 Bluetooth::BluetoothRemoteDevice device = Bluetooth::BluetoothRemoteDevice(address);
8950 if (handleFlag && connectState != DEACTIVE_CONNECTED) {
8951 return SUCCESS;
8952 }
8953 return Bluetooth::AudioHfpManager::HandleScoWithRecongnition(handleFlag, device);
8954 }
8955
SetRotationToEffect(const uint32_t rotate)8956 void AudioPolicyService::SetRotationToEffect(const uint32_t rotate)
8957 {
8958 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
8959 CHECK_AND_RETURN_LOG(gsp != nullptr, "Audio Server Proxy is null");
8960
8961 std::string identity = IPCSkeleton::ResetCallingIdentity();
8962 gsp->SetRotationToEffect(rotate);
8963 IPCSkeleton::SetCallingIdentity(identity);
8964 }
8965
IsA2dpOffloadConnected()8966 bool AudioPolicyService::IsA2dpOffloadConnected()
8967 {
8968 if (audioA2dpOffloadManager_ == nullptr) {
8969 AUDIO_WARNING_LOG("Null audioA2dpOffloadManager");
8970 return true;
8971 }
8972 A2dpOffloadConnectionState state = audioA2dpOffloadManager_->GetA2dOffloadConnectionState();
8973 return state == CONNECTION_STATUS_CONNECTED;
8974 }
8975
UpdateSessionConnectionState(const int32_t & sessionID,const int32_t & state)8976 void AudioPolicyService::UpdateSessionConnectionState(const int32_t &sessionID, const int32_t &state)
8977 {
8978 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
8979 CHECK_AND_RETURN_LOG(gsp != nullptr, "Audio Server Proxy is null");
8980
8981 std::string identity = IPCSkeleton::ResetCallingIdentity();
8982 gsp->UpdateSessionConnectionState(sessionID, state);
8983 IPCSkeleton::SetCallingIdentity(identity);
8984 }
8985
LoadSplitModule(const std::string & splitArgs,const std::string & networkId)8986 int32_t AudioPolicyService::LoadSplitModule(const std::string &splitArgs, const std::string &networkId)
8987 {
8988 AUDIO_INFO_LOG("start audio stream split, the split args is %{public}s", splitArgs.c_str());
8989 if (splitArgs.empty() || networkId.empty()) {
8990 std::string anonymousNetworkId = networkId.empty() ? "" : networkId.substr(0, 2) + "***";
8991 AUDIO_ERR_LOG("LoadSplitModule, invalid param, splitArgs:'%{public}s', networkId:'%{public}s'",
8992 splitArgs.c_str(), anonymousNetworkId.c_str());
8993 return ERR_INVALID_PARAM;
8994 }
8995 std::string moduleName = GetRemoteModuleName(networkId, OUTPUT_DEVICE);
8996
8997 ClosePortAndEraseIOHandle(moduleName);
8998
8999 AudioModuleInfo moudleInfo = ConstructRemoteAudioModuleInfo(networkId, OUTPUT_DEVICE, DEVICE_TYPE_SPEAKER);
9000 moudleInfo.lib = "libmodule-split-stream-sink.z.so";
9001 moudleInfo.extra = splitArgs;
9002
9003 int32_t openRet = OpenPortAndInsertIOHandle(moduleName, moudleInfo);
9004 if (openRet != 0) {
9005 AUDIO_ERR_LOG("open fail, OpenPortAndInsertIOHandle ret: %{public}d", openRet);
9006 }
9007 return openRet;
9008 }
9009
SetDefaultOutputDevice(const DeviceType deviceType,const uint32_t sessionID,const StreamUsage streamUsage,bool isRunning)9010 int32_t AudioPolicyService::SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionID,
9011 const StreamUsage streamUsage, bool isRunning)
9012 {
9013 CHECK_AND_RETURN_RET_LOG(hasEarpiece_, ERR_NOT_SUPPORTED, "the device has no earpiece");
9014 int32_t ret = audioDeviceManager_.SetDefaultOutputDevice(deviceType, sessionID, streamUsage, isRunning);
9015 if (ret == NEED_TO_FETCH) {
9016 FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::SET_DEFAULT_OUTPUT_DEVICE);
9017 return SUCCESS;
9018 }
9019 return ret;
9020 }
9021
UpdateDefaultOutputDeviceWhenStopping(int32_t uid)9022 void AudioPolicyService::UpdateDefaultOutputDeviceWhenStopping(int32_t uid)
9023 {
9024 std::vector<uint32_t> sessionIDSet = streamCollector_.GetAllRendererSessionIDForUID(uid);
9025 for (const auto &sessionID : sessionIDSet) {
9026 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(sessionID);
9027 audioDeviceManager_.RemoveSelectedDefaultOutputDevice(sessionID);
9028 }
9029 FetchDevice(true);
9030 }
9031
SetPreferredDevice(const PreferredType preferredType,const sptr<AudioDeviceDescriptor> & desc)9032 int32_t AudioPolicyService::SetPreferredDevice(const PreferredType preferredType,
9033 const sptr<AudioDeviceDescriptor> &desc)
9034 {
9035 int32_t ret = SUCCESS;
9036 switch (preferredType) {
9037 case AUDIO_MEDIA_RENDER:
9038 audioStateManager_.SetPreferredMediaRenderDevice(desc);
9039 break;
9040 case AUDIO_CALL_RENDER:
9041 audioStateManager_.SetPreferredCallRenderDevice(desc);
9042 break;
9043 case AUDIO_CALL_CAPTURE:
9044 audioStateManager_.SetPreferredCallCaptureDevice(desc);
9045 break;
9046 case AUDIO_RECORD_CAPTURE:
9047 audioStateManager_.SetPreferredRecordCaptureDevice(desc);
9048 break;
9049 case AUDIO_RING_RENDER:
9050 case AUDIO_TONE_RENDER:
9051 AUDIO_WARNING_LOG("preferredType:%{public}d, not supported", preferredType);
9052 ret = ERR_INVALID_PARAM;
9053 break;
9054 default:
9055 AUDIO_ERR_LOG("invalid preferredType: %{public}d", preferredType);
9056 ret = ERR_INVALID_PARAM;
9057 break;
9058 }
9059 if (desc == nullptr || desc->deviceType_ == DEVICE_TYPE_NONE) {
9060 ErasePreferredDeviceByType(preferredType);
9061 }
9062 if (ret != SUCCESS) {
9063 AUDIO_ERR_LOG("Set preferredType %{public}d failed, ret: %{public}d", preferredType, ret);
9064 }
9065 return ret;
9066 }
9067
ErasePreferredDeviceByType(const PreferredType preferredType)9068 int32_t AudioPolicyService::ErasePreferredDeviceByType(const PreferredType preferredType)
9069 {
9070 if (isBTReconnecting_) {
9071 return SUCCESS;
9072 }
9073 auto type = static_cast<Media::MediaMonitor::PerferredType>(preferredType);
9074 int32_t ret = Media::MediaMonitor::MediaMonitorManager::GetInstance().ErasePreferredDeviceByType(type);
9075 if (ret != SUCCESS) {
9076 AUDIO_ERR_LOG("Erase preferredType %{public}d failed, ret: %{public}d", preferredType, ret);
9077 return ERROR;
9078 }
9079 return SUCCESS;
9080 }
9081
OnA2dpPlayingStateChanged(const std::string & deviceAddress,int32_t playingState)9082 void AudioA2dpOffloadManager::OnA2dpPlayingStateChanged(const std::string &deviceAddress, int32_t playingState)
9083 {
9084 AUDIO_INFO_LOG("OnA2dpPlayingStateChanged current A2dpOffload MacAddr:%{public}s, incoming MacAddr:%{public}s, "
9085 "currentStatus:%{public}d, incommingState:%{public}d", GetEncryptAddr(a2dpOffloadDeviceAddress_).c_str(),
9086 GetEncryptAddr(deviceAddress).c_str(), currentOffloadConnectionState_, playingState);
9087 if (deviceAddress != a2dpOffloadDeviceAddress_) {
9088 if (playingState == A2DP_STOPPED && currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTED) {
9089 return;
9090 }
9091 // below is A2dp(not offload scenario)
9092 currentOffloadConnectionState_ = CONNECTION_STATUS_DISCONNECTED;
9093 return;
9094 }
9095
9096 // deviceAddress matched
9097 if (playingState == A2DP_PLAYING) {
9098 if (currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTING) {
9099 AUDIO_INFO_LOG("OnA2dpPlayingStateChanged currentOffloadConnectionState_ change "
9100 "from %{public}d to %{public}d", currentOffloadConnectionState_, CONNECTION_STATUS_CONNECTED);
9101
9102 for (int32_t sessionId : connectionTriggerSessionIds_) {
9103 audioPolicyService_->UpdateSessionConnectionState(sessionId, DATA_LINK_CONNECTED);
9104 }
9105 std::vector<int32_t>().swap(connectionTriggerSessionIds_);
9106 connectionCV_.notify_all();
9107 }
9108 currentOffloadConnectionState_ = CONNECTION_STATUS_CONNECTED;
9109 } else if (playingState == A2DP_STOPPED) {
9110 AUDIO_INFO_LOG("OnA2dpPlayingStateChanged currentOffloadConnectionState_ change "
9111 "from %{public}d to %{public}d", currentOffloadConnectionState_, CONNECTION_STATUS_DISCONNECTED);
9112
9113 currentOffloadConnectionState_ = CONNECTION_STATUS_DISCONNECTED;
9114 a2dpOffloadDeviceAddress_ = "";
9115 std::vector<int32_t>().swap(connectionTriggerSessionIds_);
9116 } else {
9117 // at the current moment, we only handle the PLAYING and STOPPED state,
9118 // will handle other state in the future
9119 AUDIO_INFO_LOG("OnA2dpPlayingStateChanged currentOffloadConnectionState_: %{public}d, "
9120 "received unexpected state:%{public}d", currentOffloadConnectionState_, playingState);
9121 }
9122 }
9123
ConnectA2dpOffload(const std::string & deviceAddress,const vector<int32_t> & sessionIds)9124 void AudioA2dpOffloadManager::ConnectA2dpOffload(const std::string &deviceAddress, const vector<int32_t> &sessionIds)
9125 {
9126 AUDIO_INFO_LOG("start connecting a2dpOffload for MacAddr:%{public}s.", GetEncryptAddr(deviceAddress).c_str());
9127 a2dpOffloadDeviceAddress_ = deviceAddress;
9128 connectionTriggerSessionIds_.assign(sessionIds.begin(), sessionIds.end());
9129
9130 for (int32_t sessionId : connectionTriggerSessionIds_) {
9131 audioPolicyService_->UpdateSessionConnectionState(sessionId, DATA_LINK_CONNECTING);
9132 }
9133
9134 if (currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTED ||
9135 currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTING) {
9136 AUDIO_INFO_LOG("currentOffloadConnectionState_ already in %{public}d, "
9137 "status, no need to trigger another waiting", currentOffloadConnectionState_);
9138 return;
9139 }
9140
9141 std::thread switchThread(&AudioA2dpOffloadManager::WaitForConnectionCompleted, this);
9142 switchThread.detach();
9143 AUDIO_INFO_LOG("currentOffloadConnectionState_ change from %{public}d to %{public}d",
9144 currentOffloadConnectionState_, CONNECTION_STATUS_CONNECTING);
9145 currentOffloadConnectionState_ = CONNECTION_STATUS_CONNECTING;
9146 }
9147
WaitForConnectionCompleted()9148 void AudioA2dpOffloadManager::WaitForConnectionCompleted()
9149 {
9150 std::unique_lock<std::mutex> waitLock(connectionMutex_);
9151 bool connectionCompleted = connectionCV_.wait_for(waitLock,
9152 std::chrono::milliseconds(AudioA2dpOffloadManager::CONNECTION_TIMEOUT_IN_MS), [this] {
9153 return currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTED;
9154 });
9155 // a2dp connection timeout, anyway we should notify client dataLink OK in order to allow the data flow begin
9156 AUDIO_INFO_LOG("WaitForConnectionCompleted unblocked, connectionCompleted is %{public}d", connectionCompleted);
9157
9158 if (!connectionCompleted) {
9159 AUDIO_INFO_LOG("currentOffloadConnectionState_ change from %{public}d to %{public}d",
9160 currentOffloadConnectionState_, CONNECTION_STATUS_TIMEOUT);
9161 currentOffloadConnectionState_ = CONNECTION_STATUS_CONNECTED;
9162 for (int32_t sessionId : connectionTriggerSessionIds_) {
9163 audioPolicyService_->UpdateSessionConnectionState(sessionId, DATA_LINK_CONNECTED);
9164 }
9165 std::vector<int32_t>().swap(connectionTriggerSessionIds_);
9166 }
9167 waitLock.unlock();
9168 audioPolicyService_->FetchStreamForA2dpOffload(false);
9169 return;
9170 }
9171
IsA2dpOffloadConnecting(int32_t sessionId)9172 bool AudioA2dpOffloadManager::IsA2dpOffloadConnecting(int32_t sessionId)
9173 {
9174 if (currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTING) {
9175 if (std::find(connectionTriggerSessionIds_.begin(), connectionTriggerSessionIds_.end(), sessionId) !=
9176 connectionTriggerSessionIds_.end()) {
9177 return true;
9178 }
9179 }
9180 return false;
9181 }
9182
GetAudioEffectOffloadFlag()9183 bool AudioPolicyService::GetAudioEffectOffloadFlag()
9184 {
9185 // check if audio effect offload
9186 const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
9187 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, false, "gsp null");
9188
9189 std::string identity = IPCSkeleton::ResetCallingIdentity();
9190 bool effectOffloadFlag = gsp->GetEffectOffloadEnabled();
9191 IPCSkeleton::SetCallingIdentity(identity);
9192 return effectOffloadFlag;
9193 }
9194
CheckSpatializationAndEffectState()9195 bool AudioPolicyService::CheckSpatializationAndEffectState()
9196 {
9197 AudioSpatializationState spatialState =
9198 AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState();
9199 bool effectOffloadFlag = GetAudioEffectOffloadFlag();
9200 return spatialState.spatializationEnabled && !effectOffloadFlag;
9201 }
9202
JudgeIfLoadMchModule()9203 void AudioPolicyService::JudgeIfLoadMchModule()
9204 {
9205 bool isNeedLoadMchModule = false;
9206 {
9207 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
9208 if (IOHandles_.find(MCH_PRIMARY_SPEAKER) == IOHandles_.end()) {
9209 isNeedLoadMchModule = true;
9210 }
9211 }
9212 if (isNeedLoadMchModule) {
9213 LoadMchModule();
9214 }
9215 }
9216
FetchStreamForSpkMchStream(std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & descs)9217 void AudioPolicyService::FetchStreamForSpkMchStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
9218 vector<std::unique_ptr<AudioDeviceDescriptor>> &descs)
9219 {
9220 if (CheckStreamMultichannelMode(rendererChangeInfo->sessionId)) {
9221 JudgeIfLoadMchModule();
9222 std::string oldSinkName = GetSinkName(rendererChangeInfo->outputDeviceInfo, rendererChangeInfo->sessionId);
9223 std::string newSinkName = GetSinkPortName(descs.front()->deviceType_, PIPE_TYPE_MULTICHANNEL);
9224 AUDIO_INFO_LOG("mute sink old:[%{public}s] new:[%{public}s]", oldSinkName.c_str(), newSinkName.c_str());
9225 MuteSinkPort(oldSinkName, newSinkName, AudioStreamDeviceChangeReason::OVERRODE);
9226 int32_t ret = MoveToOutputDevice(rendererChangeInfo->sessionId, newSinkName);
9227 if (ret == SUCCESS) {
9228 streamCollector_.UpdateRendererPipeInfo(rendererChangeInfo->sessionId, PIPE_TYPE_MULTICHANNEL);
9229 }
9230 } else {
9231 AudioPipeType pipeType = PIPE_TYPE_UNKNOWN;
9232 streamCollector_.GetPipeType(rendererChangeInfo->sessionId, pipeType);
9233 if (pipeType == PIPE_TYPE_MULTICHANNEL) {
9234 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_);
9235 {
9236 AUDIO_INFO_LOG("unload multichannel module");
9237 std::string currentActivePort = MCH_PRIMARY_SPEAKER;
9238 auto ioHandleIter = IOHandles_.find(currentActivePort);
9239 CHECK_AND_RETURN_LOG(ioHandleIter != IOHandles_.end(), "Can not find port MCH_PRIMARY_SPEAKER in io map");
9240 AudioIOHandle activateDeviceIOHandle = ioHandleIter->second;
9241 audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
9242 audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle);
9243 IOHandles_.erase(currentActivePort);
9244 }
9245 }
9246 ResetOffloadMode(rendererChangeInfo->sessionId);
9247 }
9248 }
9249
ResetOffloadAndMchMode(std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & outputDevices)9250 void AudioPolicyService::ResetOffloadAndMchMode(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
9251 vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices)
9252 {
9253 if (outputDevices.front()->networkId_ != LOCAL_NETWORK_ID
9254 || outputDevices.front()->deviceType_ == DEVICE_TYPE_REMOTE_CAST) {
9255 RemoteOffloadStreamRelease(rendererChangeInfo->sessionId);
9256 } else {
9257 FetchStreamForSpkMchStream(rendererChangeInfo, outputDevices);
9258 }
9259 }
9260
ActivateConcurrencyFromServer(AudioPipeType incomingPipe)9261 int32_t AudioPolicyService::ActivateConcurrencyFromServer(AudioPipeType incomingPipe)
9262 {
9263 std::lock_guard<std::mutex> lock(offloadMutex_);
9264 CHECK_AND_RETURN_RET_LOG(!offloadSessionID_.has_value(),
9265 ERR_ILLEGAL_STATE, "Offload stream existing, concede incoming lowlatency stream");
9266 return SUCCESS;
9267 }
9268
IsVoiceCallRelatedScene()9269 bool AudioPolicyService::IsVoiceCallRelatedScene()
9270 {
9271 return audioScene_ == AUDIO_SCENE_RINGING ||
9272 audioScene_ == AUDIO_SCENE_PHONE_CALL ||
9273 audioScene_ == AUDIO_SCENE_PHONE_CHAT ||
9274 audioScene_ == AUDIO_SCENE_VOICE_RINGING;
9275 }
9276 } // namespace AudioStandard
9277 } // namespace OHOS
9278