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