• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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 
16 #include "audio_policy_service.h"
17 
18 #include "ipc_skeleton.h"
19 #include "hisysevent.h"
20 #include "iservice_registry.h"
21 #include "system_ability_definition.h"
22 #include "parameter.h"
23 
24 #include "audio_errors.h"
25 #include "audio_log.h"
26 #include "audio_utils.h"
27 #include "audio_focus_parser.h"
28 #include "audio_manager_listener_stub.h"
29 #include "datashare_helper.h"
30 #include "datashare_predicates.h"
31 #include "datashare_result_set.h"
32 #include "data_share_observer_callback.h"
33 #include "device_manager.h"
34 #include "device_init_callback.h"
35 #include "device_manager_impl.h"
36 #include "uri.h"
37 
38 #ifdef BLUETOOTH_ENABLE
39 #include "audio_server_death_recipient.h"
40 #include "audio_bluetooth_manager.h"
41 #endif
42 
43 namespace OHOS {
44 namespace AudioStandard {
45 using namespace std;
46 
47 static const std::string INNER_CAPTURER_SINK_NAME = "InnerCapturer";
48 static const std::string RECEIVER_SINK_NAME = "Receiver";
49 static const std::string SINK_NAME_FOR_CAPTURE_SUFFIX = "_CAP";
50 static const std::string MONITOR_SOURCE_SUFFIX = ".monitor";
51 
52 static const std::string SETTINGS_DATA_BASE_URI =
53     "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true";
54 static const std::string SETTINGS_DATA_FIELD_KEYWORD = "KEYWORD";
55 static const std::string SETTINGS_DATA_FIELD_VALUE = "VALUE";
56 static const std::string PREDICATES_STRING = "settings.general.device_name";
57 const uint32_t PCM_8_BIT = 8;
58 const uint32_t PCM_16_BIT = 16;
59 const uint32_t PCM_24_BIT = 24;
60 const uint32_t PCM_32_BIT = 32;
61 const uint32_t BT_BUFFER_ADJUSTMENT_FACTOR = 50;
62 const std::string AUDIO_SERVICE_PKG = "audio_manager_service";
63 const uint32_t PRIORITY_LIST_OFFSET_POSTION = 1;
64 std::shared_ptr<DataShare::DataShareHelper> g_dataShareHelper = nullptr;
65 static sptr<IStandardAudioService> g_adProxy = nullptr;
66 #ifdef BLUETOOTH_ENABLE
67 static sptr<IStandardAudioService> g_btProxy = nullptr;
68 #endif
69 static int32_t startDeviceId = 1;
70 mutex g_adProxyMutex;
71 mutex g_dataShareHelperMutex;
72 #ifdef BLUETOOTH_ENABLE
73 mutex g_btProxyMutex;
74 #endif
75 
~AudioPolicyService()76 AudioPolicyService::~AudioPolicyService()
77 {
78     AUDIO_ERR_LOG("~AudioPolicyService()");
79     Deinit();
80 }
81 
Init(void)82 bool AudioPolicyService::Init(void)
83 {
84     AUDIO_INFO_LOG("AudioPolicyService init");
85     serviceFlag_.reset();
86     audioPolicyManager_.Init();
87     audioEffectManager_.EffectManagerInit();
88 
89     if (!configParser_.LoadConfiguration()) {
90         AUDIO_ERR_LOG("Audio Config Load Configuration failed");
91         return false;
92     }
93     if (!configParser_.Parse()) {
94         AUDIO_ERR_LOG("Audio Config Parse failed");
95         return false;
96     }
97 
98 #ifdef FEATURE_DTMF_TONE
99     std::unique_ptr<AudioToneParser> audioToneParser = make_unique<AudioToneParser>();
100     CHECK_AND_RETURN_RET_LOG(audioToneParser != nullptr, false, "Failed to create AudioToneParser");
101     std::string AUDIO_TONE_CONFIG_FILE = "system/etc/audio/audio_tone_dtmf_config.xml";
102 
103     if (audioToneParser->LoadConfig(toneDescriptorMap)) {
104         AUDIO_ERR_LOG("Audio Tone Load Configuration failed");
105         return false;
106     }
107 #endif
108 
109     std::unique_ptr<AudioFocusParser> audioFocusParser = make_unique<AudioFocusParser>();
110     CHECK_AND_RETURN_RET_LOG(audioFocusParser != nullptr, false, "Failed to create AudioFocusParser");
111     std::string AUDIO_FOCUS_CONFIG_FILE = "system/etc/audio/audio_interrupt_policy_config.xml";
112 
113     if (audioFocusParser->LoadConfig(focusMap_)) {
114         AUDIO_ERR_LOG("Failed to load audio interrupt configuration!");
115         return false;
116     }
117     AUDIO_INFO_LOG("Audio interrupt configuration has been loaded. FocusMap.size: %{public}zu", focusMap_.size());
118 
119     if (deviceStatusListener_->RegisterDeviceStatusListener()) {
120         AUDIO_ERR_LOG("[Policy Service] Register for device status events failed");
121         return false;
122     }
123 
124     RegisterRemoteDevStatusCallback();
125 
126     // Get device type from const.product.devicetype when starting.
127     char devicesType[100] = {0}; // 100 for system parameter usage
128     (void)GetParameter("const.product.devicetype", " ", devicesType, sizeof(devicesType));
129     localDevicesType_ = devicesType;
130 
131     if (policyVolumeMap_ == nullptr) {
132         size_t mapSize = IPolicyProvider::GetVolumeVectorSize() * sizeof(Volume);
133         AUDIO_INFO_LOG("InitSharedVolume create shared volume map with size %{public}zu", mapSize);
134         policyVolumeMap_ = AudioSharedMemory::CreateFormLocal(mapSize, "PolicyVolumeMap");
135         CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr,
136             false, "Get shared memory failed!");
137         volumeVector_ = reinterpret_cast<Volume *>(policyVolumeMap_->GetBase());
138     }
139     return true;
140 }
141 
GetAudioServerProxy()142 const sptr<IStandardAudioService> AudioPolicyService::GetAudioServerProxy()
143 {
144     AUDIO_DEBUG_LOG("[Policy Service] Start get audio policy service proxy.");
145     lock_guard<mutex> lock(g_adProxyMutex);
146 
147     if (g_adProxy == nullptr) {
148         auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
149         if (samgr == nullptr) {
150             AUDIO_ERR_LOG("[Policy Service] Get samgr failed.");
151             return nullptr;
152         }
153 
154         sptr<IRemoteObject> object = samgr->GetSystemAbility(AUDIO_DISTRIBUTED_SERVICE_ID);
155         if (object == nullptr) {
156             AUDIO_ERR_LOG("[Policy Service] audio service remote object is NULL.");
157             return nullptr;
158         }
159 
160         g_adProxy = iface_cast<IStandardAudioService>(object);
161         if (g_adProxy == nullptr) {
162             AUDIO_ERR_LOG("[Policy Service] init g_adProxy is NULL.");
163             return nullptr;
164         }
165     }
166     const sptr<IStandardAudioService> gsp = g_adProxy;
167     return gsp;
168 }
169 
InitKVStore()170 void AudioPolicyService::InitKVStore()
171 {
172     audioPolicyManager_.InitKVStore();
173 }
174 
ConnectServiceAdapter()175 bool AudioPolicyService::ConnectServiceAdapter()
176 {
177     if (!audioPolicyManager_.ConnectServiceAdapter()) {
178         AUDIO_ERR_LOG("AudioPolicyService::ConnectServiceAdapter  Error in connecting to audio service adapter");
179         return false;
180     }
181 
182     OnServiceConnected(AudioServiceIndex::AUDIO_SERVICE_INDEX);
183 
184     return true;
185 }
186 
Deinit(void)187 void AudioPolicyService::Deinit(void)
188 {
189     AUDIO_ERR_LOG("Policy service died. closing active ports");
190     std::for_each(IOHandles_.begin(), IOHandles_.end(), [&](std::pair<std::string, AudioIOHandle> handle) {
191         audioPolicyManager_.CloseAudioPort(handle.second);
192     });
193 
194     IOHandles_.clear();
195 #ifdef ACCESSIBILITY_ENABLE
196     accessibilityConfigListener_->UnsubscribeObserver();
197 #endif
198     deviceStatusListener_->UnRegisterDeviceStatusListener();
199 
200     if (isBtListenerRegistered) {
201         UnregisterBluetoothListener();
202     }
203     volumeVector_ = nullptr;
204     policyVolumeMap_ = nullptr;
205 
206     return;
207 }
208 
SetAudioSessionCallback(AudioSessionCallback * callback)209 int32_t AudioPolicyService::SetAudioSessionCallback(AudioSessionCallback *callback)
210 {
211     return audioPolicyManager_.SetAudioSessionCallback(callback);
212 }
213 
GetMaxVolumeLevel(AudioVolumeType volumeType) const214 int32_t AudioPolicyService::GetMaxVolumeLevel(AudioVolumeType volumeType) const
215 {
216     if (volumeType == STREAM_ALL) {
217         volumeType = STREAM_MUSIC;
218     }
219     return audioPolicyManager_.GetMaxVolumeLevel(volumeType);
220 }
221 
GetMinVolumeLevel(AudioVolumeType volumeType) const222 int32_t AudioPolicyService::GetMinVolumeLevel(AudioVolumeType volumeType) const
223 {
224     if (volumeType == STREAM_ALL) {
225         volumeType = STREAM_MUSIC;
226     }
227     return audioPolicyManager_.GetMinVolumeLevel(volumeType);
228 }
229 
SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel,bool isFromVolumeKey)230 int32_t AudioPolicyService::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel, bool isFromVolumeKey)
231 {
232     int32_t result = audioPolicyManager_.SetSystemVolumeLevel(streamType, volumeLevel, isFromVolumeKey);
233     if (result == SUCCESS && streamType == STREAM_VOICE_CALL) {
234         SetVoiceCallVolume(volumeLevel);
235     }
236     // todo
237     Volume vol = {false, 1.0f, 0};
238     vol.volumeFloat = GetSystemVolumeInDb(streamType, volumeLevel, currentActiveDevice_);
239     SetSharedVolume(streamType, currentActiveDevice_, vol);
240     return result;
241 }
242 
SetVoiceCallVolume(int32_t volumeLevel)243 void AudioPolicyService::SetVoiceCallVolume(int32_t volumeLevel)
244 {
245     Trace trace("AudioPolicyService::SetVoiceCallVolume" + std::to_string(volumeLevel));
246     // set voice volume by the interface from hdi.
247     if (volumeLevel == 0) {
248         AUDIO_ERR_LOG("SetVoiceVolume: volume of voice_call cannot be set to 0");
249         return;
250     }
251     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
252     if (gsp == nullptr) {
253         AUDIO_ERR_LOG("SetVoiceVolume: gsp null");
254         return;
255     }
256     float volumeDb = static_cast<float>(volumeLevel) /
257         static_cast<float>(audioPolicyManager_.GetMaxVolumeLevel(STREAM_VOICE_CALL));
258     gsp->SetVoiceVolume(volumeDb);
259     AUDIO_INFO_LOG("SetVoiceVolume: %{public}f", volumeDb);
260 }
261 
SetVolumeForSwitchDevice(DeviceType deviceType)262 void AudioPolicyService::SetVolumeForSwitchDevice(DeviceType deviceType)
263 {
264     Trace trace("AudioPolicyService::SetVolumeForSwitchDevice:" + std::to_string(deviceType));
265     // Load volume from KvStore and set volume for each stream type
266     audioPolicyManager_.SetVolumeForSwitchDevice(deviceType);
267 
268     // The volume of voice_call needs to be adjusted separately
269     if (audioScene_ == AUDIO_SCENE_PHONE_CALL) {
270         SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL));
271     }
272 }
273 
274 
GetSystemVolumeLevel(AudioStreamType streamType,bool isFromVolumeKey) const275 int32_t AudioPolicyService::GetSystemVolumeLevel(AudioStreamType streamType, bool isFromVolumeKey) const
276 {
277     return audioPolicyManager_.GetSystemVolumeLevel(streamType, isFromVolumeKey);
278 }
279 
GetSystemVolumeDb(AudioStreamType streamType) const280 float AudioPolicyService::GetSystemVolumeDb(AudioStreamType streamType) const
281 {
282     return audioPolicyManager_.GetSystemVolumeDb(streamType);
283 }
284 
SetLowPowerVolume(int32_t streamId,float volume) const285 int32_t AudioPolicyService::SetLowPowerVolume(int32_t streamId, float volume) const
286 {
287     return streamCollector_.SetLowPowerVolume(streamId, volume);
288 }
289 
GetLowPowerVolume(int32_t streamId) const290 float AudioPolicyService::GetLowPowerVolume(int32_t streamId) const
291 {
292     return streamCollector_.GetLowPowerVolume(streamId);
293 }
294 
GetSingleStreamVolume(int32_t streamId) const295 float AudioPolicyService::GetSingleStreamVolume(int32_t streamId) const
296 {
297     return streamCollector_.GetSingleStreamVolume(streamId);
298 }
299 
SetStreamMute(AudioStreamType streamType,bool mute)300 int32_t AudioPolicyService::SetStreamMute(AudioStreamType streamType, bool mute)
301 {
302     int32_t result = audioPolicyManager_.SetStreamMute(streamType, mute);
303 
304     Volume vol = {false, 1.0f, 0};
305     vol.isMute = mute;
306     vol.volumeInt = GetSystemVolumeLevel(streamType);
307     vol.volumeFloat = GetSystemVolumeInDb(streamType, vol.volumeInt, currentActiveDevice_);
308     SetSharedVolume(streamType, currentActiveDevice_, vol);
309     return result;
310 }
311 
SetSourceOutputStreamMute(int32_t uid,bool setMute) const312 int32_t AudioPolicyService::SetSourceOutputStreamMute(int32_t uid, bool setMute) const
313 {
314     return audioPolicyManager_.SetSourceOutputStreamMute(uid, setMute);
315 }
316 
317 
GetStreamMute(AudioStreamType streamType) const318 bool AudioPolicyService::GetStreamMute(AudioStreamType streamType) const
319 {
320     return audioPolicyManager_.GetStreamMute(streamType);
321 }
322 
PrintSinkInput(SinkInput sinkInput)323 inline std::string PrintSinkInput(SinkInput sinkInput)
324 {
325     std::stringstream value;
326     value << "streamId:[" << sinkInput.streamId << "] ";
327     value << "streamType:[" << sinkInput.streamType << "] ";
328     value << "uid:[" << sinkInput.uid << "] ";
329     value << "pid:[" << sinkInput.pid << "] ";
330     value << "statusMark:[" << sinkInput.statusMark << "] ";
331     value << "sinkName:[" << sinkInput.sinkName << "] ";
332     value << "startTime:[" << sinkInput.startTime << "]";
333     return value.str();
334 }
335 
GetRemoteModuleName(std::string networkId,DeviceRole role)336 inline std::string GetRemoteModuleName(std::string networkId, DeviceRole role)
337 {
338     return networkId + (role == DeviceRole::OUTPUT_DEVICE ? "_out" : "_in");
339 }
340 
GetSelectedDeviceInfo(int32_t uid,int32_t pid,AudioStreamType streamType)341 std::string AudioPolicyService::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType)
342 {
343     (void)streamType;
344 
345     std::lock_guard<std::mutex> lock(routerMapMutex_);
346     if (!routerMap_.count(uid)) {
347         AUDIO_INFO_LOG("GetSelectedDeviceInfo no such uid[%{public}d]", uid);
348         return "";
349     }
350     std::string selectedDevice = "";
351     if (routerMap_[uid].second == pid) {
352         selectedDevice = routerMap_[uid].first;
353     } else if (routerMap_[uid].second == G_UNKNOWN_PID) {
354         routerMap_[uid].second = pid;
355         selectedDevice = routerMap_[uid].first;
356     } else {
357         AUDIO_INFO_LOG("GetSelectedDeviceInfo: uid[%{public}d] changed pid, get local as defalut", uid);
358         routerMap_.erase(uid);
359         selectedDevice = LOCAL_NETWORK_ID;
360     }
361 
362     if (LOCAL_NETWORK_ID == selectedDevice) {
363         AUDIO_INFO_LOG("GetSelectedDeviceInfo: uid[%{public}d]-->local.", uid);
364         return "";
365     }
366     // check if connected.
367     bool isConnected = false;
368     for (auto device : connectedDevices_) {
369         if (GetRemoteModuleName(device->networkId_, device->deviceRole_) == selectedDevice) {
370             isConnected = true;
371             break;
372         }
373     }
374 
375     if (isConnected) {
376         AUDIO_INFO_LOG("GetSelectedDeviceInfo result[%{public}s]", selectedDevice.c_str());
377         return selectedDevice;
378     } else {
379         routerMap_.erase(uid);
380         AUDIO_INFO_LOG("GetSelectedDeviceInfo device already disconnected.");
381         return "";
382     }
383 }
384 
NotifyRemoteRenderState(std::string networkId,std::string condition,std::string value)385 void AudioPolicyService::NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value)
386 {
387     AUDIO_INFO_LOG("NotifyRemoteRenderState device<%{public}s> condition:%{public}s value:%{public}s",
388         networkId.c_str(), condition.c_str(), value.c_str());
389 
390     vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
391     vector<SinkInput> targetSinkInputs = {};
392     for (auto sinkInput : sinkInputs) {
393         if (sinkInput.sinkName == networkId) {
394             targetSinkInputs.push_back(sinkInput);
395         }
396     }
397     AUDIO_DEBUG_LOG("NotifyRemoteRenderState move [%{public}zu] of all [%{public}zu]sink-inputs to local.",
398         targetSinkInputs.size(), sinkInputs.size());
399     sptr<AudioDeviceDescriptor> localDevice = new(std::nothrow) AudioDeviceDescriptor();
400     if (localDevice == nullptr) {
401         AUDIO_ERR_LOG("Device error: null device.");
402         return;
403     }
404     localDevice->networkId_ = LOCAL_NETWORK_ID;
405     localDevice->deviceRole_ = DeviceRole::OUTPUT_DEVICE;
406     localDevice->deviceType_ = DeviceType::DEVICE_TYPE_SPEAKER;
407 
408     int32_t ret = MoveToLocalOutputDevice(targetSinkInputs, localDevice);
409     CHECK_AND_RETURN_LOG((ret == SUCCESS), "MoveToLocalOutputDevice failed!");
410 
411     // Suspend device, notify audio stream manager that device has been changed.
412     ret = audioPolicyManager_.SuspendAudioDevice(networkId, true);
413     CHECK_AND_RETURN_LOG((ret == SUCCESS), "SuspendAudioDevice failed!");
414 
415     std::vector<sptr<AudioDeviceDescriptor>> desc = {};
416     desc.push_back(localDevice);
417     UpdateTrackerDeviceChange(desc);
418     OnPreferredOutputDeviceUpdated(currentActiveDevice_, LOCAL_NETWORK_ID);
419     AUDIO_DEBUG_LOG("NotifyRemoteRenderState success");
420 }
421 
IsDeviceConnected(sptr<AudioDeviceDescriptor> & audioDeviceDescriptors) const422 bool AudioPolicyService::IsDeviceConnected(sptr<AudioDeviceDescriptor> &audioDeviceDescriptors) const
423 {
424     size_t connectedDevicesNum = connectedDevices_.size();
425     for (size_t i = 0; i < connectedDevicesNum; i++) {
426         if (connectedDevices_[i] != nullptr) {
427             if (connectedDevices_[i]->deviceRole_ == audioDeviceDescriptors->deviceRole_
428                 && connectedDevices_[i]->deviceType_ == audioDeviceDescriptors->deviceType_
429                 && connectedDevices_[i]->interruptGroupId_ == audioDeviceDescriptors->interruptGroupId_
430                 && connectedDevices_[i]->volumeGroupId_ == audioDeviceDescriptors->volumeGroupId_
431                 && connectedDevices_[i]->networkId_ == audioDeviceDescriptors->networkId_) {
432                 return true;
433             }
434         }
435     }
436     return false;
437 }
438 
DeviceParamsCheck(DeviceRole targetRole,std::vector<sptr<AudioDeviceDescriptor>> & audioDeviceDescriptors) const439 int32_t AudioPolicyService::DeviceParamsCheck(DeviceRole targetRole,
440     std::vector<sptr<AudioDeviceDescriptor>> &audioDeviceDescriptors) const
441 {
442     size_t targetSize = audioDeviceDescriptors.size();
443     if (targetSize != 1) {
444         AUDIO_ERR_LOG("Device error: size[%{public}zu]", targetSize);
445         return ERR_INVALID_OPERATION;
446     }
447 
448     bool isDeviceTypeCorrect = false;
449     if (targetRole == DeviceRole::OUTPUT_DEVICE) {
450         isDeviceTypeCorrect = IsOutputDevice(audioDeviceDescriptors[0]->deviceType_) &&
451             IsDeviceConnected(audioDeviceDescriptors[0]);
452     } else if (targetRole == DeviceRole::INPUT_DEVICE) {
453         isDeviceTypeCorrect = IsInputDevice(audioDeviceDescriptors[0]->deviceType_) &&
454             IsDeviceConnected(audioDeviceDescriptors[0]);
455     }
456 
457     if (audioDeviceDescriptors[0]->deviceRole_ != targetRole || !isDeviceTypeCorrect) {
458         AUDIO_ERR_LOG("Device error: size[%{public}zu] deviceRole[%{public}d]", targetSize,
459             static_cast<int32_t>(audioDeviceDescriptors[0]->deviceRole_));
460         return ERR_INVALID_OPERATION;
461     }
462     return SUCCESS;
463 }
464 
SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)465 int32_t AudioPolicyService::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
466     std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
467 {
468     AUDIO_INFO_LOG("SelectOutputDevice start for uid[%{public}d]", audioRendererFilter->uid);
469     // check size == 1 && output device
470     int32_t res = DeviceParamsCheck(DeviceRole::OUTPUT_DEVICE, audioDeviceDescriptors);
471     CHECK_AND_RETURN_RET_LOG(res == SUCCESS, res, "DeviceParamsCheck no success");
472 
473     std::string networkId = audioDeviceDescriptors[0]->networkId_;
474     DeviceType deviceType = audioDeviceDescriptors[0]->deviceType_;
475 
476     if (networkId == LOCAL_NETWORK_ID) {
477         UpdateOutputDeviceSelectedByCalling(deviceType);
478     }
479     // switch between local devices
480     if (!isCurrentRemoteRenderer && networkId == LOCAL_NETWORK_ID && currentActiveDevice_ != deviceType) {
481         if (deviceType == DeviceType::DEVICE_TYPE_DEFAULT) {
482             deviceType = FetchHighPriorityDevice(true);
483         }
484         return SelectNewDevice(DeviceRole::OUTPUT_DEVICE, deviceType);
485     }
486 
487     int32_t targetUid = audioRendererFilter->uid;
488     AudioStreamType targetStreamType = audioRendererFilter->streamType;
489     // move all sink-input.
490     bool moveAll = false;
491     if (targetUid == -1) {
492         AUDIO_INFO_LOG("Move all sink inputs.");
493         moveAll = true;
494         std::lock_guard<std::mutex> lock(routerMapMutex_);
495         routerMap_.clear();
496     }
497 
498     // find sink-input id with audioRendererFilter
499     std::vector<SinkInput> targetSinkInputs = {};
500     vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
501 
502     for (size_t i = 0; i < sinkInputs.size(); i++) {
503         if (sinkInputs[i].uid == dAudioClientUid) {
504             AUDIO_INFO_LOG("Find sink-input with daudio[%{public}d]", sinkInputs[i].pid);
505             continue;
506         }
507         if (sinkInputs[i].streamType == STREAM_DEFAULT) {
508             AUDIO_INFO_LOG("Sink-input[%{public}zu] of effect sink, don't move", i);
509             continue;
510         }
511         AUDIO_DEBUG_LOG("sinkinput[%{public}zu]:%{public}s", i, PrintSinkInput(sinkInputs[i]).c_str());
512         if (moveAll || (targetUid == sinkInputs[i].uid && targetStreamType == sinkInputs[i].streamType)) {
513             targetSinkInputs.push_back(sinkInputs[i]);
514         }
515     }
516 
517     // move target uid, but no stream played yet, record the routing info for first start.
518     if (!moveAll && targetSinkInputs.size() == 0) {
519         return RememberRoutingInfo(audioRendererFilter, audioDeviceDescriptors[0]);
520     }
521 
522     auto ret = (networkId == LOCAL_NETWORK_ID) ? MoveToLocalOutputDevice(targetSinkInputs, audioDeviceDescriptors[0]):
523                                                  MoveToRemoteOutputDevice(targetSinkInputs, audioDeviceDescriptors[0]);
524     UpdateTrackerDeviceChange(audioDeviceDescriptors);
525     OnPreferredOutputDeviceUpdated(currentActiveDevice_, networkId);
526     AUDIO_DEBUG_LOG("SelectOutputDevice result[%{public}d], [%{public}zu] moved.", ret, targetSinkInputs.size());
527     return ret;
528 }
529 
530 
RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter,sptr<AudioDeviceDescriptor> deviceDescriptor)531 int32_t AudioPolicyService::RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter,
532     sptr<AudioDeviceDescriptor> deviceDescriptor)
533 {
534     AUDIO_INFO_LOG("RememberRoutingInfo for uid[%{public}d] device[%{public}s]", audioRendererFilter->uid,
535         deviceDescriptor->networkId_.c_str());
536     if (deviceDescriptor->networkId_ == LOCAL_NETWORK_ID) {
537         std::lock_guard<std::mutex> lock(routerMapMutex_);
538         routerMap_[audioRendererFilter->uid] = std::pair(LOCAL_NETWORK_ID, G_UNKNOWN_PID);
539         return SUCCESS;
540     }
541     // remote device.
542     std::string networkId = deviceDescriptor->networkId_;
543     DeviceRole deviceRole = deviceDescriptor->deviceRole_;
544 
545     std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
546     if (!IOHandles_.count(moduleName)) {
547         AUDIO_ERR_LOG("Device error: no such device:%{public}s", networkId.c_str());
548         return ERR_INVALID_PARAM;
549     }
550     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
551     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
552     int32_t ret = gsp->CheckRemoteDeviceState(networkId, deviceRole, true);
553     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!");
554 
555     std::lock_guard<std::mutex> lock(routerMapMutex_);
556     routerMap_[audioRendererFilter->uid] = std::pair(moduleName, G_UNKNOWN_PID);
557     return SUCCESS;
558 }
559 
MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,sptr<AudioDeviceDescriptor> localDeviceDescriptor)560 int32_t AudioPolicyService::MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,
561     sptr<AudioDeviceDescriptor> localDeviceDescriptor)
562 {
563     AUDIO_INFO_LOG("MoveToLocalOutputDevice for [%{public}zu] sink-inputs", sinkInputIds.size());
564     // check
565     if (LOCAL_NETWORK_ID != localDeviceDescriptor->networkId_) {
566         AUDIO_ERR_LOG("MoveToLocalOutputDevice failed: not a local device.");
567         return ERR_INVALID_OPERATION;
568     }
569 
570     DeviceType localDeviceType = localDeviceDescriptor->deviceType_;
571     if (localDeviceType != currentActiveDevice_) {
572         AUDIO_WARNING_LOG("MoveToLocalOutputDevice: device[%{public}d] not active, use device[%{public}d] instead.",
573             static_cast<int32_t>(localDeviceType), static_cast<int32_t>(currentActiveDevice_));
574     }
575 
576     // start move.
577     uint32_t sinkId = -1; // invalid sink id, use sink name instead.
578     std::string sinkName = GetPortName(currentActiveDevice_);
579     for (size_t i = 0; i < sinkInputIds.size(); i++) {
580         if (audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, sinkName) != SUCCESS) {
581             AUDIO_ERR_LOG("move [%{public}d] to local failed", sinkInputIds[i].streamId);
582             return ERROR;
583         }
584         std::lock_guard<std::mutex> lock(routerMapMutex_);
585         routerMap_[sinkInputIds[i].uid] = std::pair(LOCAL_NETWORK_ID, sinkInputIds[i].pid);
586     }
587 
588     isCurrentRemoteRenderer = false;
589     return SUCCESS;
590 }
591 
OpenRemoteAudioDevice(std::string networkId,DeviceRole deviceRole,DeviceType deviceType,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)592 int32_t AudioPolicyService::OpenRemoteAudioDevice(std::string networkId, DeviceRole deviceRole, DeviceType deviceType,
593     sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
594 {
595     // open the test device. We should open it when device is online.
596     std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
597     AudioModuleInfo remoteDeviceInfo = ConstructRemoteAudioModuleInfo(networkId, deviceRole, deviceType);
598     AudioIOHandle remoteIOIdx = audioPolicyManager_.OpenAudioPort(remoteDeviceInfo);
599     AUDIO_DEBUG_LOG("OpenAudioPort remoteIOIdx %{public}d", remoteIOIdx);
600     CHECK_AND_RETURN_RET_LOG(remoteIOIdx != OPEN_PORT_FAILURE, ERR_INVALID_HANDLE, "OpenAudioPort failed %{public}d",
601         remoteIOIdx);
602     IOHandles_[moduleName] = remoteIOIdx;
603 
604     // If device already in list, remove it else do not modify the list.
605     auto isPresent = [&deviceType, &networkId] (const sptr<AudioDeviceDescriptor> &descriptor) {
606         return descriptor->deviceType_ == deviceType && descriptor->networkId_ == networkId;
607     };
608 
609     std::lock_guard<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_);
610     connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent),
611         connectedDevices_.end());
612     UpdateDisplayName(remoteDeviceDescriptor);
613     connectedDevices_.insert(connectedDevices_.begin(), remoteDeviceDescriptor);
614     return SUCCESS;
615 }
616 
MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)617 int32_t AudioPolicyService::MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,
618     sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
619 {
620     AUDIO_INFO_LOG("MoveToRemoteOutputDevice for [%{public}zu] sink-inputs", sinkInputIds.size());
621 
622     std::string networkId = remoteDeviceDescriptor->networkId_;
623     DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_;
624     DeviceType deviceType = remoteDeviceDescriptor->deviceType_;
625 
626     if (networkId == LOCAL_NETWORK_ID) { // check: networkid
627         AUDIO_ERR_LOG("MoveToRemoteOutputDevice failed: not a remote device.");
628         return ERR_INVALID_OPERATION;
629     }
630 
631     uint32_t sinkId = -1; // invalid sink id, use sink name instead.
632     std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
633     if (IOHandles_.count(moduleName)) {
634         IOHandles_[moduleName]; // mIOHandle is module id, not equal to sink id.
635     } else {
636         AUDIO_ERR_LOG("no such device.");
637         if (!isOpenRemoteDevice) {
638             return ERR_INVALID_PARAM;
639         } else {
640             return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor);
641         }
642     }
643 
644     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
645     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
646     CHECK_AND_RETURN_RET_LOG((gsp->CheckRemoteDeviceState(networkId, deviceRole, true) == SUCCESS),
647         ERR_OPERATION_FAILED, "remote device state is invalid!");
648 
649     // start move.
650     for (size_t i = 0; i < sinkInputIds.size(); i++) {
651         if (audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId,
652             sinkId, moduleName) != SUCCESS) {
653             AUDIO_ERR_LOG("move [%{public}d] failed", sinkInputIds[i].streamId);
654             return ERROR;
655         }
656         std::lock_guard<std::mutex> lock(routerMapMutex_);
657         routerMap_[sinkInputIds[i].uid] = std::pair(moduleName, sinkInputIds[i].pid);
658     }
659 
660     if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) {
661         AUDIO_WARNING_LOG("Not defult type[%{public}d] on device:[%{public}s]", deviceType, networkId.c_str());
662     }
663     isCurrentRemoteRenderer = true;
664     return SUCCESS;
665 }
666 
PrintSourceOutput(SourceOutput sourceOutput)667 inline std::string PrintSourceOutput(SourceOutput sourceOutput)
668 {
669     std::stringstream value;
670     value << "streamId:[" << sourceOutput.streamId << "] ";
671     value << "streamType:[" << sourceOutput.streamType << "] ";
672     value << "uid:[" << sourceOutput.uid << "] ";
673     value << "pid:[" << sourceOutput.pid << "] ";
674     value << "statusMark:[" << sourceOutput.statusMark << "] ";
675     value << "deviceSourceId:[" << sourceOutput.deviceSourceId << "] ";
676     value << "startTime:[" << sourceOutput.startTime << "]";
677     return value.str();
678 }
679 
SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)680 int32_t AudioPolicyService::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
681     std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
682 {
683     AUDIO_INFO_LOG("Select input device start for uid[%{public}d]", audioCapturerFilter->uid);
684     // check size == 1 && input device
685     int32_t res = DeviceParamsCheck(DeviceRole::INPUT_DEVICE, audioDeviceDescriptors);
686     if (res != SUCCESS) {
687         return res;
688     }
689 
690     std::string networkId = audioDeviceDescriptors[0]->networkId_;
691     DeviceType deviceType = audioDeviceDescriptors[0]->deviceType_;
692 
693     // switch between local devices
694     if (LOCAL_NETWORK_ID == networkId && activeInputDevice_ != deviceType) {
695         if (deviceType == DeviceType::DEVICE_TYPE_DEFAULT) {
696             deviceType = FetchHighPriorityDevice(false);
697         }
698         return SelectNewDevice(DeviceRole::INPUT_DEVICE, deviceType);
699     }
700 
701     if (!remoteCapturerSwitch_) {
702         AUDIO_DEBUG_LOG("remote capturer capbility is not open now.");
703         return SUCCESS;
704     }
705     int32_t targetUid = audioCapturerFilter->uid;
706     // move all source-output.
707     bool moveAll = false;
708     if (targetUid == -1) {
709         AUDIO_DEBUG_LOG("Move all source outputs.");
710         moveAll = true;
711     }
712 
713     // find source-output id with audioCapturerFilter
714     std::vector<uint32_t> targetSourceOutputIds = {};
715     vector<SourceOutput> sourceOutputs = audioPolicyManager_.GetAllSourceOutputs();
716     for (size_t i = 0; i < sourceOutputs.size();i++) {
717         AUDIO_DEBUG_LOG("SourceOutput[%{public}zu]:%{public}s", i, PrintSourceOutput(sourceOutputs[i]).c_str());
718         if (moveAll || (targetUid == sourceOutputs[i].uid)) {
719             targetSourceOutputIds.push_back(sourceOutputs[i].paStreamId);
720         }
721     }
722 
723     int32_t ret = SUCCESS;
724     if (LOCAL_NETWORK_ID == networkId) {
725         ret = MoveToLocalInputDevice(targetSourceOutputIds, audioDeviceDescriptors[0]);
726     } else {
727         ret = MoveToRemoteInputDevice(targetSourceOutputIds, audioDeviceDescriptors[0]);
728     }
729 
730     OnPreferredInputDeviceUpdated(activeInputDevice_, LOCAL_NETWORK_ID);
731     AUDIO_DEBUG_LOG("SelectInputDevice result[%{public}d]", ret);
732     return ret;
733 }
734 
MoveToLocalInputDevice(std::vector<uint32_t> sourceOutputIds,sptr<AudioDeviceDescriptor> localDeviceDescriptor)735 int32_t AudioPolicyService::MoveToLocalInputDevice(std::vector<uint32_t> sourceOutputIds,
736     sptr<AudioDeviceDescriptor> localDeviceDescriptor)
737 {
738     AUDIO_INFO_LOG("MoveToLocalInputDevice start");
739     // check
740     if (LOCAL_NETWORK_ID != localDeviceDescriptor->networkId_) {
741         AUDIO_ERR_LOG("MoveToLocalInputDevice failed: not a local device.");
742         return ERR_INVALID_OPERATION;
743     }
744 
745     DeviceType localDeviceType = localDeviceDescriptor->deviceType_;
746     if (localDeviceType != activeInputDevice_) {
747         AUDIO_WARNING_LOG("MoveToLocalInputDevice: device[%{public}d] not active, use device[%{public}d] instead.",
748             static_cast<int32_t>(localDeviceType), static_cast<int32_t>(activeInputDevice_));
749     }
750 
751     // start move.
752     uint32_t sourceId = -1; // invalid source id, use source name instead.
753     std::string sourceName = GetPortName(activeInputDevice_);
754     for (size_t i = 0; i < sourceOutputIds.size(); i++) {
755         if (audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputIds[i], sourceId, sourceName) != SUCCESS) {
756             AUDIO_DEBUG_LOG("move [%{public}d] to local failed", sourceOutputIds[i]);
757             return ERROR;
758         }
759     }
760 
761     return SUCCESS;
762 }
763 
MoveToRemoteInputDevice(std::vector<uint32_t> sourceOutputIds,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)764 int32_t AudioPolicyService::MoveToRemoteInputDevice(std::vector<uint32_t> sourceOutputIds,
765     sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
766 {
767     AUDIO_INFO_LOG("MoveToRemoteInputDevice start");
768 
769     std::string networkId = remoteDeviceDescriptor->networkId_;
770     DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_;
771     DeviceType deviceType = remoteDeviceDescriptor->deviceType_;
772 
773     if (networkId == LOCAL_NETWORK_ID) { // check: networkid
774         AUDIO_ERR_LOG("MoveToRemoteInputDevice failed: not a remote device.");
775         return ERR_INVALID_OPERATION;
776     }
777 
778     uint32_t sourceId = -1; // invalid sink id, use sink name instead.
779     std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
780     if (IOHandles_.count(moduleName)) {
781         IOHandles_[moduleName]; // mIOHandle is module id, not equal to sink id.
782     } else {
783         AUDIO_ERR_LOG("no such device.");
784         if (!isOpenRemoteDevice) {
785             return ERR_INVALID_PARAM;
786         } else {
787             return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor);
788         }
789     }
790 
791     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
792     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
793     CHECK_AND_RETURN_RET_LOG((gsp->CheckRemoteDeviceState(networkId, deviceRole, true) == SUCCESS),
794         ERR_OPERATION_FAILED, "remote device state is invalid!");
795 
796     // start move.
797     for (size_t i = 0; i < sourceOutputIds.size(); i++) {
798         if (audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputIds[i], sourceId, moduleName) != SUCCESS) {
799             AUDIO_DEBUG_LOG("move [%{public}d] failed", sourceOutputIds[i]);
800             return ERROR;
801         }
802     }
803 
804     if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) {
805         AUDIO_DEBUG_LOG("Not defult type[%{public}d] on device:[%{public}s]", deviceType, networkId.c_str());
806     }
807     return SUCCESS;
808 }
809 
IsStreamActive(AudioStreamType streamType) const810 bool AudioPolicyService::IsStreamActive(AudioStreamType streamType) const
811 {
812     if (streamType == STREAM_VOICE_CALL && audioScene_ == AUDIO_SCENE_PHONE_CALL) {
813         return true;
814     }
815 
816     return streamCollector_.IsStreamActive(streamType);
817 }
818 
GetPortName(InternalDeviceType deviceType)819 std::string AudioPolicyService::GetPortName(InternalDeviceType deviceType)
820 {
821     std::string portName = PORT_NONE;
822     switch (deviceType) {
823         case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
824             portName = BLUETOOTH_SPEAKER;
825             break;
826         case InternalDeviceType::DEVICE_TYPE_EARPIECE:
827         case InternalDeviceType::DEVICE_TYPE_SPEAKER:
828         case InternalDeviceType::DEVICE_TYPE_WIRED_HEADSET:
829         case InternalDeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
830         case InternalDeviceType::DEVICE_TYPE_USB_HEADSET:
831         case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
832             portName = PRIMARY_SPEAKER;
833             break;
834         case InternalDeviceType::DEVICE_TYPE_MIC:
835             portName = PRIMARY_MIC;
836             break;
837         case InternalDeviceType::DEVICE_TYPE_WAKEUP:
838             portName = PRIMARY_WAKEUP;
839             break;
840         case InternalDeviceType::DEVICE_TYPE_FILE_SINK:
841             portName = FILE_SINK;
842             break;
843         case InternalDeviceType::DEVICE_TYPE_FILE_SOURCE:
844             portName = FILE_SOURCE;
845             break;
846         default:
847             portName = PORT_NONE;
848             break;
849     }
850 
851     AUDIO_INFO_LOG("port name is %{public}s", portName.c_str());
852     return portName;
853 }
854 
855 // private method
ConstructRemoteAudioModuleInfo(std::string networkId,DeviceRole deviceRole,DeviceType deviceType)856 AudioModuleInfo AudioPolicyService::ConstructRemoteAudioModuleInfo(std::string networkId, DeviceRole deviceRole,
857     DeviceType deviceType)
858 {
859     AudioModuleInfo audioModuleInfo = {};
860     if (deviceRole == DeviceRole::OUTPUT_DEVICE) {
861         audioModuleInfo.lib = "libmodule-hdi-sink.z.so";
862         audioModuleInfo.format = "s16le"; // 16bit little endian
863         audioModuleInfo.fixedLatency = "1"; // here we need to set latency fixed for a fixed buffer size.
864     } else if (deviceRole == DeviceRole::INPUT_DEVICE) {
865         audioModuleInfo.lib = "libmodule-hdi-source.z.so";
866         audioModuleInfo.format = "s16le"; // we assume it is bigger endian
867     } else {
868         AUDIO_ERR_LOG("Invalid flag provided %{public}d", static_cast<int32_t>(deviceType));
869     }
870 
871     // used as "sink_name" in hdi_sink.c, hope we could use name to find target sink.
872     audioModuleInfo.name = GetRemoteModuleName(networkId, deviceRole);
873     audioModuleInfo.networkId = networkId;
874 
875     std::stringstream typeValue;
876     typeValue << static_cast<int32_t>(deviceType);
877     audioModuleInfo.deviceType = typeValue.str();
878 
879     audioModuleInfo.adapterName = "remote";
880     audioModuleInfo.className = "remote"; // used in renderer_sink_adapter.c
881     audioModuleInfo.fileName = "remote_dump_file";
882 
883     audioModuleInfo.channels = "2";
884     audioModuleInfo.rate = "48000";
885     audioModuleInfo.bufferSize = "4096";
886 
887     return audioModuleInfo;
888 }
889 
890 // private method
ConstructWakeUpAudioModuleInfo(int32_t wakeupNo)891 AudioModuleInfo AudioPolicyService::ConstructWakeUpAudioModuleInfo(int32_t wakeupNo)
892 {
893     AudioModuleInfo audioModuleInfo = {};
894     audioModuleInfo.lib = "libmodule-hdi-source.z.so";
895     audioModuleInfo.format = "s16le";
896 
897     audioModuleInfo.name = WAKEUP_NAMES[wakeupNo];
898     audioModuleInfo.networkId = "LocalDevice";
899 
900     audioModuleInfo.adapterName = "primary";
901     audioModuleInfo.className = "primary";
902     audioModuleInfo.fileName = "";
903 
904     audioModuleInfo.channels = "1";
905     audioModuleInfo.rate = "16000";
906     audioModuleInfo.bufferSize = "1280";
907     audioModuleInfo.OpenMicSpeaker = "1";
908 
909     audioModuleInfo.sourceType = std::to_string(SourceType::SOURCE_TYPE_WAKEUP);
910     return audioModuleInfo;
911 }
912 
OnPreferredOutputDeviceUpdated(DeviceType deviceType,std::string networkId)913 void AudioPolicyService::OnPreferredOutputDeviceUpdated(DeviceType deviceType, std::string networkId)
914 {
915     Trace trace("AudioPolicyService::OnPreferredOutputDeviceUpdated:" + std::to_string(deviceType));
916     AUDIO_INFO_LOG("Entered %{public}s", __func__);
917 
918     for (auto it = preferredOutputDeviceCbsMap_.begin(); it != preferredOutputDeviceCbsMap_.end(); ++it) {
919         AudioRendererInfo rendererInfo;
920         auto deviceDescs = GetPreferredOutputDeviceDescriptors(rendererInfo);
921         if (!(it->second->hasBTPermission_)) {
922             UpdateDescWhenNoBTPermission(deviceDescs);
923         }
924         it->second->OnPreferredOutputDeviceUpdated(deviceDescs);
925     }
926     UpdateEffectDefaultSink(deviceType);
927 }
928 
OnPreferredInputDeviceUpdated(DeviceType deviceType,std::string networkId)929 void AudioPolicyService::OnPreferredInputDeviceUpdated(DeviceType deviceType, std::string networkId)
930 {
931     AUDIO_INFO_LOG("Entered %{public}s", __func__);
932 
933     std::lock_guard<std::mutex> lock(preferredInputMapMutex_);
934     for (auto it = preferredInputDeviceCbsMap_.begin(); it != preferredInputDeviceCbsMap_.end(); ++it) {
935         AudioCapturerInfo captureInfo;
936         auto deviceDescs = GetPreferredInputDeviceDescriptors(captureInfo);
937         if (!(it->second->hasBTPermission_)) {
938             UpdateDescWhenNoBTPermission(deviceDescs);
939         }
940         it->second->OnPreferredInputDeviceUpdated(deviceDescs);
941     }
942 }
943 
OnPreferredDeviceUpdated(DeviceType activeOutputDevice,DeviceType activeInputDevice)944 void AudioPolicyService::OnPreferredDeviceUpdated(DeviceType activeOutputDevice, DeviceType activeInputDevice)
945 {
946     OnPreferredOutputDeviceUpdated(activeOutputDevice, LOCAL_NETWORK_ID);
947     OnPreferredInputDeviceUpdated(activeInputDevice, LOCAL_NETWORK_ID);
948 }
949 
SetWakeUpAudioCapturer(InternalAudioCapturerOptions options)950 int32_t AudioPolicyService::SetWakeUpAudioCapturer([[maybe_unused]] InternalAudioCapturerOptions options)
951 {
952     AUDIO_INFO_LOG("Entered %{public}s", __func__);
953 
954     int32_t wakeupNo = 0;
955     {
956         std::lock_guard<std::mutex> lock(wakeupCountMutex_);
957         if (wakeupCount_ < 0) {
958             AUDIO_ERR_LOG("wakeupCount_ = %{public}d", wakeupCount_);
959             wakeupCount_ = 0;
960         }
961         if (wakeupCount_ >= WAKEUP_LIMIT) {
962             return ERROR;
963         }
964         wakeupNo = wakeupCount_;
965         wakeupCount_++;
966     }
967 
968     AudioModuleInfo moduleInfo = ConstructWakeUpAudioModuleInfo(wakeupNo);
969     AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
970     CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
971         "OpenAudioPort failed %{public}d", ioHandle);
972 
973     {
974         std::lock_guard<std::mutex> lck(ioHandlesMutex_);
975         IOHandles_[moduleInfo.name] = ioHandle;
976     }
977 
978     AUDIO_DEBUG_LOG("SetWakeUpAudioCapturer Active Success!");
979     return wakeupNo;
980 }
981 
CloseWakeUpAudioCapturer()982 int32_t AudioPolicyService::CloseWakeUpAudioCapturer()
983 {
984     AUDIO_INFO_LOG("Entered %{public}s", __func__);
985 
986     {
987         std::lock_guard<std::mutex> lock(wakeupCountMutex_);
988         wakeupCount_--;
989         if (wakeupCount_ > 0) {
990             return SUCCESS;
991         }
992         for (auto key : WAKEUP_NAMES) {
993             AudioIOHandle ioHandle;
994             {
995                 std::lock_guard<std::mutex> lck(ioHandlesMutex_);
996                 auto ioHandleIter = IOHandles_.find(std::string(key));
997                 if (ioHandleIter == IOHandles_.end()) {
998                     AUDIO_ERR_LOG("CloseWakeUpAudioCapturer failed");
999                     continue;
1000                 } else {
1001                     ioHandle = ioHandleIter->second;
1002                     IOHandles_.erase(ioHandleIter);
1003                 }
1004             }
1005             audioPolicyManager_.CloseAudioPort(ioHandle);
1006         }
1007     }
1008     return SUCCESS;
1009 }
1010 
GetDevices(DeviceFlag deviceFlag)1011 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDevices(DeviceFlag deviceFlag)
1012 {
1013     AUDIO_DEBUG_LOG("Entered %{public}s", __func__);
1014 
1015     std::shared_lock<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_);
1016 
1017     std::vector<sptr<AudioDeviceDescriptor>> deviceList = {};
1018 
1019     if (deviceFlag < DeviceFlag::OUTPUT_DEVICES_FLAG || deviceFlag > DeviceFlag::ALL_L_D_DEVICES_FLAG) {
1020         AUDIO_ERR_LOG("Invalid flag provided %{public}d", deviceFlag);
1021         return deviceList;
1022     }
1023 
1024     if (deviceFlag == DeviceFlag::ALL_L_D_DEVICES_FLAG) {
1025         return connectedDevices_;
1026     }
1027 
1028     for (const auto& device : connectedDevices_) {
1029         if (device == nullptr) {
1030             continue;
1031         }
1032         bool filterAllLocal = deviceFlag == DeviceFlag::ALL_DEVICES_FLAG && device->networkId_ == LOCAL_NETWORK_ID;
1033         bool filterLocalOutput = deviceFlag == DeviceFlag::OUTPUT_DEVICES_FLAG
1034             && device->networkId_ == LOCAL_NETWORK_ID
1035             && device->deviceRole_ == DeviceRole::OUTPUT_DEVICE;
1036         bool filterLocalInput = deviceFlag == DeviceFlag::INPUT_DEVICES_FLAG
1037             && device->networkId_ == LOCAL_NETWORK_ID
1038             && device->deviceRole_ == DeviceRole::INPUT_DEVICE;
1039 
1040         bool filterAllRemote = deviceFlag == DeviceFlag::ALL_DISTRIBUTED_DEVICES_FLAG
1041             && device->networkId_ != LOCAL_NETWORK_ID;
1042         bool filterRemoteOutput = deviceFlag == DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG
1043             && device->networkId_ != LOCAL_NETWORK_ID
1044             && device->deviceRole_ == DeviceRole::OUTPUT_DEVICE;
1045         bool filterRemoteInput = deviceFlag == DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG
1046             && device->networkId_ != LOCAL_NETWORK_ID
1047             && device->deviceRole_ == DeviceRole::INPUT_DEVICE;
1048 
1049         if (filterAllLocal || filterLocalOutput || filterLocalInput || filterAllRemote || filterRemoteOutput
1050             || filterRemoteInput) {
1051             sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*device);
1052             deviceList.push_back(devDesc);
1053         }
1054     }
1055 
1056     AUDIO_DEBUG_LOG("GetDevices list size = [%{public}zu]", deviceList.size());
1057     return deviceList;
1058 }
1059 
GetPreferredOutputDeviceDescriptors(AudioRendererInfo & rendererInfo,std::string networkId)1060 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredOutputDeviceDescriptors(
1061     AudioRendererInfo &rendererInfo, std::string networkId)
1062 {
1063     std::vector<sptr<AudioDeviceDescriptor>> deviceList = {};
1064     for (const auto& device : connectedDevices_) {
1065         if (device == nullptr) {
1066             continue;
1067         }
1068         bool filterLocalOutput = ((currentActiveDevice_ == device->deviceType_)
1069             && (device->networkId_ == LOCAL_NETWORK_ID)
1070             && (device->deviceRole_ == DeviceRole::OUTPUT_DEVICE));
1071         if (!isCurrentRemoteRenderer && filterLocalOutput && networkId == LOCAL_NETWORK_ID) {
1072             sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*device);
1073             deviceList.push_back(devDesc);
1074         }
1075 
1076         bool filterRemoteOutput = ((device->networkId_ != networkId)
1077             && (device->deviceRole_ == DeviceRole::OUTPUT_DEVICE));
1078         if (isCurrentRemoteRenderer && filterRemoteOutput) {
1079             sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*device);
1080             deviceList.push_back(devDesc);
1081         }
1082     }
1083 
1084     return deviceList;
1085 }
1086 
GetPreferredInputDeviceDescriptors(AudioCapturerInfo & captureInfo,std::string networkId)1087 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredInputDeviceDescriptors(
1088     AudioCapturerInfo &captureInfo, std::string networkId)
1089 {
1090     std::vector<sptr<AudioDeviceDescriptor>> deviceList = {};
1091     for (const auto& device : connectedDevices_) {
1092         if (device == nullptr) {
1093             continue;
1094         }
1095         bool filterLocalInput = ((activeInputDevice_ == device->deviceType_)
1096             && (device->networkId_ == LOCAL_NETWORK_ID)
1097             && (device->deviceRole_ == DeviceRole::INPUT_DEVICE));
1098         if (!remoteCapturerSwitch_ && filterLocalInput && networkId == LOCAL_NETWORK_ID) {
1099             sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*device);
1100             deviceList.push_back(devDesc);
1101         }
1102 
1103         bool filterRemoteInput = ((device->networkId_ != networkId)
1104             && (device->deviceRole_ == DeviceRole::INPUT_DEVICE));
1105         if (remoteCapturerSwitch_ && filterRemoteInput) {
1106             sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*device);
1107             deviceList.push_back(devDesc);
1108         }
1109     }
1110 
1111     return deviceList;
1112 }
1113 
FetchHighPriorityDevice(bool isOutputDevice=true)1114 DeviceType AudioPolicyService::FetchHighPriorityDevice(bool isOutputDevice = true)
1115 {
1116     AUDIO_DEBUG_LOG("Entered %{public}s", __func__);
1117     DeviceType priorityDevice = isOutputDevice ? DEVICE_TYPE_SPEAKER : DEVICE_TYPE_MIC;
1118     std::vector<DeviceType> priorityList = isOutputDevice ? outputPriorityList_ : inputPriorityList_;
1119     for (const auto &device : priorityList) {
1120         auto isPresent = [&device, this] (const sptr<AudioDeviceDescriptor> &desc) {
1121             CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
1122             if ((audioScene_ == AUDIO_SCENE_PHONE_CALL || audioScene_ == AUDIO_SCENE_PHONE_CHAT) &&
1123                 (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP)) {
1124                 return false;
1125             } else {
1126                 return desc->deviceType_ == device;
1127             }
1128         };
1129 
1130         auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
1131         if (itr != connectedDevices_.end()) {
1132             priorityDevice = (*itr)->deviceType_;
1133             break;
1134         }
1135     }
1136     AUDIO_INFO_LOG("FetchHighPriorityDevice: priorityDevice: %{public}d, currentActiveDevice_: %{public}d",
1137         priorityDevice, currentActiveDevice_);
1138     return priorityDevice;
1139 }
1140 
SetMicrophoneMute(bool isMute)1141 int32_t AudioPolicyService::SetMicrophoneMute(bool isMute)
1142 {
1143     AUDIO_DEBUG_LOG("SetMicrophoneMute state[%{public}d]", isMute);
1144     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
1145     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
1146     int32_t ret = gsp->SetMicrophoneMute(isMute);
1147     if (ret == SUCCESS) {
1148         isMicrophoneMute_ = isMute;
1149     }
1150     return ret;
1151 }
1152 
IsMicrophoneMute()1153 bool AudioPolicyService::IsMicrophoneMute()
1154 {
1155     AUDIO_DEBUG_LOG("Enter IsMicrophoneMute");
1156     return isMicrophoneMute_;
1157 }
1158 
SetSystemSoundUri(const std::string & key,const std::string & uri)1159 int32_t AudioPolicyService::SetSystemSoundUri(const std::string &key, const std::string &uri)
1160 {
1161     return audioPolicyManager_.SetSystemSoundUri(key, uri);
1162 }
1163 
GetSystemSoundUri(const std::string & key)1164 std::string AudioPolicyService::GetSystemSoundUri(const std::string &key)
1165 {
1166     return audioPolicyManager_.GetSystemSoundUri(key);
1167 }
1168 
IsSessionIdValid(int32_t callerUid,int32_t sessionId)1169 bool AudioPolicyService::IsSessionIdValid(int32_t callerUid, int32_t sessionId)
1170 {
1171     AUDIO_INFO_LOG("IsSessionIdValid::callerUid: %{public}d, sessionId: %{public}d", callerUid, sessionId);
1172 
1173     constexpr int32_t mediaUid = 1013; // "uid" : "media"
1174     if (callerUid == mediaUid) {
1175         AUDIO_INFO_LOG("IsSessionIdValid::sessionId:%{public}d is an valid id from media", sessionId);
1176         return true;
1177     }
1178 
1179     return true;
1180 }
1181 
UpdateActiveDeviceRoute(InternalDeviceType deviceType)1182 void UpdateActiveDeviceRoute(InternalDeviceType deviceType)
1183 {
1184     AUDIO_DEBUG_LOG("UpdateActiveDeviceRoute Device type[%{public}d]", deviceType);
1185 
1186     if (g_adProxy == nullptr) {
1187         return;
1188     }
1189     auto ret = SUCCESS;
1190 
1191     switch (deviceType) {
1192         case DEVICE_TYPE_BLUETOOTH_SCO:
1193         case DEVICE_TYPE_USB_HEADSET:
1194         case DEVICE_TYPE_WIRED_HEADSET: {
1195             ret = g_adProxy->UpdateActiveDeviceRoute(deviceType, DeviceFlag::ALL_DEVICES_FLAG);
1196             CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the route for %{public}d", deviceType);
1197             break;
1198         }
1199         case DEVICE_TYPE_WIRED_HEADPHONES:
1200         case DEVICE_TYPE_EARPIECE:
1201         case DEVICE_TYPE_SPEAKER: {
1202             ret = g_adProxy->UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG);
1203             CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the route for %{public}d", deviceType);
1204             break;
1205         }
1206         case DEVICE_TYPE_MIC: {
1207             ret = g_adProxy->UpdateActiveDeviceRoute(deviceType, DeviceFlag::INPUT_DEVICES_FLAG);
1208             CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the route for %{public}d", deviceType);
1209             break;
1210         }
1211         default:
1212             break;
1213     }
1214 }
1215 
ConvertToHDIAudioFormat(AudioSampleFormat sampleFormat)1216 static string ConvertToHDIAudioFormat(AudioSampleFormat sampleFormat)
1217 {
1218     switch (sampleFormat) {
1219         case SAMPLE_U8:
1220             return "u8";
1221         case SAMPLE_S16LE:
1222             return "s16le";
1223         case SAMPLE_S24LE:
1224             return "s24le";
1225         case SAMPLE_S32LE:
1226             return "s32le";
1227         default:
1228             return "";
1229     }
1230 }
1231 
GetSampleFormatValue(AudioSampleFormat sampleFormat)1232 static uint32_t GetSampleFormatValue(AudioSampleFormat sampleFormat)
1233 {
1234     switch (sampleFormat) {
1235         case SAMPLE_U8:
1236             return PCM_8_BIT;
1237         case SAMPLE_S16LE:
1238             return PCM_16_BIT;
1239         case SAMPLE_S24LE:
1240             return PCM_24_BIT;
1241         case SAMPLE_S32LE:
1242             return PCM_32_BIT;
1243         default:
1244             return PCM_16_BIT;
1245     }
1246 }
1247 
SelectNewDevice(DeviceRole deviceRole,DeviceType deviceType)1248 int32_t AudioPolicyService::SelectNewDevice(DeviceRole deviceRole, DeviceType deviceType)
1249 {
1250     Trace trace("AudioPolicyService::SelectNewDevice:" + std::to_string(deviceType));
1251     int32_t result = SUCCESS;
1252 
1253     if (deviceRole == DeviceRole::OUTPUT_DEVICE) {
1254         std::string activePort = GetPortName(currentActiveDevice_);
1255         AUDIO_INFO_LOG("port %{public}s, active device %{public}d", activePort.c_str(), currentActiveDevice_);
1256         audioPolicyManager_.SuspendAudioDevice(activePort, true);
1257     }
1258 
1259     std::string portName = GetPortName(deviceType);
1260     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, result, "Invalid port name %{public}s", portName.c_str());
1261 
1262     if (deviceRole == DeviceRole::OUTPUT_DEVICE) {
1263         int32_t muteDuration = 200000; // us
1264         std::thread switchThread(&AudioPolicyService::KeepPortMute, this, muteDuration, portName, deviceType);
1265         switchThread.detach(); // add another sleep before switch local can avoid pop in some case
1266     }
1267 
1268     result = audioPolicyManager_.SelectDevice(deviceRole, deviceType, portName);
1269     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, result, "SetDeviceActive failed %{public}d", result);
1270     audioPolicyManager_.SuspendAudioDevice(portName, false);
1271 
1272     if (isUpdateRouteSupported_) {
1273         DeviceFlag deviceFlag = deviceRole == DeviceRole::OUTPUT_DEVICE ? OUTPUT_DEVICES_FLAG : INPUT_DEVICES_FLAG;
1274         const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
1275         CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
1276         gsp->UpdateActiveDeviceRoute(deviceType, deviceFlag);
1277     }
1278 
1279     if (deviceRole == DeviceRole::OUTPUT_DEVICE) {
1280         SetVolumeForSwitchDevice(deviceType);
1281         currentActiveDevice_ = deviceType;
1282         OnPreferredOutputDeviceUpdated(currentActiveDevice_, LOCAL_NETWORK_ID);
1283     } else {
1284         activeInputDevice_ = deviceType;
1285         OnPreferredInputDeviceUpdated(activeInputDevice_, LOCAL_NETWORK_ID);
1286     }
1287     return SUCCESS;
1288 }
1289 
HandleA2dpDevice(DeviceType deviceType)1290 int32_t AudioPolicyService::HandleA2dpDevice(DeviceType deviceType)
1291 {
1292     Trace trace("AudioPolicyService::HandleA2dpDevice");
1293     std::string activePort = GetPortName(currentActiveDevice_);
1294     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1295         auto primaryModulesPos = deviceClassInfo_.find(ClassType::TYPE_A2DP);
1296         if (primaryModulesPos != deviceClassInfo_.end()) {
1297             auto moduleInfoList = primaryModulesPos->second;
1298             for (auto &moduleInfo : moduleInfoList) {
1299                 if (IOHandles_.find(moduleInfo.name) == IOHandles_.end()) {
1300                     AUDIO_INFO_LOG("Load a2dp module [%{public}s]", moduleInfo.name.c_str());
1301                     AudioStreamInfo audioStreamInfo = {};
1302                     GetActiveDeviceStreamInfo(deviceType, audioStreamInfo);
1303                     uint32_t bufferSize = (audioStreamInfo.samplingRate * GetSampleFormatValue(audioStreamInfo.format) *
1304                         audioStreamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR);
1305                     AUDIO_INFO_LOG("a2dp rate: %{public}d, format: %{public}d, channel: %{public}d",
1306                         audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
1307                     moduleInfo.channels = to_string(audioStreamInfo.channels);
1308                     moduleInfo.rate = to_string(audioStreamInfo.samplingRate);
1309                     moduleInfo.format = ConvertToHDIAudioFormat(audioStreamInfo.format);
1310                     moduleInfo.bufferSize = to_string(bufferSize);
1311 
1312                     AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
1313                     CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
1314                         "OpenAudioPort failed %{public}d", ioHandle);
1315                     IOHandles_[moduleInfo.name] = ioHandle;
1316                 }
1317 
1318                 AUDIO_INFO_LOG("port %{public}s, active device %{public}d", activePort.c_str(), currentActiveDevice_);
1319                 audioPolicyManager_.SuspendAudioDevice(activePort, true);
1320             }
1321         }
1322     } else if (currentActiveDevice_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
1323         audioPolicyManager_.SuspendAudioDevice(activePort, true);
1324         int32_t muteDuration =  1000000; // us
1325         std::thread switchThread(&AudioPolicyService::KeepPortMute, this, muteDuration, PRIMARY_SPEAKER, deviceType);
1326         switchThread.detach();
1327         int32_t beforSwitchDelay = 300000;
1328         usleep(beforSwitchDelay);
1329     }
1330 
1331     if (isUpdateRouteSupported_) {
1332         UpdateActiveDeviceRoute(deviceType);
1333     }
1334     SetVolumeForSwitchDevice(deviceType);
1335 
1336     AudioIOHandle ioHandle = GetAudioIOHandle(deviceType);
1337     std::string portName = GetPortName(deviceType);
1338     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, ERR_OPERATION_FAILED, "Invalid port %{public}s", portName.c_str());
1339 
1340     int32_t result = audioPolicyManager_.SetDeviceActive(ioHandle, deviceType, portName, true);
1341     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, result, "SetDeviceActive failed %{public}d", result);
1342     audioPolicyManager_.SuspendAudioDevice(portName, false);
1343 
1344     UpdateInputDeviceInfo(deviceType);
1345 
1346     return SUCCESS;
1347 }
1348 
HandleFileDevice(DeviceType deviceType)1349 int32_t AudioPolicyService::HandleFileDevice(DeviceType deviceType)
1350 {
1351     AUDIO_INFO_LOG("HandleFileDevice");
1352     AudioIOHandle ioHandle = GetAudioIOHandle(deviceType);
1353     std::string portName = GetPortName(deviceType);
1354     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, ERR_OPERATION_FAILED, "Invalid port %{public}s", portName.c_str());
1355 
1356     int32_t result = audioPolicyManager_.SetDeviceActive(ioHandle, deviceType, portName, true);
1357     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, result, "SetDeviceActive failed %{public}d", result);
1358     audioPolicyManager_.SuspendAudioDevice(portName, false);
1359 
1360     if (isUpdateRouteSupported_) {
1361         UpdateActiveDeviceRoute(deviceType);
1362     }
1363 
1364     UpdateInputDeviceInfo(deviceType);
1365     return SUCCESS;
1366 }
1367 
ActivateNewDevice(DeviceType deviceType,bool isSceneActivation=false)1368 int32_t AudioPolicyService::ActivateNewDevice(DeviceType deviceType, bool isSceneActivation = false)
1369 {
1370     AUDIO_INFO_LOG("Switch device: [%{public}d]-->[%{public}d]", currentActiveDevice_, deviceType);
1371     int32_t result = SUCCESS;
1372 
1373     if (currentActiveDevice_ == deviceType) {
1374         return result;
1375     }
1376 
1377     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP || currentActiveDevice_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
1378         result = HandleA2dpDevice(deviceType);
1379         return result;
1380     }
1381 
1382     if (deviceType == DEVICE_TYPE_FILE_SINK || currentActiveDevice_ == DEVICE_TYPE_FILE_SINK) {
1383         result = HandleFileDevice(deviceType);
1384         return result;
1385     }
1386 
1387     std::string portName = GetPortName(deviceType);
1388     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, ERR_OPERATION_FAILED, "Invalid port %{public}s", portName.c_str());
1389     bool isVolumeSwitched = false;
1390     if (isUpdateRouteSupported_ && !isSceneActivation) {
1391         if (GetDeviceRole(deviceType) == OUTPUT_DEVICE) {
1392             int32_t muteDuration = 1200000; // us
1393             std::thread switchThread(&AudioPolicyService::KeepPortMute, this, muteDuration, portName, deviceType);
1394             switchThread.detach();
1395             int32_t beforSwitchDelay = 300000; // 300 ms
1396             usleep(beforSwitchDelay);
1397         }
1398         UpdateActiveDeviceRoute(deviceType);
1399         if (GetDeviceRole(deviceType) == OUTPUT_DEVICE) {
1400             SetVolumeForSwitchDevice(deviceType);
1401             isVolumeSwitched = true;
1402         }
1403     }
1404 
1405     if (GetDeviceRole(deviceType) == OUTPUT_DEVICE && !isVolumeSwitched) {
1406         SetVolumeForSwitchDevice(deviceType);
1407     }
1408 
1409     UpdateInputDeviceInfo(deviceType);
1410 
1411     return SUCCESS;
1412 }
1413 
KeepPortMute(int32_t muteDuration,std::string portName,DeviceType deviceType)1414 void AudioPolicyService::KeepPortMute(int32_t muteDuration, std::string portName, DeviceType deviceType)
1415 {
1416     Trace trace("AudioPolicyService::KeepPortMute:" + portName + " for " + std::to_string(muteDuration) + "us");
1417     AUDIO_INFO_LOG("KeepPortMute %{public}d us for device type[%{public}d]", muteDuration, deviceType);
1418     audioPolicyManager_.SetSinkMute(portName, true);
1419     usleep(muteDuration);
1420     audioPolicyManager_.SetSinkMute(portName, false);
1421 }
1422 
ActivateNewDevice(std::string networkId,DeviceType deviceType,bool isRemote)1423 int32_t AudioPolicyService::ActivateNewDevice(std::string networkId, DeviceType deviceType, bool isRemote)
1424 {
1425     if (isRemote) {
1426         AudioModuleInfo moduleInfo = ConstructRemoteAudioModuleInfo(networkId, GetDeviceRole(deviceType), deviceType);
1427         AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
1428         CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
1429             "OpenAudioPort failed %{public}d", ioHandle);
1430         std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(deviceType));
1431         IOHandles_[moduleName] = ioHandle;
1432     }
1433     return SUCCESS;
1434 }
1435 
SetDeviceActive(InternalDeviceType deviceType,bool active)1436 int32_t AudioPolicyService::SetDeviceActive(InternalDeviceType deviceType, bool active)
1437 {
1438     AUDIO_INFO_LOG("SetDeviceActive: Device type[%{public}d] flag[%{public}d]", deviceType, active);
1439     CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
1440 
1441     int32_t result = SUCCESS;
1442 
1443     if (!active) {
1444         CHECK_AND_RETURN_RET_LOG(deviceType == currentActiveDevice_, SUCCESS, "This device is not active");
1445         deviceType = FetchHighPriorityDevice();
1446     }
1447 
1448     if (deviceType == currentActiveDevice_) {
1449         AUDIO_INFO_LOG("Device already activated %{public}d. No need to activate again", currentActiveDevice_);
1450         return SUCCESS;
1451     }
1452 
1453     // Activate new device if its already connected
1454     auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &desc) {
1455         CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "SetDeviceActive::Invalid device descriptor");
1456         return ((deviceType == desc->deviceType_) || (deviceType == DEVICE_TYPE_FILE_SINK));
1457     };
1458 
1459     auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
1460     if (itr == connectedDevices_.end()) {
1461         AUDIO_ERR_LOG("Requested device not available %{public}d ", deviceType);
1462         return ERR_OPERATION_FAILED;
1463     }
1464 
1465     switch (deviceType) {
1466         case DEVICE_TYPE_EARPIECE:
1467             result = ActivateNewDevice(DEVICE_TYPE_EARPIECE);
1468             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Earpiece activation err %{public}d", result);
1469             result = ActivateNewDevice(DEVICE_TYPE_MIC);
1470             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Microphone activation err %{public}d", result);
1471             break;
1472         case DEVICE_TYPE_SPEAKER:
1473             result = ActivateNewDevice(DEVICE_TYPE_SPEAKER);
1474             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Speaker activation err %{public}d", result);
1475             result = ActivateNewDevice(DEVICE_TYPE_MIC);
1476             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Microphone activation err %{public}d", result);
1477             break;
1478         case DEVICE_TYPE_FILE_SINK:
1479             result = ActivateNewDevice(DEVICE_TYPE_FILE_SINK);
1480             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "FILE_SINK activation err %{public}d", result);
1481             result = ActivateNewDevice(DEVICE_TYPE_FILE_SOURCE);
1482             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "FILE_SOURCE activation err %{public}d", result);
1483             break;
1484         default:
1485             result = ActivateNewDevice(deviceType);
1486             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Activation failed for %{public}d", deviceType);
1487             break;
1488     }
1489 
1490     currentActiveDevice_ = deviceType;
1491     OnPreferredDeviceUpdated(currentActiveDevice_, activeInputDevice_);
1492     return result;
1493 }
1494 
IsDeviceActive(InternalDeviceType deviceType) const1495 bool AudioPolicyService::IsDeviceActive(InternalDeviceType deviceType) const
1496 {
1497     AUDIO_INFO_LOG("Entered AudioPolicyService::%{public}s", __func__);
1498     return currentActiveDevice_ == deviceType;
1499 }
1500 
GetActiveOutputDevice() const1501 DeviceType AudioPolicyService::GetActiveOutputDevice() const
1502 {
1503     return currentActiveDevice_;
1504 }
1505 
GetActiveInputDevice() const1506 DeviceType AudioPolicyService::GetActiveInputDevice() const
1507 {
1508     return activeInputDevice_;
1509 }
1510 
SetRingerMode(AudioRingerMode ringMode)1511 int32_t AudioPolicyService::SetRingerMode(AudioRingerMode ringMode)
1512 {
1513     return audioPolicyManager_.SetRingerMode(ringMode);
1514 }
1515 
GetRingerMode() const1516 AudioRingerMode AudioPolicyService::GetRingerMode() const
1517 {
1518     return audioPolicyManager_.GetRingerMode();
1519 }
1520 
SetAudioScene(AudioScene audioScene)1521 int32_t AudioPolicyService::SetAudioScene(AudioScene audioScene)
1522 {
1523     AUDIO_INFO_LOG("SetAudioScene: %{public}d", audioScene);
1524     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
1525     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
1526     audioScene_ = audioScene;
1527 
1528     if (isUpdateRouteSupported_) {
1529         SetEarpieceState();
1530     }
1531 
1532     DeviceType priorityDev = FetchHighPriorityDevice();
1533 
1534     if (audioScene == AUDIO_SCENE_PHONE_CHAT) {
1535         auto uid = IPCSkeleton::GetCallingUid();
1536         DeviceType device = DEVICE_TYPE_NONE;
1537         {
1538             std::lock_guard<std::mutex> lock(outputDeviceSelectedByCallingMutex_);
1539             if (outputDeviceSelectedByCalling_.count(uid)) {
1540                 device = outputDeviceSelectedByCalling_.at(uid);
1541             }
1542         }
1543 
1544         auto isConnected = [&device] (const sptr<AudioDeviceDescriptor> &desc) {
1545             CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "lambda isConnected: Invalid device descriptor");
1546             if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
1547                 return false;
1548             } else {
1549                 return desc->deviceType_ == device;
1550             }
1551         };
1552 
1553         if (device != DEVICE_TYPE_NONE) {
1554             auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isConnected);
1555             if (itr != connectedDevices_.end()) {
1556                 priorityDev = device;
1557             }
1558         }
1559     }
1560     AUDIO_DEBUG_LOG("Current active device: %{public}d. Priority device: %{public}d",
1561         currentActiveDevice_, priorityDev);
1562 
1563     int32_t result = ActivateNewDevice(priorityDev, true);
1564     CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "Device activation failed [%{public}d]", result);
1565 
1566     currentActiveDevice_ = priorityDev;
1567     AUDIO_DEBUG_LOG("Current active device updates: %{public}d", currentActiveDevice_);
1568     OnPreferredDeviceUpdated(currentActiveDevice_, activeInputDevice_);
1569 
1570     result = gsp->SetAudioScene(audioScene, priorityDev);
1571     CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "SetAudioScene failed [%{public}d]", result);
1572 
1573     return SUCCESS;
1574 }
1575 
SetEarpieceState()1576 void AudioPolicyService::SetEarpieceState()
1577 {
1578     if (audioScene_ == AUDIO_SCENE_PHONE_CALL) {
1579         AUDIO_INFO_LOG("SetEarpieceState: add earpiece device only for [phone], localDevicesType [%{public}s]",
1580             localDevicesType_.c_str());
1581         if (localDevicesType_.compare("phone") != 0) {
1582             return;
1583         }
1584 
1585         // add earpiece to connectedDevices_
1586         auto isPresent = [](const sptr<AudioDeviceDescriptor> &desc) {
1587             CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
1588             return desc->deviceType_ == DEVICE_TYPE_EARPIECE;
1589         };
1590         auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
1591         if (itr == connectedDevices_.end()) {
1592             sptr<AudioDeviceDescriptor> audioDescriptor =
1593                 new (std::nothrow) AudioDeviceDescriptor(DEVICE_TYPE_EARPIECE, OUTPUT_DEVICE);
1594             UpdateDisplayName(audioDescriptor);
1595             connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
1596             AUDIO_INFO_LOG("SetAudioScene: Add earpiece to connectedDevices_");
1597         }
1598 
1599         // add earpiece to outputPriorityList_
1600         auto earpiecePos = find(outputPriorityList_.begin(), outputPriorityList_.end(), DEVICE_TYPE_EARPIECE);
1601         if (earpiecePos == outputPriorityList_.end()) {
1602             outputPriorityList_.insert(outputPriorityList_.end() - PRIORITY_LIST_OFFSET_POSTION,
1603                 DEVICE_TYPE_EARPIECE);
1604             AUDIO_INFO_LOG("SetAudioScene: Add earpiece to outputPriorityList_");
1605         }
1606     } else {
1607         // remove earpiece from connectedDevices_
1608         auto isPresent = [] (const sptr<AudioDeviceDescriptor> &desc) {
1609             CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
1610             return desc->deviceType_ == DEVICE_TYPE_EARPIECE;
1611         };
1612 
1613         std::lock_guard<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_);
1614         auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
1615         if (itr != connectedDevices_.end()) {
1616             connectedDevices_.erase(itr);
1617             AUDIO_INFO_LOG("SetAudioScene: Remove earpiece from connectedDevices_");
1618         }
1619         // remove earpiece from outputPriorityList_
1620         auto earpiecePos = find(outputPriorityList_.begin(), outputPriorityList_.end(), DEVICE_TYPE_EARPIECE);
1621         if (earpiecePos != outputPriorityList_.end()) {
1622             outputPriorityList_.erase(earpiecePos);
1623             AUDIO_INFO_LOG("SetAudioScene: Remove earpiece from outputPriorityList_");
1624         }
1625     }
1626 }
1627 
GetLocalDevicesType()1628 std::string AudioPolicyService::GetLocalDevicesType()
1629 {
1630     return localDevicesType_;
1631 }
1632 
GetAudioScene(bool hasSystemPermission) const1633 AudioScene AudioPolicyService::GetAudioScene(bool hasSystemPermission) const
1634 {
1635     AUDIO_INFO_LOG("GetAudioScene return value: %{public}d", audioScene_);
1636     if (!hasSystemPermission) {
1637         switch (audioScene_) {
1638             case AUDIO_SCENE_RINGING:
1639             case AUDIO_SCENE_PHONE_CALL:
1640                 return AUDIO_SCENE_DEFAULT;
1641             default:
1642                 break;
1643         }
1644     }
1645     return audioScene_;
1646 }
1647 
IsAudioInterruptEnabled() const1648 bool AudioPolicyService::IsAudioInterruptEnabled() const
1649 {
1650     return interruptEnabled_;
1651 }
1652 
OnAudioInterruptEnable(bool enable)1653 void AudioPolicyService::OnAudioInterruptEnable(bool enable)
1654 {
1655     interruptEnabled_ = enable;
1656 }
1657 
OnUpdateRouteSupport(bool isSupported)1658 void AudioPolicyService::OnUpdateRouteSupport(bool isSupported)
1659 {
1660     isUpdateRouteSupported_ = isSupported;
1661 }
1662 
GetActiveDeviceStreamInfo(DeviceType deviceType,AudioStreamInfo & streamInfo)1663 bool AudioPolicyService::GetActiveDeviceStreamInfo(DeviceType deviceType, AudioStreamInfo &streamInfo)
1664 {
1665     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1666         auto streamInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_);
1667         if (streamInfoPos != connectedA2dpDeviceMap_.end()) {
1668             streamInfo.samplingRate = streamInfoPos->second.samplingRate;
1669             streamInfo.format = streamInfoPos->second.format;
1670             streamInfo.channels = streamInfoPos->second.channels;
1671             return true;
1672         }
1673     }
1674 
1675     return false;
1676 }
1677 
IsConfigurationUpdated(DeviceType deviceType,const AudioStreamInfo & streamInfo)1678 bool AudioPolicyService::IsConfigurationUpdated(DeviceType deviceType, const AudioStreamInfo &streamInfo)
1679 {
1680     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1681         AudioStreamInfo audioStreamInfo = {};
1682         if (GetActiveDeviceStreamInfo(deviceType, audioStreamInfo)) {
1683             AUDIO_DEBUG_LOG("Device configurations current rate: %{public}d, format: %{public}d, channel: %{public}d",
1684                 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
1685             AUDIO_DEBUG_LOG("Device configurations updated rate: %{public}d, format: %{public}d, channel: %{public}d",
1686                 streamInfo.samplingRate, streamInfo.format, streamInfo.channels);
1687             if ((audioStreamInfo.samplingRate != streamInfo.samplingRate)
1688                 || (audioStreamInfo.channels != streamInfo.channels)
1689                 || (audioStreamInfo.format != streamInfo.format)) {
1690                 return true;
1691             }
1692         }
1693     }
1694 
1695     return false;
1696 }
1697 
UpdateConnectedDevicesWhenConnecting(const AudioDeviceDescriptor & deviceDescriptor,std::vector<sptr<AudioDeviceDescriptor>> & desc)1698 void AudioPolicyService::UpdateConnectedDevicesWhenConnecting(const AudioDeviceDescriptor &deviceDescriptor,
1699     std::vector<sptr<AudioDeviceDescriptor>> &desc)
1700 {
1701     sptr<AudioDeviceDescriptor> audioDescriptor = nullptr;
1702 
1703     if (IsOutputDevice(deviceDescriptor.deviceType_)) {
1704         AUDIO_INFO_LOG("Filling output device for %{public}d", deviceDescriptor.deviceType_);
1705 
1706         audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(deviceDescriptor);
1707         audioDescriptor->deviceRole_ = OUTPUT_DEVICE;
1708 
1709         // Use speaker streaminfo for all output devices cap
1710         auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(),
1711         [](const sptr<AudioDeviceDescriptor> &devDesc) {
1712             CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor");
1713             return (devDesc->deviceType_ == DEVICE_TYPE_SPEAKER);
1714         });
1715         if (itr != connectedDevices_.end()) {
1716             audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0);
1717         }
1718 
1719         desc.push_back(audioDescriptor);
1720         audioDescriptor->deviceId_ = startDeviceId++;
1721         UpdateDisplayName(audioDescriptor);
1722         connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
1723     }
1724     if (IsInputDevice(deviceDescriptor.deviceType_)) {
1725         AUDIO_INFO_LOG("Filling input device for %{public}d", deviceDescriptor.deviceType_);
1726 
1727         audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(deviceDescriptor);
1728         audioDescriptor->deviceRole_ = INPUT_DEVICE;
1729 
1730         // Use mic streaminfo for all input devices cap
1731         auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(),
1732             [](const sptr<AudioDeviceDescriptor> &devDesc) {
1733             CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor");
1734             return (devDesc->deviceType_ == DEVICE_TYPE_MIC);
1735         });
1736         if (itr != connectedDevices_.end()) {
1737             audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0);
1738         }
1739 
1740         desc.push_back(audioDescriptor);
1741         audioDescriptor->deviceId_ = startDeviceId++;
1742         UpdateDisplayName(audioDescriptor);
1743         connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
1744     }
1745 }
1746 
UpdateConnectedDevicesWhenDisconnecting(const AudioDeviceDescriptor & deviceDescriptor,std::vector<sptr<AudioDeviceDescriptor>> & desc)1747 void AudioPolicyService::UpdateConnectedDevicesWhenDisconnecting(const AudioDeviceDescriptor& deviceDescriptor,
1748     std::vector<sptr<AudioDeviceDescriptor>> &desc)
1749 {
1750     AUDIO_INFO_LOG("[%{public}s], devType:[%{public}d]", __func__, deviceDescriptor.deviceType_);
1751     auto isPresent = [&deviceDescriptor](const sptr<AudioDeviceDescriptor>& descriptor) {
1752         return descriptor->deviceType_ == deviceDescriptor.deviceType_
1753             && descriptor->networkId_ == deviceDescriptor.networkId_;
1754     };
1755     // Remember the disconnected device descriptor and remove it
1756     for (auto it = connectedDevices_.begin(); it != connectedDevices_.end();) {
1757         it = find_if(it, connectedDevices_.end(), isPresent);
1758         if (it != connectedDevices_.end()) {
1759             desc.push_back(*it);
1760             it = connectedDevices_.erase(it);
1761         }
1762     }
1763 }
1764 
OnPnpDeviceStatusUpdated(DeviceType devType,bool isConnected)1765 void AudioPolicyService::OnPnpDeviceStatusUpdated(DeviceType devType, bool isConnected)
1766 {
1767     CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type");
1768     if (!hasModulesLoaded) {
1769         AUDIO_WARNING_LOG("modules has not loaded");
1770         pnpDevice_ = devType;
1771         isPnpDeviceConnected = isConnected;
1772         return;
1773     }
1774     AudioStreamInfo streamInfo = {};
1775     if (g_adProxy == nullptr) {
1776         GetAudioServerProxy();
1777     }
1778     OnDeviceStatusUpdated(devType, isConnected, "", "", streamInfo);
1779 }
1780 
UpdateLocalGroupInfo(bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo,AudioDeviceDescriptor & deviceDesc)1781 void AudioPolicyService::UpdateLocalGroupInfo(bool isConnected, const std::string& macAddress,
1782     const std::string& deviceName, const AudioStreamInfo& streamInfo, AudioDeviceDescriptor& deviceDesc)
1783 {
1784     deviceDesc.SetDeviceInfo(deviceName, macAddress);
1785     deviceDesc.SetDeviceCapability(streamInfo, 0);
1786     UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, LOCAL_NETWORK_ID, isConnected,
1787         NO_REMOTE_ID);
1788     UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, LOCAL_NETWORK_ID, isConnected,
1789         NO_REMOTE_ID);
1790     deviceDesc.networkId_ = LOCAL_NETWORK_ID;
1791 }
1792 
HandleLocalDeviceConnected(DeviceType devType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)1793 int32_t AudioPolicyService::HandleLocalDeviceConnected(DeviceType devType, const std::string& macAddress,
1794     const std::string& deviceName, const AudioStreamInfo& streamInfo)
1795 {
1796     AUDIO_INFO_LOG("[%{public}s], macAddress:[%{public}s]", __func__, macAddress.c_str());
1797     if (devType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1798         connectedA2dpDeviceMap_.insert(make_pair(macAddress, streamInfo));
1799         activeBTDevice_ = macAddress;
1800     }
1801 
1802     // new device found. If connected, add into active device list
1803     int32_t result = ActivateNewDevice(devType);
1804     CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Failed to activate new device %{public}d", devType);
1805     currentActiveDevice_ = devType;
1806 
1807     return result;
1808 }
1809 
HandleLocalDeviceDisconnected(DeviceType devType,const std::string & macAddress)1810 int32_t AudioPolicyService::HandleLocalDeviceDisconnected(DeviceType devType, const std::string& macAddress)
1811 {
1812     int32_t result = ERROR;
1813     if (currentActiveDevice_ == devType) {
1814         auto priorityDev = FetchHighPriorityDevice();
1815         AUDIO_INFO_LOG("Priority device is [%{public}d]", priorityDev);
1816 
1817         if (priorityDev == DEVICE_TYPE_SPEAKER) {
1818             result = ActivateNewDevice(DEVICE_TYPE_MIC);
1819             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Failed to activate new device [%{public}d]",
1820                 DEVICE_TYPE_MIC);
1821             result = ActivateNewDevice(DEVICE_TYPE_SPEAKER);
1822             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Failed to activate new device [%{public}d]",
1823                 DEVICE_TYPE_SPEAKER);
1824         } else {
1825             result = ActivateNewDevice(priorityDev);
1826             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Failed to activate new device [%{public}d]",
1827                 priorityDev);
1828         }
1829 
1830         currentActiveDevice_ = priorityDev;
1831         UpdateEffectDefaultSink(priorityDev);
1832     } else {
1833         // The disconnected device is not current acitve device. No need to change active device.
1834         AUDIO_INFO_LOG("Current acitve device: %{public}d. No need to change", currentActiveDevice_);
1835         result = SUCCESS;
1836     }
1837 
1838     if (devType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1839         connectedA2dpDeviceMap_.erase(macAddress);
1840         activeBTDevice_ = "";
1841 
1842         if (IOHandles_.find(BLUETOOTH_SPEAKER) != IOHandles_.end()) {
1843             audioPolicyManager_.CloseAudioPort(IOHandles_[BLUETOOTH_SPEAKER]);
1844             IOHandles_.erase(BLUETOOTH_SPEAKER);
1845         }
1846     }
1847 
1848     return result;
1849 }
1850 
FindConnectedHeadset()1851 DeviceType AudioPolicyService::FindConnectedHeadset()
1852 {
1853     DeviceType retType = DEVICE_TYPE_NONE;
1854     for (const auto& devDesc: connectedDevices_) {
1855         if ((devDesc->deviceType_ == DEVICE_TYPE_WIRED_HEADSET) ||
1856             (devDesc->deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES) ||
1857             (devDesc->deviceType_ == DEVICE_TYPE_USB_HEADSET)) {
1858             retType = devDesc->deviceType_;
1859             break;
1860         }
1861     }
1862     return retType;
1863 }
1864 
OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)1865 void AudioPolicyService::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress,
1866     const std::string& deviceName, const AudioStreamInfo& streamInfo)
1867 {
1868     AUDIO_INFO_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d]", devType, isConnected);
1869 
1870     std::lock_guard<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_);
1871     // Special logic for extern cable, need refactor
1872     if (devType == DEVICE_TYPE_EXTERN_CABLE) {
1873         if (!isConnected) {
1874             AUDIO_INFO_LOG("Extern cable disconnected, do nothing");
1875             return;
1876         }
1877         DeviceType connectedHeadsetType = FindConnectedHeadset();
1878         if (connectedHeadsetType == DEVICE_TYPE_NONE) {
1879             AUDIO_INFO_LOG("Extern cable connect without headset connected before, do nothing");
1880             return;
1881         }
1882         devType = connectedHeadsetType;
1883         isConnected = false;
1884     }
1885 
1886     int32_t result = ERROR;
1887     AudioDeviceDescriptor deviceDesc(devType, GetDeviceRole(devType));
1888     UpdateLocalGroupInfo(isConnected, macAddress, deviceName, streamInfo, deviceDesc);
1889 
1890     // fill device change action for callback
1891     std::vector<sptr<AudioDeviceDescriptor>> deviceChangeDescriptor = {};
1892     auto isPresent = [&devType] (const sptr<AudioDeviceDescriptor> &descriptor) {
1893         return descriptor->deviceType_ == devType;
1894     };
1895     if (isConnected) {
1896         // If device already in list, remove it else do not modify the list
1897         connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent),
1898             connectedDevices_.end());
1899         UpdateConnectedDevicesWhenConnecting(deviceDesc, deviceChangeDescriptor);
1900 
1901         if ((devType == DEVICE_TYPE_BLUETOOTH_SCO && GetAudioScene() == AUDIO_SCENE_DEFAULT) ||
1902             (devType == DEVICE_TYPE_BLUETOOTH_A2DP && GetAudioScene() == AUDIO_SCENE_PHONE_CALL)) {
1903             // For SCO or A2DP device, add to connected device and donot activate now
1904             AUDIO_INFO_LOG("BT SCO or A2DP device detected in non-call mode [%{public}d]", GetAudioScene());
1905             if (devType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1906                 connectedA2dpDeviceMap_.insert(make_pair(macAddress, streamInfo));
1907                 activeBTDevice_ = macAddress;
1908             }
1909             TriggerDeviceChangedCallback(deviceChangeDescriptor, isConnected);
1910             UpdateTrackerDeviceChange(deviceChangeDescriptor);
1911             return;
1912         }
1913         result = HandleLocalDeviceConnected(devType, macAddress, deviceName, streamInfo);
1914         CHECK_AND_RETURN_LOG(result == SUCCESS, "Connect local device failed.");
1915     } else {
1916         UpdateConnectedDevicesWhenDisconnecting(deviceDesc, deviceChangeDescriptor);
1917         result = HandleLocalDeviceDisconnected(devType, macAddress);
1918         CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed.");
1919     }
1920 
1921     OnPreferredDeviceUpdated(currentActiveDevice_, activeInputDevice_);
1922     TriggerDeviceChangedCallback(deviceChangeDescriptor, isConnected);
1923     UpdateTrackerDeviceChange(deviceChangeDescriptor);
1924 }
1925 
1926 #ifdef FEATURE_DTMF_TONE
GetSupportedTones()1927 std::vector<int32_t> AudioPolicyService::GetSupportedTones()
1928 {
1929     std::vector<int> supportedToneList = {};
1930     for (auto i = toneDescriptorMap.begin(); i != toneDescriptorMap.end(); i++) {
1931         supportedToneList.push_back(i->first);
1932     }
1933     return supportedToneList;
1934 }
1935 
GetToneConfig(int32_t ltonetype)1936 std::shared_ptr<ToneInfo> AudioPolicyService::GetToneConfig(int32_t ltonetype)
1937 {
1938     if (toneDescriptorMap.find(ltonetype) == toneDescriptorMap.end()) {
1939         return nullptr;
1940     }
1941     AUDIO_DEBUG_LOG("AudioPolicyService GetToneConfig %{public}d", ltonetype);
1942     return toneDescriptorMap[ltonetype];
1943 }
1944 #endif
1945 
OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)1946 void AudioPolicyService::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress,
1947     const std::string &deviceName, const AudioStreamInfo &streamInfo)
1948 {
1949     AUDIO_DEBUG_LOG("OnDeviceConfigurationChanged in");
1950     if ((deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) && !macAddress.compare(activeBTDevice_)
1951         && IsDeviceActive(deviceType)) {
1952         if (!IsConfigurationUpdated(deviceType, streamInfo)) {
1953             AUDIO_DEBUG_LOG("Audio configuration same");
1954             return;
1955         }
1956 
1957         uint32_t bufferSize
1958             = (streamInfo.samplingRate * GetSampleFormatValue(streamInfo.format)
1959                 * streamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR);
1960         AUDIO_DEBUG_LOG("Updated buffer size: %{public}d", bufferSize);
1961         connectedA2dpDeviceMap_[macAddress] = streamInfo;
1962 
1963         auto a2dpModulesPos = deviceClassInfo_.find(ClassType::TYPE_A2DP);
1964         if (a2dpModulesPos != deviceClassInfo_.end()) {
1965             auto moduleInfoList = a2dpModulesPos->second;
1966             for (auto &moduleInfo : moduleInfoList) {
1967                 if (IOHandles_.find(moduleInfo.name) != IOHandles_.end()) {
1968                     moduleInfo.channels = to_string(streamInfo.channels);
1969                     moduleInfo.rate = to_string(streamInfo.samplingRate);
1970                     moduleInfo.format = ConvertToHDIAudioFormat(streamInfo.format);
1971                     moduleInfo.bufferSize = to_string(bufferSize);
1972 
1973                     // First unload the existing bt sink
1974                     AUDIO_DEBUG_LOG("UnLoad existing a2dp module");
1975                     std::string currentActivePort = GetPortName(currentActiveDevice_);
1976                     AudioIOHandle activateDeviceIOHandle = IOHandles_[BLUETOOTH_SPEAKER];
1977                     audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
1978                     audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle);
1979 
1980                     // Load bt sink module again with new configuration
1981                     AUDIO_DEBUG_LOG("Reload a2dp module [%{public}s]", moduleInfo.name.c_str());
1982                     AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
1983                     CHECK_AND_RETURN_LOG(ioHandle != OPEN_PORT_FAILURE, "OpenAudioPort failed %{public}d", ioHandle);
1984                     IOHandles_[moduleInfo.name] = ioHandle;
1985                     std::string portName = GetPortName(deviceType);
1986                     audioPolicyManager_.SetDeviceActive(ioHandle, deviceType, portName, true);
1987                     audioPolicyManager_.SuspendAudioDevice(portName, false);
1988 
1989                     auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &descriptor) {
1990                         return descriptor->deviceType_ == deviceType;
1991                     };
1992 
1993                     sptr<AudioDeviceDescriptor> audioDescriptor
1994                         = new(std::nothrow) AudioDeviceDescriptor(deviceType, OUTPUT_DEVICE);
1995                     audioDescriptor->SetDeviceInfo(deviceName, macAddress);
1996                     audioDescriptor->SetDeviceCapability(streamInfo, 0);
1997                     std::replace_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent, audioDescriptor);
1998                     break;
1999                 }
2000             }
2001         }
2002     }
2003 }
2004 
RemoveDeviceInRouterMap(std::string networkId)2005 void AudioPolicyService::RemoveDeviceInRouterMap(std::string networkId)
2006 {
2007     std::lock_guard<std::mutex> lock(routerMapMutex_);
2008     std::unordered_map<int32_t, std::pair<std::string, int32_t>>::iterator it;
2009     for (it = routerMap_.begin();it != routerMap_.end();) {
2010         if (it->second.first == networkId) {
2011             routerMap_.erase(it++);
2012         } else {
2013             it++;
2014         }
2015     }
2016 }
2017 
SetDisplayName(const std::string & deviceName,bool isLocalDevice)2018 void AudioPolicyService::SetDisplayName(const std::string &deviceName, bool isLocalDevice)
2019 {
2020     for (const auto& deviceInfo : connectedDevices_) {
2021         if ((isLocalDevice && deviceInfo->networkId_ == LOCAL_NETWORK_ID) ||
2022             (!isLocalDevice && deviceInfo->networkId_ != LOCAL_NETWORK_ID)) {
2023             deviceInfo->displayName_ = deviceName;
2024         }
2025     }
2026 }
2027 
RegisterRemoteDevStatusCallback()2028 void AudioPolicyService::RegisterRemoteDevStatusCallback()
2029 {
2030     AUDIO_INFO_LOG("Entered %{public}s", __func__);
2031     std::shared_ptr<DistributedHardware::DmInitCallback> initCallback = std::make_shared<DeviceInitCallBack>();
2032     int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(AUDIO_SERVICE_PKG, initCallback);
2033     if (ret != SUCCESS) {
2034         AUDIO_ERR_LOG("Init device manage failed");
2035         return;
2036     }
2037     std::shared_ptr<DistributedHardware::DeviceStatusCallback> callback = std::make_shared<DeviceStatusCallbackImpl>();
2038     DistributedHardware::DeviceManager::GetInstance().RegisterDevStatusCallback(AUDIO_SERVICE_PKG, "", callback);
2039 }
2040 
CreateDataShareHelperInstance()2041 bool AudioPolicyService::CreateDataShareHelperInstance()
2042 {
2043     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2044     CHECK_AND_RETURN_RET_LOG(samgr != nullptr, false, "[Policy Service] Get samgr failed.");
2045 
2046     sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(AUDIO_POLICY_SERVICE_ID);
2047     CHECK_AND_RETURN_RET_LOG(remoteObject != nullptr, false, "[Policy Service] audio service remote object is NULL.");
2048 
2049     lock_guard<mutex> lock(g_dataShareHelperMutex);
2050     g_dataShareHelper = DataShare::DataShareHelper::Creator(remoteObject, SETTINGS_DATA_BASE_URI);
2051     CHECK_AND_RETURN_RET_LOG(g_dataShareHelper != nullptr, false, "CreateDataShareHelperInstance create fail.");
2052     return true;
2053 }
2054 
GetDeviceNameFromDataShareHelper(std::string & deviceName)2055 int32_t AudioPolicyService::GetDeviceNameFromDataShareHelper(std::string &deviceName)
2056 {
2057     lock_guard<mutex> lock(g_dataShareHelperMutex);
2058     CHECK_AND_RETURN_RET_LOG(g_dataShareHelper != nullptr, ERROR, "GetDeviceNameFromDataShareHelper NULL.");
2059     std::shared_ptr<Uri> uri = std::make_shared<Uri>(SETTINGS_DATA_BASE_URI);
2060     std::vector<std::string> columns;
2061     columns.emplace_back(SETTINGS_DATA_FIELD_VALUE);
2062     DataShare::DataSharePredicates predicates;
2063     predicates.EqualTo(SETTINGS_DATA_FIELD_KEYWORD, PREDICATES_STRING);
2064 
2065     auto resultSet = g_dataShareHelper->Query(*uri, predicates, columns);
2066     CHECK_AND_RETURN_RET_LOG(resultSet != nullptr, ERROR, "GetDeviceNameFromDataShareHelper query fail.");
2067 
2068     int32_t numRows = 0;
2069     resultSet->GetRowCount(numRows);
2070 
2071     if (numRows <= 0) {
2072         AUDIO_ERR_LOG("GetDeviceNameFromDataShareHelper row zero.");
2073         return ERROR;
2074     }
2075     int columnIndex;
2076     resultSet->GoToFirstRow();
2077     resultSet->GetColumnIndex(SETTINGS_DATA_FIELD_VALUE, columnIndex);
2078     resultSet->GetString(columnIndex, deviceName);
2079     AUDIO_INFO_LOG("GetDeviceNameFromDataShareHelper deviceName[%{public}s]", deviceName.c_str());
2080     return SUCCESS;
2081 }
2082 
RegisterNameMonitorHelper()2083 void AudioPolicyService::RegisterNameMonitorHelper()
2084 {
2085     lock_guard<mutex> lock(g_dataShareHelperMutex);
2086     CHECK_AND_BREAK_LOG(g_dataShareHelper != nullptr, "RegisterNameMonitorHelper g_dataShareHelper is NULL.");
2087     auto uri = std::make_shared<Uri>(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING);
2088     sptr<AAFwk::DataAbilityObserverStub> settingDataObserver = std::make_unique<DataShareObserverCallBack>().release();
2089     g_dataShareHelper->RegisterObserver(*uri, settingDataObserver);
2090 }
2091 
UpdateDisplayName(sptr<AudioDeviceDescriptor> deviceDescriptor)2092 void AudioPolicyService::UpdateDisplayName(sptr<AudioDeviceDescriptor> deviceDescriptor)
2093 {
2094     if (deviceDescriptor->networkId_ == LOCAL_NETWORK_ID) {
2095         std::string devicesName = "";
2096         int32_t ret = GetDeviceNameFromDataShareHelper(devicesName);
2097         if (ret != SUCCESS) {
2098             AUDIO_ERR_LOG("Local UpdateDisplayName init device failed");
2099             return;
2100         }
2101         deviceDescriptor->displayName_ = devicesName;
2102     } else {
2103         std::shared_ptr<DistributedHardware::DmInitCallback> callback = std::make_shared<DeviceInitCallBack>();
2104         int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(AUDIO_SERVICE_PKG, callback);
2105         if (ret != SUCCESS) {
2106         AUDIO_ERR_LOG("UpdateDisplayName init device failed");
2107         return;
2108         }
2109         std::vector<DistributedHardware::DmDeviceInfo> deviceList;
2110         if (DistributedHardware::DeviceManager::GetInstance()
2111             .GetTrustedDeviceList(AUDIO_SERVICE_PKG, "", deviceList) == SUCCESS) {
2112             for (auto deviceInfo : deviceList) {
2113                 std::string strNetworkId(deviceInfo.networkId);
2114                 if (strNetworkId == deviceDescriptor->networkId_) {
2115                     AUDIO_INFO_LOG("UpdateDisplayName remote name [%{public}s]", deviceInfo.deviceName);
2116                     deviceDescriptor->displayName_ = deviceInfo.deviceName;
2117                     break;
2118                 }
2119             }
2120         };
2121     }
2122 }
2123 
OnDeviceStatusUpdated(DStatusInfo statusInfo)2124 void AudioPolicyService::OnDeviceStatusUpdated(DStatusInfo statusInfo)
2125 {
2126     AUDIO_INFO_LOG("Device connection updated | HDI_PIN[%{public}d] CONNECT_STATUS[%{public}d] NETWORKID[%{public}s]",
2127         statusInfo.hdiPin, statusInfo.isConnected, statusInfo.networkId);
2128 
2129     std::lock_guard<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_);
2130 
2131     DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin);
2132     const std::string networkId = statusInfo.networkId;
2133     AudioDeviceDescriptor deviceDesc(devType, GetDeviceRole(devType));
2134     deviceDesc.SetDeviceInfo(statusInfo.deviceName, statusInfo.macAddress);
2135     deviceDesc.SetDeviceCapability(statusInfo.streamInfo, 0);
2136     deviceDesc.networkId_ = networkId;
2137     UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, networkId, statusInfo.isConnected,
2138         statusInfo.mappingVolumeId);
2139     UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, networkId,
2140         statusInfo.isConnected, statusInfo.mappingInterruptId);
2141 
2142     std::vector<sptr<AudioDeviceDescriptor>> deviceChangeDescriptor = {};
2143 
2144     // new device found. If connected, add into active device list
2145     if (statusInfo.isConnected) {
2146         for (auto devDes : connectedDevices_) {
2147             if (devDes->deviceType_ == devType && devDes->networkId_ == networkId) {
2148                 AUDIO_INFO_LOG("Device [%{public}s] Type [%{public}d] has connected already!",
2149                     networkId.c_str(), devType);
2150                 return;
2151             }
2152         }
2153 
2154         int32_t ret = ActivateNewDevice(statusInfo.networkId, devType,
2155             statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED);
2156         CHECK_AND_RETURN_LOG(ret == SUCCESS, "DEVICE online but open audio device failed.");
2157         UpdateConnectedDevicesWhenConnecting(deviceDesc, deviceChangeDescriptor);
2158 
2159         const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2160         if (gsp != nullptr && statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED) {
2161             gsp->NotifyDeviceInfo(networkId, true);
2162         }
2163     } else {
2164         UpdateConnectedDevicesWhenDisconnecting(deviceDesc, deviceChangeDescriptor);
2165         std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(devType));
2166         if (IOHandles_.find(moduleName) != IOHandles_.end()) {
2167             audioPolicyManager_.CloseAudioPort(IOHandles_[moduleName]);
2168             IOHandles_.erase(moduleName);
2169         }
2170         RemoveDeviceInRouterMap(moduleName);
2171     }
2172 
2173     TriggerDeviceChangedCallback(deviceChangeDescriptor, statusInfo.isConnected);
2174     if (GetDeviceRole(devType) == DeviceRole::INPUT_DEVICE) {
2175         remoteCapturerSwitch_ = true;
2176     }
2177 }
2178 
OnServiceConnected(AudioServiceIndex serviceIndex)2179 void AudioPolicyService::OnServiceConnected(AudioServiceIndex serviceIndex)
2180 {
2181     AUDIO_INFO_LOG("[module_load]::OnServiceConnected for [%{public}d]", serviceIndex);
2182     CHECK_AND_RETURN_LOG(serviceIndex >= HDI_SERVICE_INDEX && serviceIndex <= AUDIO_SERVICE_INDEX, "invalid index");
2183 
2184     // If audio service or hdi service is not ready, donot load default modules
2185     lock_guard<mutex> lock(serviceFlagMutex_);
2186     serviceFlag_.set(serviceIndex, true);
2187     if (serviceFlag_.count() != MIN_SERVICE_COUNT) {
2188         AUDIO_INFO_LOG("[module_load]::hdi service or audio service not up. Cannot load default module now");
2189         return;
2190     }
2191 
2192     int32_t result = ERROR;
2193     AUDIO_INFO_LOG("[module_load]::HDI and AUDIO SERVICE is READY. Loading default modules");
2194     for (const auto &device : deviceClassInfo_) {
2195         if (device.first == ClassType::TYPE_PRIMARY || device.first == ClassType::TYPE_FILE_IO) {
2196             auto moduleInfoList = device.second;
2197             for (auto &moduleInfo : moduleInfoList) {
2198                 AUDIO_INFO_LOG("[module_load]::Load module[%{public}s]", moduleInfo.name.c_str());
2199                 moduleInfo.sinkLatency = sinkLatencyInMsec_ != 0 ? to_string(sinkLatencyInMsec_) : "";
2200                 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
2201                 if (ioHandle == OPEN_PORT_FAILURE) {
2202                     AUDIO_INFO_LOG("[module_load]::Open port failed");
2203                     continue;
2204                 }
2205                 IOHandles_[moduleInfo.name] = ioHandle;
2206                 auto devType = GetDeviceType(moduleInfo.name);
2207                 if (devType == DEVICE_TYPE_SPEAKER || devType == DEVICE_TYPE_MIC) {
2208                     result = audioPolicyManager_.SetDeviceActive(ioHandle, devType, moduleInfo.name, true);
2209                     if (result != SUCCESS) {
2210                         AUDIO_ERR_LOG("[module_load]::Device failed %{public}d", devType);
2211                         continue;
2212                     }
2213                     AddAudioDevice(moduleInfo, devType);
2214                 }
2215             }
2216         }
2217     }
2218 
2219     if (result == SUCCESS) {
2220         AUDIO_INFO_LOG("[module_load]::Setting speaker as active device on bootup");
2221         hasModulesLoaded = true;
2222         currentActiveDevice_ = DEVICE_TYPE_SPEAKER;
2223         activeInputDevice_ = DEVICE_TYPE_MIC;
2224         SetVolumeForSwitchDevice(currentActiveDevice_);
2225         OnPreferredDeviceUpdated(currentActiveDevice_, activeInputDevice_);
2226         OnPnpDeviceStatusUpdated(pnpDevice_, isPnpDeviceConnected);
2227         audioEffectManager_.SetMasterSinkAvailable();
2228         if (audioEffectManager_.CanLoadEffectSinks()) {
2229             LoadEffectSinks();
2230         }
2231     }
2232     RegisterBluetoothListener();
2233 }
2234 
OnServiceDisconnected(AudioServiceIndex serviceIndex)2235 void AudioPolicyService::OnServiceDisconnected(AudioServiceIndex serviceIndex)
2236 {
2237     AUDIO_ERR_LOG("OnServiceDisconnected for [%{public}d]", serviceIndex);
2238     CHECK_AND_RETURN_LOG(serviceIndex >= HDI_SERVICE_INDEX && serviceIndex <= AUDIO_SERVICE_INDEX, "invalid index");
2239     if (serviceIndex == HDI_SERVICE_INDEX) {
2240         AUDIO_ERR_LOG("Auto exit audio policy service for hdi service stopped!");
2241         _Exit(0);
2242     }
2243 }
2244 
OnMonoAudioConfigChanged(bool audioMono)2245 void AudioPolicyService::OnMonoAudioConfigChanged(bool audioMono)
2246 {
2247     AUDIO_INFO_LOG("AudioPolicyService::OnMonoAudioConfigChanged: audioMono = %{public}s", audioMono? "true": "false");
2248     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2249     if (gsp == nullptr) {
2250         AUDIO_ERR_LOG("Service proxy unavailable: g_adProxy null");
2251         return;
2252     }
2253     gsp->SetAudioMonoState(audioMono);
2254 }
2255 
OnAudioBalanceChanged(float audioBalance)2256 void AudioPolicyService::OnAudioBalanceChanged(float audioBalance)
2257 {
2258     AUDIO_INFO_LOG("AudioPolicyService::OnAudioBalanceChanged: audioBalance = %{public}f", audioBalance);
2259     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2260     if (gsp == nullptr) {
2261         AUDIO_ERR_LOG("Service proxy unavailable: g_adProxy null");
2262         return;
2263     }
2264     gsp->SetAudioBalanceValue(audioBalance);
2265 }
2266 
UpdateEffectDefaultSink(DeviceType deviceType)2267 void AudioPolicyService::UpdateEffectDefaultSink(DeviceType deviceType)
2268 {
2269     Trace trace("AudioPolicyService::OnPreferredOutputDeviceUpdated:" + std::to_string(deviceType));
2270     if (effectActiveDevice_ == deviceType) {
2271         return;
2272     }
2273     effectActiveDevice_ = deviceType;
2274     switch (deviceType) {
2275         case DeviceType::DEVICE_TYPE_EARPIECE:
2276         case DeviceType::DEVICE_TYPE_SPEAKER:
2277         case DeviceType::DEVICE_TYPE_FILE_SINK:
2278         case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
2279         case DeviceType::DEVICE_TYPE_USB_HEADSET:
2280         case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
2281         case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO: {
2282             const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2283             CHECK_AND_RETURN_LOG(gsp != nullptr, "Service proxy unavailable");
2284             std::string sinkName = GetPortName(deviceType);
2285             bool ret = gsp->SetOutputDeviceSink(deviceType, sinkName);
2286             CHECK_AND_RETURN_LOG(ret, "Failed to set output device sink");
2287             int res = audioPolicyManager_.UpdateSwapDeviceStatus();
2288             CHECK_AND_RETURN_LOG(res == SUCCESS, "Failed to update client swap device status");
2289             break;
2290         }
2291         default:
2292             break;
2293     }
2294 }
2295 
LoadSinksForCapturer()2296 void AudioPolicyService::LoadSinksForCapturer()
2297 {
2298     AUDIO_INFO_LOG("LoadSinksForCapturer");
2299     LoadInnerCapturerSink();
2300     LoadReceiverSink();
2301     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2302     if (gsp == nullptr) {
2303         AUDIO_ERR_LOG("LoadSinksForCapturer error for g_adProxy null");
2304         return;
2305     }
2306     bool ret = gsp->CreatePlaybackCapturerManager();
2307     CHECK_AND_RETURN_LOG(ret, "PlaybackCapturerManager create failed");
2308 }
2309 
LoadInnerCapturerSink()2310 void AudioPolicyService::LoadInnerCapturerSink()
2311 {
2312     AUDIO_INFO_LOG("LoadInnerCapturerSink");
2313     AudioModuleInfo moduleInfo = {};
2314     moduleInfo.lib = "libmodule-inner-capturer-sink.z.so";
2315     moduleInfo.name = INNER_CAPTURER_SINK_NAME;
2316     AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
2317     CHECK_AND_RETURN_LOG(ioHandle != OPEN_PORT_FAILURE,
2318         "OpenAudioPort failed %{public}d for InnerCapturer sink", ioHandle);
2319     IOHandles_[moduleInfo.name] = ioHandle;
2320 }
2321 
LoadReceiverSink()2322 void AudioPolicyService::LoadReceiverSink()
2323 {
2324     AUDIO_INFO_LOG("LoadReceiverSink");
2325     AudioModuleInfo moduleInfo = {};
2326     moduleInfo.name = RECEIVER_SINK_NAME;
2327     moduleInfo.lib = "libmodule-receiver-sink.z.so";
2328     AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
2329     CHECK_AND_RETURN_LOG(ioHandle != OPEN_PORT_FAILURE, "OpenAudioPort failed %{public}d for Receiver sink", ioHandle);
2330     IOHandles_[moduleInfo.name] = ioHandle;
2331 }
2332 
LoadLoopback()2333 void AudioPolicyService::LoadLoopback()
2334 {
2335     AudioIOHandle ioHandle;
2336     std::string moduleName;
2337     AUDIO_INFO_LOG("LoadLoopback");
2338 
2339     if (IOHandles_.count(INNER_CAPTURER_SINK_NAME) != 1u) {
2340         AUDIO_ERR_LOG("LoadLoopback failed for InnerCapturer not loaded");
2341         return;
2342     }
2343 
2344     LoopbackModuleInfo moduleInfo = {};
2345     moduleInfo.lib = "libmodule-loopback.z.so";
2346     moduleInfo.sink = INNER_CAPTURER_SINK_NAME;
2347 
2348     for (auto sceneType = AUDIO_SUPPORTED_SCENE_TYPES.begin(); sceneType != AUDIO_SUPPORTED_SCENE_TYPES.end();
2349         ++sceneType) {
2350         moduleInfo.source = sceneType->second + SINK_NAME_FOR_CAPTURE_SUFFIX + MONITOR_SOURCE_SUFFIX;
2351         ioHandle = audioPolicyManager_.LoadLoopback(moduleInfo);
2352         CHECK_AND_RETURN_LOG(ioHandle != OPEN_PORT_FAILURE, "LoadLoopback failed %{public}d", ioHandle);
2353         moduleName = moduleInfo.source + moduleInfo.sink;
2354         IOHandles_[moduleName] = ioHandle;
2355     }
2356 
2357     if (IOHandles_.count(RECEIVER_SINK_NAME) != 1u) {
2358         AUDIO_ERR_LOG("receiver sink not exist");
2359     } else {
2360         moduleInfo.source = RECEIVER_SINK_NAME + MONITOR_SOURCE_SUFFIX;
2361         ioHandle = audioPolicyManager_.LoadLoopback(moduleInfo);
2362         CHECK_AND_RETURN_LOG(ioHandle != OPEN_PORT_FAILURE, "LoadLoopback failed %{public}d", ioHandle);
2363         moduleName = moduleInfo.source + moduleInfo.sink;
2364         IOHandles_[moduleName] = ioHandle;
2365     }
2366 }
2367 
UnloadLoopback()2368 void AudioPolicyService::UnloadLoopback()
2369 {
2370     std::string module;
2371     AUDIO_INFO_LOG("UnloadLoopback");
2372 
2373     for (auto sceneType = AUDIO_SUPPORTED_SCENE_TYPES.begin(); sceneType != AUDIO_SUPPORTED_SCENE_TYPES.end();
2374         ++sceneType) {
2375         module = sceneType->second + SINK_NAME_FOR_CAPTURE_SUFFIX + MONITOR_SOURCE_SUFFIX + INNER_CAPTURER_SINK_NAME;
2376         if (IOHandles_.find(module) != IOHandles_.end()) {
2377             audioPolicyManager_.CloseAudioPort(IOHandles_[module]);
2378             IOHandles_.erase(module);
2379         }
2380     }
2381 
2382     module = RECEIVER_SINK_NAME + MONITOR_SOURCE_SUFFIX + INNER_CAPTURER_SINK_NAME;
2383     if (IOHandles_.find(module) != IOHandles_.end()) {
2384         audioPolicyManager_.CloseAudioPort(IOHandles_[module]);
2385         IOHandles_.erase(module);
2386     }
2387 }
2388 
LoadEffectSinks()2389 void AudioPolicyService::LoadEffectSinks()
2390 {
2391     // Create sink for each effect
2392     AudioModuleInfo moduleInfo = {};
2393     moduleInfo.lib = "libmodule-cluster-sink.z.so";
2394     moduleInfo.name = "CLUSTER";
2395     AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
2396     CHECK_AND_RETURN_LOG(ioHandle != OPEN_PORT_FAILURE, "OpenAudioPort failed %{public}d", ioHandle);
2397     IOHandles_[moduleInfo.name] = ioHandle;
2398 
2399     moduleInfo.lib = "libmodule-effect-sink.z.so";
2400     char device[50] = {0};
2401     int ret = GetParameter("const.build.product", " ", device, sizeof(device));
2402     std::string deviceString(device);
2403     if (ret > 0 && deviceString.compare("default") == 0) {
2404         moduleInfo.rate = "44100";
2405     } else {
2406         moduleInfo.rate = "48000";
2407     }
2408     for (auto sceneType = AUDIO_SUPPORTED_SCENE_TYPES.begin(); sceneType != AUDIO_SUPPORTED_SCENE_TYPES.end();
2409         ++sceneType) {
2410         AUDIO_INFO_LOG("Initial sink for scene name %{public}s", sceneType->second.c_str());
2411         moduleInfo.name = sceneType->second;
2412         moduleInfo.sceneName.clear();
2413         ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
2414         CHECK_AND_RETURN_LOG(ioHandle != OPEN_PORT_FAILURE, "OpenAudioPort failed %{public}d", ioHandle);
2415         IOHandles_[moduleInfo.name] = ioHandle;
2416 
2417         moduleInfo.name += SINK_NAME_FOR_CAPTURE_SUFFIX;
2418         moduleInfo.sceneName = sceneType->second;
2419         AUDIO_INFO_LOG("Initial effect sink:%{public}s for capturer", moduleInfo.name.c_str());
2420         ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
2421         CHECK_AND_RETURN_LOG(ioHandle != OPEN_PORT_FAILURE, "OpenAudioPort failed %{public}d", ioHandle);
2422         IOHandles_[moduleInfo.name] = ioHandle;
2423     }
2424     LoadSinksForCapturer(); // repy on the success of loading effect sink
2425 }
2426 
LoadEffectLibrary()2427 void AudioPolicyService::LoadEffectLibrary()
2428 {
2429     // IPC -> audioservice load library
2430     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
2431     if (gsp == nullptr) {
2432         AUDIO_ERR_LOG("Service proxy unavailable: g_adProxy null");
2433         return;
2434     }
2435     OriginalEffectConfig oriEffectConfig = {};
2436     audioEffectManager_.GetOriginalEffectConfig(oriEffectConfig);
2437     vector<Effect> successLoadedEffects;
2438     bool loadSuccess = gsp->LoadAudioEffectLibraries(oriEffectConfig.libraries,
2439                                                      oriEffectConfig.effects,
2440                                                      successLoadedEffects);
2441     if (!loadSuccess) {
2442         AUDIO_ERR_LOG("Load audio effect failed, please check log");
2443     }
2444 
2445     audioEffectManager_.UpdateAvailableEffects(successLoadedEffects);
2446     audioEffectManager_.BuildAvailableAEConfig();
2447 
2448     // Initialize EffectChainManager in audio service through IPC
2449     SupportedEffectConfig supportedEffectConfig;
2450     audioEffectManager_.GetSupportedEffectConfig(supportedEffectConfig);
2451     std::unordered_map<std::string, std::string> sceneTypeToEffectChainNameMap;
2452     audioEffectManager_.ConstructSceneTypeToEffectChainNameMap(sceneTypeToEffectChainNameMap);
2453     bool ret = gsp->CreateEffectChainManager(supportedEffectConfig.effectChains, sceneTypeToEffectChainNameMap);
2454     CHECK_AND_RETURN_LOG(ret, "EffectChainManager create failed");
2455 
2456     audioEffectManager_.SetEffectChainManagerAvailable();
2457     if (audioEffectManager_.CanLoadEffectSinks()) {
2458         LoadEffectSinks();
2459     }
2460 }
2461 
GetEffectManagerInfo(OriginalEffectConfig & oriEffectConfig,std::vector<Effect> & availableEffects)2462 void AudioPolicyService::GetEffectManagerInfo(OriginalEffectConfig& oriEffectConfig,
2463                                               std::vector<Effect>& availableEffects)
2464 {
2465     audioEffectManager_.GetOriginalEffectConfig(oriEffectConfig);
2466     audioEffectManager_.GetAvailableEffects(availableEffects);
2467 }
2468 
AddAudioDevice(AudioModuleInfo & moduleInfo,InternalDeviceType devType)2469 void AudioPolicyService::AddAudioDevice(AudioModuleInfo& moduleInfo, InternalDeviceType devType)
2470 {
2471     // add new device into active device list
2472     std::string volumeGroupName = GetGroupName(moduleInfo.name, VOLUME_TYPE);
2473     std::string interruptGroupName = GetGroupName(moduleInfo.name, INTERRUPT_TYPE);
2474     int32_t volumeGroupId = GROUP_ID_NONE;
2475     int32_t interruptGroupId = GROUP_ID_NONE;
2476     UpdateGroupInfo(GroupType::VOLUME_TYPE, volumeGroupName, volumeGroupId, LOCAL_NETWORK_ID, true,
2477         NO_REMOTE_ID);
2478     UpdateGroupInfo(GroupType::INTERRUPT_TYPE, interruptGroupName, interruptGroupId, LOCAL_NETWORK_ID,
2479         true, NO_REMOTE_ID);
2480 
2481     sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(devType,
2482         GetDeviceRole(moduleInfo.role), volumeGroupId, interruptGroupId, LOCAL_NETWORK_ID);
2483     if (!moduleInfo.rate.empty() && !moduleInfo.channels.empty()) {
2484         AudioStreamInfo streamInfo = {};
2485         streamInfo.samplingRate = static_cast<AudioSamplingRate>(stoi(moduleInfo.rate));
2486         streamInfo.channels = static_cast<AudioChannel>(stoi(moduleInfo.channels));
2487         audioDescriptor->SetDeviceCapability(streamInfo, 0);
2488     }
2489 
2490     audioDescriptor->deviceId_ = startDeviceId++;
2491     UpdateDisplayName(audioDescriptor);
2492     connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
2493 }
2494 
2495 // Parser callbacks
OnXmlParsingCompleted(const std::unordered_map<ClassType,std::list<AudioModuleInfo>> & xmlData)2496 void AudioPolicyService::OnXmlParsingCompleted(const std::unordered_map<ClassType, std::list<AudioModuleInfo>> &xmlData)
2497 {
2498     AUDIO_INFO_LOG("%{public}s, device class num [%{public}zu]", __func__, xmlData.size());
2499     if (xmlData.empty()) {
2500         AUDIO_ERR_LOG("failed to parse xml file. Received data is empty");
2501         return;
2502     }
2503 
2504     deviceClassInfo_ = xmlData;
2505 }
2506 
OnVolumeGroupParsed(std::unordered_map<std::string,std::string> & volumeGroupData)2507 void AudioPolicyService::OnVolumeGroupParsed(std::unordered_map<std::string, std::string>& volumeGroupData)
2508 {
2509     AUDIO_INFO_LOG("%{public}s, group data num [%{public}zu]", __func__, volumeGroupData.size());
2510     if (volumeGroupData.empty()) {
2511         AUDIO_ERR_LOG("failed to parse xml file. Received data is empty");
2512         return;
2513     }
2514 
2515     volumeGroupData_ = volumeGroupData;
2516 }
2517 
OnInterruptGroupParsed(std::unordered_map<std::string,std::string> & interruptGroupData)2518 void AudioPolicyService::OnInterruptGroupParsed(std::unordered_map<std::string, std::string>& interruptGroupData)
2519 {
2520     AUDIO_INFO_LOG("AudioPolicyService::%{public}s, group data num [%{public}zu]", __func__, interruptGroupData.size());
2521     if (interruptGroupData.empty()) {
2522         AUDIO_ERR_LOG("failed to parse xml file. Received data is empty");
2523         return;
2524     }
2525 
2526     interruptGroupData_ = interruptGroupData;
2527 }
2528 
SetDeviceChangeCallback(const int32_t clientId,const DeviceFlag flag,const sptr<IRemoteObject> & object,bool hasBTPermission)2529 int32_t AudioPolicyService::SetDeviceChangeCallback(const int32_t clientId, const DeviceFlag flag,
2530     const sptr<IRemoteObject> &object, bool hasBTPermission)
2531 {
2532     sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object);
2533 
2534     if (callback != nullptr) {
2535         callback->hasBTPermission_ = hasBTPermission;
2536         deviceChangeCbsMap_[{clientId, flag}] = callback;
2537     }
2538     AUDIO_DEBUG_LOG("SetDeviceChangeCallback:: deviceChangeCbsMap_ size: %{public}zu", deviceChangeCbsMap_.size());
2539     return SUCCESS;
2540 }
2541 
UnsetDeviceChangeCallback(const int32_t clientId,DeviceFlag flag)2542 int32_t AudioPolicyService::UnsetDeviceChangeCallback(const int32_t clientId, DeviceFlag flag)
2543 {
2544     AUDIO_INFO_LOG("Entered %{public}s", __func__);
2545 
2546     if (deviceChangeCbsMap_.erase({clientId, flag}) == 0) {
2547         AUDIO_INFO_LOG("client not present in %{public}s", __func__);
2548     }
2549     // for audio manager napi remove all device change callback
2550     if (flag == DeviceFlag::ALL_DEVICES_FLAG) {
2551         for (auto it = deviceChangeCbsMap_.begin(); it != deviceChangeCbsMap_.end();) {
2552             if ((*it).first.first == clientId && ((*it).first.second == DeviceFlag::INPUT_DEVICES_FLAG ||
2553                 (*it).first.second == DeviceFlag::OUTPUT_DEVICES_FLAG)) {
2554                 it = deviceChangeCbsMap_.erase(it);
2555             } else {
2556                 it++;
2557             }
2558         }
2559     }
2560     // for routing manager napi remove all device change callback
2561     if (flag == DeviceFlag::ALL_L_D_DEVICES_FLAG) {
2562         for (auto it = deviceChangeCbsMap_.begin(); it != deviceChangeCbsMap_.end();) {
2563             if ((*it).first.first == clientId) {
2564                 it = deviceChangeCbsMap_.erase(it);
2565             } else {
2566                 it++;
2567             }
2568         }
2569     }
2570 
2571     AUDIO_DEBUG_LOG("UnsetDeviceChangeCallback:: deviceChangeCbsMap_ size: %{public}zu", deviceChangeCbsMap_.size());
2572     return SUCCESS;
2573 }
2574 
SetPreferredOutputDeviceChangeCallback(const int32_t clientId,const sptr<IRemoteObject> & object,bool hasBTPermission)2575 int32_t AudioPolicyService::SetPreferredOutputDeviceChangeCallback(const int32_t clientId,
2576     const sptr<IRemoteObject> &object, bool hasBTPermission)
2577 {
2578     sptr<IStandardAudioRoutingManagerListener> callback = iface_cast<IStandardAudioRoutingManagerListener>(object);
2579     if (callback != nullptr) {
2580         callback->hasBTPermission_ = hasBTPermission;
2581         preferredOutputDeviceCbsMap_[clientId] = callback;
2582     }
2583 
2584     return SUCCESS;
2585 }
2586 
SetPreferredInputDeviceChangeCallback(const int32_t clientId,const sptr<IRemoteObject> & object,bool hasBTPermission)2587 int32_t AudioPolicyService::SetPreferredInputDeviceChangeCallback(const int32_t clientId,
2588     const sptr<IRemoteObject> &object, bool hasBTPermission)
2589 {
2590     AUDIO_INFO_LOG("Entered %{public}s", __func__);
2591 
2592     sptr<IStandardAudioRoutingManagerListener> callback = iface_cast<IStandardAudioRoutingManagerListener>(object);
2593     if (callback != nullptr) {
2594         callback->hasBTPermission_ = hasBTPermission;
2595         std::lock_guard<std::mutex> lock(preferredInputMapMutex_);
2596         preferredInputDeviceCbsMap_[clientId] = callback;
2597     }
2598 
2599     return SUCCESS;
2600 }
2601 
UnsetPreferredOutputDeviceChangeCallback(const int32_t clientId)2602 int32_t AudioPolicyService::UnsetPreferredOutputDeviceChangeCallback(const int32_t clientId)
2603 {
2604     AUDIO_INFO_LOG("Entered %{public}s", __func__);
2605 
2606     if (preferredOutputDeviceCbsMap_.erase(clientId) == 0) {
2607         AUDIO_ERR_LOG("client not present in %{public}s", __func__);
2608         return ERR_INVALID_OPERATION;
2609     }
2610 
2611     return SUCCESS;
2612 }
2613 
UnsetPreferredInputDeviceChangeCallback(const int32_t clientId)2614 int32_t AudioPolicyService::UnsetPreferredInputDeviceChangeCallback(const int32_t clientId)
2615 {
2616     AUDIO_INFO_LOG("Entered %{public}s", __func__);
2617     std::lock_guard<std::mutex> lock(preferredInputMapMutex_);
2618     if (preferredInputDeviceCbsMap_.erase(clientId) == 0) {
2619         AUDIO_ERR_LOG("client not present in %{public}s", __func__);
2620         return ERR_INVALID_OPERATION;
2621     }
2622 
2623     return SUCCESS;
2624 }
2625 
RegisterAudioRendererEventListener(int32_t clientPid,const sptr<IRemoteObject> & object,bool hasBTPermission,bool hasSysPermission)2626 int32_t AudioPolicyService::RegisterAudioRendererEventListener(int32_t clientPid, const sptr<IRemoteObject> &object,
2627     bool hasBTPermission, bool hasSysPermission)
2628 {
2629     return streamCollector_.RegisterAudioRendererEventListener(clientPid, object, hasBTPermission, hasSysPermission);
2630 }
2631 
UnregisterAudioRendererEventListener(int32_t clientPid)2632 int32_t AudioPolicyService::UnregisterAudioRendererEventListener(int32_t clientPid)
2633 {
2634     return streamCollector_.UnregisterAudioRendererEventListener(clientPid);
2635 }
2636 
RegisterAudioCapturerEventListener(int32_t clientPid,const sptr<IRemoteObject> & object,bool hasBTPermission,bool hasSysPermission)2637 int32_t AudioPolicyService::RegisterAudioCapturerEventListener(int32_t clientPid, const sptr<IRemoteObject> &object,
2638     bool hasBTPermission, bool hasSysPermission)
2639 {
2640     return streamCollector_.RegisterAudioCapturerEventListener(clientPid, object, hasBTPermission, hasSysPermission);
2641 }
2642 
UnregisterAudioCapturerEventListener(int32_t clientPid)2643 int32_t AudioPolicyService::UnregisterAudioCapturerEventListener(int32_t clientPid)
2644 {
2645     return streamCollector_.UnregisterAudioCapturerEventListener(clientPid);
2646 }
2647 
UpdateRendererInfoWhenNoPermission(const unique_ptr<AudioRendererChangeInfo> & audioRendererChangeInfos,bool hasSystemPermission)2648 static void UpdateRendererInfoWhenNoPermission(const unique_ptr<AudioRendererChangeInfo> &audioRendererChangeInfos,
2649     bool hasSystemPermission)
2650 {
2651     if (!hasSystemPermission) {
2652         audioRendererChangeInfos->clientUID = 0;
2653         audioRendererChangeInfos->rendererState = RENDERER_INVALID;
2654     }
2655 }
2656 
UpdateCapturerInfoWhenNoPermission(const unique_ptr<AudioCapturerChangeInfo> & audioCapturerChangeInfos,bool hasSystemPermission)2657 static void UpdateCapturerInfoWhenNoPermission(const unique_ptr<AudioCapturerChangeInfo> &audioCapturerChangeInfos,
2658     bool hasSystemPermission)
2659 {
2660     if (!hasSystemPermission) {
2661         audioCapturerChangeInfos->clientUID = 0;
2662         audioCapturerChangeInfos->capturerState = CAPTURER_INVALID;
2663     }
2664 }
2665 
HasLowLatencyCapability(DeviceType deviceType,bool isRemote)2666 static bool HasLowLatencyCapability(DeviceType deviceType, bool isRemote)
2667 {
2668     // Distributed devices are low latency devices
2669     if (isRemote) {
2670         return true;
2671     }
2672 
2673     switch (deviceType) {
2674         case DeviceType::DEVICE_TYPE_EARPIECE:
2675         case DeviceType::DEVICE_TYPE_SPEAKER:
2676         case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
2677         case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
2678         case DeviceType::DEVICE_TYPE_USB_HEADSET:
2679             return true;
2680 
2681         case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
2682         case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
2683             return false;
2684         default:
2685             return false;
2686     }
2687 }
2688 
UpdateDeviceInfo(DeviceInfo & deviceInfo,const sptr<AudioDeviceDescriptor> & desc,bool hasBTPermission,bool hasSystemPermission)2689 static void UpdateDeviceInfo(DeviceInfo &deviceInfo, const sptr<AudioDeviceDescriptor> &desc, bool hasBTPermission,
2690     bool hasSystemPermission)
2691 {
2692     deviceInfo.deviceType = desc->deviceType_;
2693     deviceInfo.deviceRole = desc->deviceRole_;
2694     deviceInfo.deviceId = desc->deviceId_;
2695     deviceInfo.channelMasks = desc->channelMasks_;
2696     deviceInfo.displayName = desc->displayName_;
2697 
2698     if (hasBTPermission) {
2699         deviceInfo.deviceName = desc->deviceName_;
2700         deviceInfo.macAddress = desc->macAddress_;
2701     } else {
2702         deviceInfo.deviceName = "";
2703         deviceInfo.macAddress = "";
2704     }
2705 
2706     deviceInfo.isLowLatencyDevice = HasLowLatencyCapability(deviceInfo.deviceType,
2707         desc->networkId_ != LOCAL_NETWORK_ID);
2708 
2709     if (hasSystemPermission) {
2710         deviceInfo.networkId = desc->networkId_;
2711         deviceInfo.volumeGroupId = desc->volumeGroupId_;
2712         deviceInfo.interruptGroupId = desc->interruptGroupId_;
2713     } else {
2714         deviceInfo.networkId = "";
2715         deviceInfo.volumeGroupId = GROUP_ID_NONE;
2716         deviceInfo.interruptGroupId = GROUP_ID_NONE;
2717     }
2718     deviceInfo.audioStreamInfo.samplingRate = desc->audioStreamInfo_.samplingRate;
2719     deviceInfo.audioStreamInfo.encoding = desc->audioStreamInfo_.encoding;
2720     deviceInfo.audioStreamInfo.format = desc->audioStreamInfo_.format;
2721     deviceInfo.audioStreamInfo.channels = desc->audioStreamInfo_.channels;
2722 }
2723 
UpdateStreamChangeDeviceInfo(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)2724 void AudioPolicyService::UpdateStreamChangeDeviceInfo(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
2725 {
2726     if (mode == AUDIO_MODE_PLAYBACK) {
2727         std::vector<sptr<AudioDeviceDescriptor>> outputDevices = GetDevices(OUTPUT_DEVICES_FLAG);
2728         DeviceType activeDeviceType = currentActiveDevice_;
2729         DeviceRole activeDeviceRole = OUTPUT_DEVICE;
2730         for (sptr<AudioDeviceDescriptor> desc : outputDevices) {
2731             if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
2732                 UpdateDeviceInfo(streamChangeInfo.audioRendererChangeInfo.outputDeviceInfo, desc, true, true);
2733                 break;
2734             }
2735         }
2736     } else {
2737         std::vector<sptr<AudioDeviceDescriptor>> inputDevices = GetDevices(INPUT_DEVICES_FLAG);
2738         DeviceType activeDeviceType = activeInputDevice_;
2739         DeviceRole activeDeviceRole = INPUT_DEVICE;
2740         for (sptr<AudioDeviceDescriptor> desc : inputDevices) {
2741             if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
2742                 UpdateDeviceInfo(streamChangeInfo.audioCapturerChangeInfo.inputDeviceInfo, desc, true, true);
2743                 break;
2744             }
2745         }
2746     }
2747 }
2748 
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object)2749 int32_t AudioPolicyService::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
2750     const sptr<IRemoteObject> &object)
2751 {
2752     UpdateStreamChangeDeviceInfo(mode, streamChangeInfo);
2753     return streamCollector_.RegisterTracker(mode, streamChangeInfo, object);
2754 }
2755 
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)2756 int32_t AudioPolicyService::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
2757 {
2758     AUDIO_INFO_LOG("Entered AudioPolicyService::%{public}s", __func__);
2759     UpdateStreamChangeDeviceInfo(mode, streamChangeInfo);
2760     return streamCollector_.UpdateTracker(mode, streamChangeInfo);
2761 }
2762 
GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos,bool hasBTPermission,bool hasSystemPermission)2763 int32_t AudioPolicyService::GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>>
2764     &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission)
2765 {
2766     int32_t status = streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
2767     if (status != SUCCESS) {
2768         AUDIO_ERR_LOG("AudioPolicyServer:: Get renderer change info failed");
2769         return status;
2770     }
2771 
2772     std::vector<sptr<AudioDeviceDescriptor>> outputDevices = GetDevices(OUTPUT_DEVICES_FLAG);
2773     DeviceType activeDeviceType = currentActiveDevice_;
2774     DeviceRole activeDeviceRole = OUTPUT_DEVICE;
2775     for (sptr<AudioDeviceDescriptor> desc : outputDevices) {
2776         if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
2777             size_t rendererInfosSize = audioRendererChangeInfos.size();
2778             for (size_t i = 0; i < rendererInfosSize; i++) {
2779                 UpdateRendererInfoWhenNoPermission(audioRendererChangeInfos[i], hasSystemPermission);
2780                 UpdateDeviceInfo(audioRendererChangeInfos[i]->outputDeviceInfo, desc, hasBTPermission,
2781                     hasSystemPermission);
2782             }
2783             break;
2784         }
2785     }
2786 
2787     return status;
2788 }
2789 
GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos,bool hasBTPermission,bool hasSystemPermission)2790 int32_t AudioPolicyService::GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>>
2791     &audioCapturerChangeInfos, bool hasBTPermission, bool hasSystemPermission)
2792 {
2793     int status = streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos);
2794     if (status != SUCCESS) {
2795         AUDIO_ERR_LOG("AudioPolicyServer:: Get capturer change info failed");
2796         return status;
2797     }
2798 
2799     std::vector<sptr<AudioDeviceDescriptor>> inputDevices = GetDevices(INPUT_DEVICES_FLAG);
2800     DeviceType activeDeviceType = activeInputDevice_;
2801     DeviceRole activeDeviceRole = INPUT_DEVICE;
2802     for (sptr<AudioDeviceDescriptor> desc : inputDevices) {
2803         if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
2804             size_t capturerInfosSize = audioCapturerChangeInfos.size();
2805             for (size_t i = 0; i < capturerInfosSize; i++) {
2806                 UpdateCapturerInfoWhenNoPermission(audioCapturerChangeInfos[i], hasSystemPermission);
2807                 UpdateDeviceInfo(audioCapturerChangeInfos[i]->inputDeviceInfo, desc, hasBTPermission,
2808                     hasSystemPermission);
2809             }
2810             break;
2811         }
2812     }
2813 
2814     return status;
2815 }
2816 
RegisteredTrackerClientDied(pid_t pid)2817 void AudioPolicyService::RegisteredTrackerClientDied(pid_t pid)
2818 {
2819     streamCollector_.RegisteredTrackerClientDied(static_cast<int32_t>(pid));
2820 }
2821 
RegisteredStreamListenerClientDied(pid_t pid)2822 void AudioPolicyService::RegisteredStreamListenerClientDied(pid_t pid)
2823 {
2824     streamCollector_.RegisteredStreamListenerClientDied(static_cast<int32_t>(pid));
2825 }
2826 
ReconfigureAudioChannel(const uint32_t & channelCount,DeviceType deviceType)2827 int32_t AudioPolicyService::ReconfigureAudioChannel(const uint32_t &channelCount, DeviceType deviceType)
2828 {
2829     if (currentActiveDevice_ != DEVICE_TYPE_FILE_SINK) {
2830         AUDIO_INFO_LOG("FILE_SINK_DEVICE is not active. Cannot reconfigure now");
2831         return ERROR;
2832     }
2833 
2834     std::string module = FILE_SINK;
2835 
2836     if (deviceType == DeviceType::DEVICE_TYPE_FILE_SINK) {
2837         CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_8 && channelCount >= MONO, ERROR, "Invalid sink channel");
2838         module = FILE_SINK;
2839     } else if (deviceType == DeviceType::DEVICE_TYPE_FILE_SOURCE) {
2840         CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_6 && channelCount >= MONO, ERROR, "Invalid src channel");
2841         module = FILE_SOURCE;
2842     } else {
2843         AUDIO_ERR_LOG("Invalid DeviceType");
2844         return ERROR;
2845     }
2846 
2847     if (IOHandles_.find(module) != IOHandles_.end()) {
2848         audioPolicyManager_.CloseAudioPort(IOHandles_[module]);
2849         IOHandles_.erase(module);
2850     }
2851 
2852     auto fileClass = deviceClassInfo_.find(ClassType::TYPE_FILE_IO);
2853     if (fileClass != deviceClassInfo_.end()) {
2854         auto moduleInfoList = fileClass->second;
2855         for (auto &moduleInfo : moduleInfoList) {
2856             if (module == moduleInfo.name) {
2857                 moduleInfo.channels = to_string(channelCount);
2858                 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
2859                 IOHandles_[moduleInfo.name] = ioHandle;
2860                 audioPolicyManager_.SetDeviceActive(ioHandle, deviceType, module, true);
2861             }
2862         }
2863     }
2864 
2865     return SUCCESS;
2866 }
2867 
2868 // private methods
GetAudioIOHandle(InternalDeviceType deviceType)2869 AudioIOHandle AudioPolicyService::GetAudioIOHandle(InternalDeviceType deviceType)
2870 {
2871     AudioIOHandle ioHandle;
2872     switch (deviceType) {
2873         case InternalDeviceType::DEVICE_TYPE_WIRED_HEADSET:
2874         case InternalDeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
2875         case InternalDeviceType::DEVICE_TYPE_USB_HEADSET:
2876         case InternalDeviceType::DEVICE_TYPE_EARPIECE:
2877         case InternalDeviceType::DEVICE_TYPE_SPEAKER:
2878         case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
2879             ioHandle = IOHandles_[PRIMARY_SPEAKER];
2880             break;
2881         case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
2882             ioHandle = IOHandles_[BLUETOOTH_SPEAKER];
2883             break;
2884         case InternalDeviceType::DEVICE_TYPE_MIC:
2885             ioHandle = IOHandles_[PRIMARY_MIC];
2886             break;
2887         case InternalDeviceType::DEVICE_TYPE_FILE_SINK:
2888             ioHandle = IOHandles_[FILE_SINK];
2889             break;
2890         case InternalDeviceType::DEVICE_TYPE_FILE_SOURCE:
2891             ioHandle = IOHandles_[FILE_SOURCE];
2892             break;
2893         default:
2894             ioHandle = IOHandles_[PRIMARY_MIC];
2895             break;
2896     }
2897     return ioHandle;
2898 }
2899 
GetDeviceType(const std::string & deviceName)2900 InternalDeviceType AudioPolicyService::GetDeviceType(const std::string &deviceName)
2901 {
2902     InternalDeviceType devType = InternalDeviceType::DEVICE_TYPE_NONE;
2903     if (deviceName == "Speaker") {
2904         devType = InternalDeviceType::DEVICE_TYPE_SPEAKER;
2905     } else if (deviceName == "Built_in_mic") {
2906         devType = InternalDeviceType::DEVICE_TYPE_MIC;
2907     } else if (deviceName == "Built_in_wakeup") {
2908         devType = InternalDeviceType::DEVICE_TYPE_WAKEUP;
2909     } else if (deviceName == "fifo_output" || deviceName == "fifo_input") {
2910         devType = DEVICE_TYPE_BLUETOOTH_SCO;
2911     } else if (deviceName == "file_sink") {
2912         devType = DEVICE_TYPE_FILE_SINK;
2913     } else if (deviceName == "file_source") {
2914         devType = DEVICE_TYPE_FILE_SOURCE;
2915     }
2916 
2917     return devType;
2918 }
2919 
GetGroupName(const std::string & deviceName,const GroupType type)2920 std::string AudioPolicyService::GetGroupName(const std::string& deviceName, const GroupType type)
2921 {
2922     std::string groupName = GROUP_NAME_NONE;
2923     if (type == VOLUME_TYPE) {
2924         auto iter = volumeGroupData_.find(deviceName);
2925         if (iter != volumeGroupData_.end()) {
2926             groupName = iter->second;
2927         }
2928     } else {
2929         auto iter = interruptGroupData_.find(deviceName);
2930         if (iter != interruptGroupData_.end()) {
2931             groupName = iter->second;
2932         }
2933     }
2934     return groupName;
2935 }
2936 
WriteDeviceChangedSysEvents(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)2937 void AudioPolicyService::WriteDeviceChangedSysEvents(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected)
2938 {
2939     for (auto deviceDescriptor : desc) {
2940         if (deviceDescriptor != nullptr) {
2941             if ((deviceDescriptor->deviceType_ == DEVICE_TYPE_WIRED_HEADSET)
2942                 || (deviceDescriptor->deviceType_ == DEVICE_TYPE_USB_HEADSET)
2943                 || (deviceDescriptor->deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES)) {
2944                 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::AUDIO, "HEADSET_CHANGE",
2945                     HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
2946                     "ISCONNECT", isConnected ? 1 : 0,
2947                     "HASMIC", 1,
2948                     "DEVICETYPE", deviceDescriptor->deviceType_);
2949             }
2950 
2951             if (!isConnected) {
2952                 continue;
2953             }
2954 
2955             if (deviceDescriptor->deviceRole_ == OUTPUT_DEVICE) {
2956                 vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
2957                 for (SinkInput sinkInput : sinkInputs) {
2958                     HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::AUDIO, "DEVICE_CHANGE",
2959                         HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
2960                         "ISOUTPUT", 1,
2961                         "STREAMID", sinkInput.streamId,
2962                         "STREAMTYPE", sinkInput.streamType,
2963                         "DEVICETYPE", deviceDescriptor->deviceType_);
2964                 }
2965             } else if (deviceDescriptor->deviceRole_ == INPUT_DEVICE) {
2966                 vector<SourceOutput> sourceOutputs = audioPolicyManager_.GetAllSourceOutputs();
2967                 for (SourceOutput sourceOutput : sourceOutputs) {
2968                     HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::AUDIO, "DEVICE_CHANGE",
2969                         HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
2970                         "ISOUTPUT", 0,
2971                         "STREAMID", sourceOutput.streamId,
2972                         "STREAMTYPE", sourceOutput.streamType,
2973                         "DEVICETYPE", deviceDescriptor->deviceType_);
2974                 }
2975             }
2976         }
2977     }
2978 }
2979 
UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> & desc)2980 void AudioPolicyService::UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> &desc)
2981 {
2982     AUDIO_INFO_LOG("AudioPolicyService::%{public}s IN", __func__);
2983     for (sptr<AudioDeviceDescriptor> deviceDesc : desc) {
2984         if (deviceDesc->deviceRole_ == OUTPUT_DEVICE) {
2985             DeviceType activeDevice = currentActiveDevice_;
2986             auto isPresent = [&activeDevice] (const sptr<AudioDeviceDescriptor> &desc) {
2987                 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
2988                 return ((activeDevice == desc->deviceType_) && (OUTPUT_DEVICE == desc->deviceRole_));
2989             };
2990 
2991             auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
2992             if (itr != connectedDevices_.end()) {
2993                 DeviceInfo outputDevice = {};
2994                 UpdateDeviceInfo(outputDevice, *itr, true, true);
2995                 streamCollector_.UpdateTracker(AUDIO_MODE_PLAYBACK, outputDevice);
2996             }
2997         }
2998 
2999         if (deviceDesc->deviceRole_ == INPUT_DEVICE) {
3000             DeviceType activeDevice = activeInputDevice_;
3001             auto isPresent = [&activeDevice] (const sptr<AudioDeviceDescriptor> &desc) {
3002                 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
3003                 return ((activeDevice == desc->deviceType_) && (INPUT_DEVICE == desc->deviceRole_));
3004             };
3005 
3006             auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
3007             if (itr != connectedDevices_.end()) {
3008                 DeviceInfo inputDevice = {};
3009                 UpdateDeviceInfo(inputDevice, *itr, true, true);
3010                 streamCollector_.UpdateTracker(AUDIO_MODE_RECORD, inputDevice);
3011             }
3012         }
3013     }
3014 }
3015 
UpdateGroupInfo(GroupType type,std::string groupName,int32_t & groupId,std::string networkId,bool connected,int32_t mappingId)3016 void AudioPolicyService::UpdateGroupInfo(GroupType type, std::string groupName, int32_t& groupId, std::string networkId,
3017     bool connected, int32_t mappingId)
3018 {
3019     ConnectType connectType = CONNECT_TYPE_LOCAL;
3020     if (networkId != LOCAL_NETWORK_ID) {
3021         connectType = CONNECT_TYPE_DISTRIBUTED;
3022     }
3023     if (type == GroupType::VOLUME_TYPE) {
3024         auto isPresent = [&groupName, &networkId] (const sptr<VolumeGroupInfo> &volumeInfo) {
3025             return ((groupName == volumeInfo->groupName_) || (networkId == volumeInfo->networkId_));
3026         };
3027 
3028         auto iter = std::find_if(volumeGroups_.begin(), volumeGroups_.end(), isPresent);
3029         if (iter != volumeGroups_.end()) {
3030             groupId = (*iter)->volumeGroupId_;
3031             // if status is disconnected, remove the group that has none audio device
3032             std::vector<sptr<AudioDeviceDescriptor>> devsInGroup = GetDevicesForGroup(type, groupId);
3033             if (!connected && devsInGroup.size() == 0) {
3034                 volumeGroups_.erase(iter);
3035             }
3036             return;
3037         }
3038         if (groupName != GROUP_NAME_NONE && connected) {
3039             groupId = AudioGroupHandle::GetInstance().GetNextId(type);
3040             sptr<VolumeGroupInfo> volumeGroupInfo = new(std::nothrow) VolumeGroupInfo(groupId,
3041                 mappingId, groupName, networkId, connectType);
3042             volumeGroups_.push_back(volumeGroupInfo);
3043         }
3044     } else {
3045         auto isPresent = [&groupName, &networkId] (const sptr<InterruptGroupInfo> &info) {
3046             return ((groupName == info->groupName_) || (networkId == info->networkId_));
3047         };
3048 
3049         auto iter = std::find_if(interruptGroups_.begin(), interruptGroups_.end(), isPresent);
3050         if (iter != interruptGroups_.end()) {
3051             groupId = (*iter)->interruptGroupId_;
3052             // if status is disconnected, remove the group that has none audio device
3053             std::vector<sptr<AudioDeviceDescriptor>> devsInGroup = GetDevicesForGroup(type, groupId);
3054             if (!connected && devsInGroup.size() == 0) {
3055                 interruptGroups_.erase(iter);
3056             }
3057             return;
3058         }
3059         if (groupName != GROUP_NAME_NONE && connected) {
3060             groupId = AudioGroupHandle::GetInstance().GetNextId(type);
3061             sptr<InterruptGroupInfo> interruptGroupInfo = new(std::nothrow) InterruptGroupInfo(groupId, mappingId,
3062                 groupName, networkId, connectType);
3063             interruptGroups_.push_back(interruptGroupInfo);
3064         }
3065     }
3066 }
3067 
GetDevicesForGroup(GroupType type,int32_t groupId)3068 std::vector<sptr<OHOS::AudioStandard::AudioDeviceDescriptor>> AudioPolicyService::GetDevicesForGroup(GroupType type,
3069     int32_t groupId)
3070 {
3071     std::vector<sptr<OHOS::AudioStandard::AudioDeviceDescriptor>> devices = {};
3072     for (auto devDes : connectedDevices_) {
3073         if (devDes == nullptr) {
3074             continue;
3075         }
3076         bool inVolumeGroup = type == VOLUME_TYPE && devDes->volumeGroupId_ == groupId;
3077         bool inInterruptGroup = type == INTERRUPT_TYPE && devDes->interruptGroupId_ == groupId;
3078 
3079         if (inVolumeGroup || inInterruptGroup) {
3080             sptr<AudioDeviceDescriptor> device = new AudioDeviceDescriptor(*devDes);
3081             devices.push_back(device);
3082         }
3083     }
3084     return devices;
3085 }
3086 
UpdateDescWhenNoBTPermission(vector<sptr<AudioDeviceDescriptor>> & deviceDescs)3087 void AudioPolicyService::UpdateDescWhenNoBTPermission(vector<sptr<AudioDeviceDescriptor>> &deviceDescs)
3088 {
3089     AUDIO_WARNING_LOG("UpdateDescWhenNoBTPermission: No bt permission");
3090 
3091     for (sptr<AudioDeviceDescriptor> &desc : deviceDescs) {
3092         if ((desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP)
3093             || (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO)) {
3094             sptr<AudioDeviceDescriptor> copyDesc = new AudioDeviceDescriptor(desc);
3095             copyDesc->deviceName_ = "";
3096             copyDesc->macAddress_ = "";
3097             desc = copyDesc;
3098         }
3099     }
3100 }
3101 
TriggerDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)3102 void AudioPolicyService::TriggerDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected)
3103 {
3104     Trace trace("AudioPolicyService::TriggerDeviceChangedCallback");
3105     DeviceChangeAction deviceChangeAction;
3106     deviceChangeAction.type = isConnected ? DeviceChangeType::CONNECT : DeviceChangeType::DISCONNECT;
3107 
3108     WriteDeviceChangedSysEvents(desc, isConnected);
3109 
3110     for (auto it = deviceChangeCbsMap_.begin(); it != deviceChangeCbsMap_.end(); ++it) {
3111         deviceChangeAction.flag = it->first.second;
3112         deviceChangeAction.deviceDescriptors = DeviceFilterByFlag(it->first.second, desc);
3113         if (it->second && deviceChangeAction.deviceDescriptors.size() > 0) {
3114             if (!(it->second->hasBTPermission_)) {
3115                 UpdateDescWhenNoBTPermission(deviceChangeAction.deviceDescriptors);
3116             }
3117             it->second->OnDeviceChange(deviceChangeAction);
3118         }
3119     }
3120 }
3121 
DeviceFilterByFlag(DeviceFlag flag,const std::vector<sptr<AudioDeviceDescriptor>> & desc)3122 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::DeviceFilterByFlag(DeviceFlag flag,
3123     const std::vector<sptr<AudioDeviceDescriptor>>& desc)
3124 {
3125     std::vector<sptr<AudioDeviceDescriptor>> descRet;
3126     DeviceRole role = DEVICE_ROLE_NONE;
3127     switch (flag) {
3128         case DeviceFlag::ALL_DEVICES_FLAG:
3129             for (sptr<AudioDeviceDescriptor> var : desc) {
3130                 if (var->networkId_ == LOCAL_NETWORK_ID) {
3131                     descRet.insert(descRet.end(), var);
3132                 }
3133             }
3134             break;
3135         case DeviceFlag::ALL_DISTRIBUTED_DEVICES_FLAG:
3136             for (sptr<AudioDeviceDescriptor> var : desc) {
3137                 if (var->networkId_ != LOCAL_NETWORK_ID) {
3138                     descRet.insert(descRet.end(), var);
3139                 }
3140             }
3141             break;
3142         case DeviceFlag::ALL_L_D_DEVICES_FLAG:
3143             descRet = desc;
3144             break;
3145         case DeviceFlag::OUTPUT_DEVICES_FLAG:
3146         case DeviceFlag::INPUT_DEVICES_FLAG:
3147             role = flag == INPUT_DEVICES_FLAG ? INPUT_DEVICE : OUTPUT_DEVICE;
3148             for (sptr<AudioDeviceDescriptor> var : desc) {
3149                 if (var->networkId_ == LOCAL_NETWORK_ID && var->deviceRole_ == role) {
3150                     descRet.insert(descRet.end(), var);
3151                 }
3152             }
3153             break;
3154         case DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG:
3155         case DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG:
3156             role = flag == DISTRIBUTED_INPUT_DEVICES_FLAG ? INPUT_DEVICE : OUTPUT_DEVICE;
3157             for (sptr<AudioDeviceDescriptor> var : desc) {
3158                 if (var->networkId_ != LOCAL_NETWORK_ID && var->deviceRole_ == role) {
3159                     descRet.insert(descRet.end(), var);
3160                 }
3161             }
3162             break;
3163         default:
3164             AUDIO_INFO_LOG("AudioPolicyService::%{public}s:deviceFlag type are not supported", __func__);
3165             break;
3166     }
3167     return descRet;
3168 }
3169 
IsInputDevice(DeviceType deviceType) const3170 bool AudioPolicyService::IsInputDevice(DeviceType deviceType) const
3171 {
3172     switch (deviceType) {
3173         case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
3174         case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
3175         case DeviceType::DEVICE_TYPE_MIC:
3176         case DeviceType::DEVICE_TYPE_WAKEUP:
3177         case DeviceType::DEVICE_TYPE_USB_HEADSET:
3178             return true;
3179         default:
3180             return false;
3181     }
3182 }
3183 
IsOutputDevice(DeviceType deviceType) const3184 bool AudioPolicyService::IsOutputDevice(DeviceType deviceType) const
3185 {
3186     switch (deviceType) {
3187         case DeviceType::DEVICE_TYPE_EARPIECE:
3188         case DeviceType::DEVICE_TYPE_SPEAKER:
3189         case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
3190         case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
3191         case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
3192         case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
3193         case DeviceType::DEVICE_TYPE_USB_HEADSET:
3194             return true;
3195         default:
3196             return false;
3197     }
3198 }
3199 
GetDeviceRole(DeviceType deviceType) const3200 DeviceRole AudioPolicyService::GetDeviceRole(DeviceType deviceType) const
3201 {
3202     switch (deviceType) {
3203         case DeviceType::DEVICE_TYPE_SPEAKER:
3204         case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
3205         case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
3206         case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
3207         case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
3208         case DeviceType::DEVICE_TYPE_USB_HEADSET:
3209             return DeviceRole::OUTPUT_DEVICE;
3210         case DeviceType::DEVICE_TYPE_MIC:
3211         case DeviceType::DEVICE_TYPE_WAKEUP:
3212             return DeviceRole::INPUT_DEVICE;
3213         default:
3214             return DeviceRole::DEVICE_ROLE_NONE;
3215     }
3216 }
3217 
GetDeviceRole(const std::string & role)3218 DeviceRole AudioPolicyService::GetDeviceRole(const std::string &role)
3219 {
3220     if (role == ROLE_SINK) {
3221         return DeviceRole::OUTPUT_DEVICE;
3222     } else if (role == ROLE_SOURCE) {
3223         return DeviceRole::INPUT_DEVICE;
3224     } else {
3225         return DeviceRole::DEVICE_ROLE_NONE;
3226     }
3227 }
3228 
GetDeviceRole(AudioPin pin) const3229 DeviceRole AudioPolicyService::GetDeviceRole(AudioPin pin) const
3230 {
3231     switch (pin) {
3232         case OHOS::AudioStandard::AUDIO_PIN_NONE:
3233             return DeviceRole::DEVICE_ROLE_NONE;
3234         case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER:
3235         case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET:
3236         case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT:
3237         case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI:
3238         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB:
3239         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT:
3240         case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT:
3241             return DeviceRole::OUTPUT_DEVICE;
3242         case OHOS::AudioStandard::AUDIO_PIN_IN_MIC:
3243         case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC:
3244         case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN:
3245         case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT:
3246         case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT:
3247             return DeviceRole::INPUT_DEVICE;
3248         default:
3249             return DeviceRole::DEVICE_ROLE_NONE;
3250     }
3251 }
3252 
OnAudioLatencyParsed(uint64_t latency)3253 void AudioPolicyService::OnAudioLatencyParsed(uint64_t latency)
3254 {
3255     audioLatencyInMsec_ = latency;
3256 }
3257 
GetAudioLatencyFromXml() const3258 int32_t AudioPolicyService::GetAudioLatencyFromXml() const
3259 {
3260     return audioLatencyInMsec_;
3261 }
3262 
OnSinkLatencyParsed(uint32_t latency)3263 void AudioPolicyService::OnSinkLatencyParsed(uint32_t latency)
3264 {
3265     sinkLatencyInMsec_ = latency;
3266 }
3267 
GetSinkLatencyFromXml() const3268 uint32_t AudioPolicyService::GetSinkLatencyFromXml() const
3269 {
3270     return sinkLatencyInMsec_;
3271 }
3272 
UpdateInputDeviceInfo(DeviceType deviceType)3273 void AudioPolicyService::UpdateInputDeviceInfo(DeviceType deviceType)
3274 {
3275     AUDIO_DEBUG_LOG("Current input device is %{public}d", activeInputDevice_);
3276 
3277     switch (deviceType) {
3278         case DEVICE_TYPE_EARPIECE:
3279         case DEVICE_TYPE_SPEAKER:
3280         case DEVICE_TYPE_BLUETOOTH_A2DP:
3281             activeInputDevice_ = DEVICE_TYPE_MIC;
3282             break;
3283         case DEVICE_TYPE_FILE_SINK:
3284             activeInputDevice_ = DEVICE_TYPE_FILE_SOURCE;
3285             break;
3286         case DEVICE_TYPE_WIRED_HEADSET:
3287         case DEVICE_TYPE_USB_HEADSET:
3288         case DEVICE_TYPE_BLUETOOTH_SCO:
3289             activeInputDevice_ = deviceType;
3290             break;
3291         default:
3292             break;
3293     }
3294 
3295     AUDIO_DEBUG_LOG("Input device updated to %{public}d", activeInputDevice_);
3296 }
3297 
UpdateStreamState(int32_t clientUid,StreamSetStateEventInternal & streamSetStateEventInternal)3298 int32_t AudioPolicyService::UpdateStreamState(int32_t clientUid,
3299     StreamSetStateEventInternal &streamSetStateEventInternal)
3300 {
3301     return streamCollector_.UpdateStreamState(clientUid, streamSetStateEventInternal);
3302 }
3303 
GetDeviceTypeFromPin(AudioPin hdiPin)3304 DeviceType AudioPolicyService::GetDeviceTypeFromPin(AudioPin hdiPin)
3305 {
3306     switch (hdiPin) {
3307         case OHOS::AudioStandard::AUDIO_PIN_NONE:
3308             break;
3309         case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER:
3310         case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT:
3311             return DeviceType::DEVICE_TYPE_SPEAKER;
3312         case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET:
3313             break;
3314         case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT:
3315             break;
3316         case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI:
3317             break;
3318         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB:
3319             break;
3320         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT:
3321             break;
3322         case OHOS::AudioStandard::AUDIO_PIN_IN_MIC:
3323         case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT:
3324             return DeviceType::DEVICE_TYPE_MIC;
3325         case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC:
3326             break;
3327         case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN:
3328             break;
3329         case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT:
3330             break;
3331         default:
3332             break;
3333     }
3334     return DeviceType::DEVICE_TYPE_DEFAULT;
3335 }
3336 
GetVolumeGroupInfos()3337 std::vector<sptr<VolumeGroupInfo>> AudioPolicyService::GetVolumeGroupInfos()
3338 {
3339     std::vector<sptr<VolumeGroupInfo>> volumeGroupInfos = {};
3340 
3341     for (auto& v : volumeGroups_) {
3342         sptr<VolumeGroupInfo> info = new(std::nothrow) VolumeGroupInfo(v->volumeGroupId_, v->mappingId_, v->groupName_,
3343             v->networkId_, v->connectType_);
3344         volumeGroupInfos.push_back(info);
3345     }
3346     return volumeGroupInfos;
3347 }
3348 
RegiestPolicy()3349 void AudioPolicyService::RegiestPolicy()
3350 {
3351     AUDIO_INFO_LOG("Enter RegiestPolicy");
3352     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3353     if (gsp == nullptr) {
3354         AUDIO_ERR_LOG("RegiestPolicy g_adProxy null");
3355         return;
3356     }
3357     sptr<PolicyProviderWrapper> wrapper = new(std::nothrow) PolicyProviderWrapper(this);
3358     CHECK_AND_RETURN_LOG(wrapper != nullptr, "Get null PolicyProviderWrapper");
3359     sptr<IRemoteObject> object = wrapper->AsObject();
3360     if (object == nullptr) {
3361         AUDIO_ERR_LOG("RegiestPolicy AsObject is nullptr");
3362         return;
3363     }
3364     int32_t ret = gsp->RegiestPolicyProvider(object);
3365     AUDIO_DEBUG_LOG("RegiestPolicy result:%{public}d", ret);
3366 }
3367 
GetProcessDeviceInfo(const AudioProcessConfig & config,DeviceInfo & deviceInfo)3368 int32_t AudioPolicyService::GetProcessDeviceInfo(const AudioProcessConfig &config, DeviceInfo &deviceInfo)
3369 {
3370     AUDIO_INFO_LOG("%{public}s", ProcessConfig::DumpProcessConfig(config).c_str());
3371     // todo
3372     // check process in routerMap, return target device for it
3373     // put the currentActiveDevice_ in deviceinfo, so it can create with current using device.
3374     // genarate the unique deviceid?
3375 
3376     if (config.audioMode == AUDIO_MODE_RECORD) {
3377         deviceInfo.deviceId = 1;
3378         deviceInfo.networkId = LOCAL_NETWORK_ID;
3379         deviceInfo.deviceRole = INPUT_DEVICE;
3380         deviceInfo.deviceType = DEVICE_TYPE_MIC;
3381     } else {
3382         deviceInfo.deviceId = 6; // 6 for test
3383         deviceInfo.networkId = LOCAL_NETWORK_ID;
3384         deviceInfo.deviceType = currentActiveDevice_;
3385         deviceInfo.deviceRole = OUTPUT_DEVICE;
3386     }
3387     AudioStreamInfo targetStreamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO}; // note: read from xml
3388     deviceInfo.audioStreamInfo = targetStreamInfo;
3389     deviceInfo.deviceName = "mmap_device";
3390     return SUCCESS;
3391 }
3392 
InitSharedVolume(std::shared_ptr<AudioSharedMemory> & buffer)3393 int32_t AudioPolicyService::InitSharedVolume(std::shared_ptr<AudioSharedMemory> &buffer)
3394 {
3395     CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr,
3396         ERR_OPERATION_FAILED, "Get shared memory failed!");
3397 
3398     // init volume map
3399     // todo device
3400     for (size_t i = 0; i < IPolicyProvider::GetVolumeVectorSize(); i++) {
3401         float volFloat = GetSystemVolumeDb(g_volumeIndexVector[i].first);
3402         volumeVector_[i].isMute = false;
3403         volumeVector_[i].volumeFloat = volFloat;
3404         volumeVector_[i].volumeInt = 0;
3405     }
3406     buffer = policyVolumeMap_;
3407 
3408     return SUCCESS;
3409 }
3410 
GetSharedVolume(AudioStreamType streamType,DeviceType deviceType,Volume & vol)3411 bool AudioPolicyService::GetSharedVolume(AudioStreamType streamType, DeviceType deviceType, Volume &vol)
3412 {
3413     CHECK_AND_RETURN_RET_LOG(volumeVector_ != nullptr, false, "Get shared memory failed!");
3414     size_t index = 0;
3415     if (!IPolicyProvider::GetVolumeIndex(streamType, deviceType, index) ||
3416         index >= IPolicyProvider::GetVolumeVectorSize()) {
3417         return false;
3418     }
3419     vol.isMute = volumeVector_[index].isMute;
3420     vol.volumeFloat = volumeVector_[index].volumeFloat;
3421     vol.volumeInt = volumeVector_[index].volumeInt;
3422     return true;
3423 }
3424 
SetSharedVolume(AudioStreamType streamType,DeviceType deviceType,Volume vol)3425 bool AudioPolicyService::SetSharedVolume(AudioStreamType streamType, DeviceType deviceType, Volume vol)
3426 {
3427     CHECK_AND_RETURN_RET_LOG(volumeVector_ != nullptr, false, "Set shared memory failed!");
3428     size_t index = 0;
3429     if (!IPolicyProvider::GetVolumeIndex(streamType, deviceType, index) ||
3430         index >= IPolicyProvider::GetVolumeVectorSize()) {
3431         return false;
3432     }
3433     volumeVector_[index].isMute = vol.isMute;
3434     volumeVector_[index].volumeFloat = vol.volumeFloat;
3435     volumeVector_[index].volumeInt = vol.volumeInt;
3436     return true;
3437 }
3438 
SetParameterCallback(const std::shared_ptr<AudioParameterCallback> & callback)3439 void AudioPolicyService::SetParameterCallback(const std::shared_ptr<AudioParameterCallback>& callback)
3440 {
3441     AUDIO_INFO_LOG("Enter SetParameterCallback");
3442     sptr<AudioManagerListenerStub> parameterChangeCbStub = new(std::nothrow) AudioManagerListenerStub();
3443     if (parameterChangeCbStub == nullptr) {
3444         AUDIO_ERR_LOG("SetParameterCallback parameterChangeCbStub null");
3445         return;
3446     }
3447     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3448     if (gsp == nullptr) {
3449         AUDIO_ERR_LOG("SetParameterCallback g_adProxy null");
3450         return;
3451     }
3452     parameterChangeCbStub->SetParameterCallback(callback);
3453 
3454     sptr<IRemoteObject> object = parameterChangeCbStub->AsObject();
3455     if (object == nullptr) {
3456         AUDIO_ERR_LOG("SetParameterCallback listenerStub object is nullptr");
3457         delete parameterChangeCbStub;
3458         return;
3459     }
3460     AUDIO_DEBUG_LOG("SetParameterCallback done");
3461     gsp->SetParameterCallback(object);
3462 }
3463 
GetMaxRendererInstances()3464 int32_t AudioPolicyService::GetMaxRendererInstances()
3465 {
3466     // init max renderer instances before kvstore start by local prop for bootanimation
3467     char currentMaxRendererInstances[100] = {0}; // 100 for system parameter usage
3468     auto ret = GetParameter("persist.multimedia.audio.maxrendererinstances", "16",
3469         currentMaxRendererInstances, sizeof(currentMaxRendererInstances));
3470     if (ret > 0) {
3471         maxRendererInstances_ = atoi(currentMaxRendererInstances);
3472         AUDIO_INFO_LOG("Get max renderer instances success %{public}d", maxRendererInstances_);
3473     } else {
3474         AUDIO_ERR_LOG("Get max renderer instances failed %{public}d", ret);
3475     }
3476     return maxRendererInstances_;
3477 }
3478 
3479 #ifdef BLUETOOTH_ENABLE
RegisterBluetoothDeathCallback()3480 const sptr<IStandardAudioService> RegisterBluetoothDeathCallback()
3481 {
3482     lock_guard<mutex> lock(g_btProxyMutex);
3483     if (g_btProxy == nullptr) {
3484         auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
3485         if (samgr == nullptr) {
3486             AUDIO_ERR_LOG("RegisterBluetoothDeathCallback: get sa manager failed");
3487             return nullptr;
3488         }
3489         sptr<IRemoteObject> object = samgr->GetSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID);
3490         if (object == nullptr) {
3491             AUDIO_ERR_LOG("RegisterBluetoothDeathCallback: get audio service remote object failed");
3492             return nullptr;
3493         }
3494         g_btProxy = iface_cast<IStandardAudioService>(object);
3495         if (g_btProxy == nullptr) {
3496             AUDIO_ERR_LOG("RegisterBluetoothDeathCallback: get audio service proxy failed");
3497             return nullptr;
3498         }
3499 
3500         // register death recipent
3501         sptr<AudioServerDeathRecipient> asDeathRecipient = new(std::nothrow) AudioServerDeathRecipient(getpid());
3502         if (asDeathRecipient != nullptr) {
3503             asDeathRecipient->SetNotifyCb(std::bind(&AudioPolicyService::BluetoothServiceCrashedCallback,
3504                 std::placeholders::_1));
3505             bool result = object->AddDeathRecipient(asDeathRecipient);
3506             if (!result) {
3507                 AUDIO_ERR_LOG("RegisterBluetoothDeathCallback: failed to add deathRecipient");
3508             }
3509         }
3510     }
3511     sptr<IStandardAudioService> gasp = g_btProxy;
3512     return gasp;
3513 }
3514 
BluetoothServiceCrashedCallback(pid_t pid)3515 void AudioPolicyService::BluetoothServiceCrashedCallback(pid_t pid)
3516 {
3517     AUDIO_INFO_LOG("Bluetooth sa crashed, will restore proxy in next call");
3518     lock_guard<mutex> lock(g_btProxyMutex);
3519     g_btProxy = nullptr;
3520     Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSink();
3521 }
3522 #endif
3523 
RegisterBluetoothListener()3524 void AudioPolicyService::RegisterBluetoothListener()
3525 {
3526 #ifdef BLUETOOTH_ENABLE
3527     AUDIO_INFO_LOG("Enter AudioPolicyService::RegisterBluetoothListener");
3528     Bluetooth::RegisterDeviceObserver(deviceStatusListener_->deviceObserver_);
3529     Bluetooth::AudioA2dpManager::RegisterBluetoothA2dpListener();
3530     Bluetooth::AudioHfpManager::RegisterBluetoothScoListener();
3531     isBtListenerRegistered = true;
3532     const sptr<IStandardAudioService> gsp = RegisterBluetoothDeathCallback();
3533 #endif
3534 }
3535 
UnregisterBluetoothListener()3536 void AudioPolicyService::UnregisterBluetoothListener()
3537 {
3538 #ifdef BLUETOOTH_ENABLE
3539     AUDIO_INFO_LOG("Enter AudioPolicyService::UnregisterBluetoothListener");
3540     Bluetooth::UnregisterDeviceObserver();
3541     Bluetooth::AudioA2dpManager::UnregisterBluetoothA2dpListener();
3542     Bluetooth::AudioHfpManager::UnregisterBluetoothScoListener();
3543     isBtListenerRegistered = false;
3544 #endif
3545 }
3546 
SubscribeAccessibilityConfigObserver()3547 void AudioPolicyService::SubscribeAccessibilityConfigObserver()
3548 {
3549 #ifdef ACCESSIBILITY_ENABLE
3550     accessibilityConfigListener_->SubscribeObserver();
3551     AUDIO_INFO_LOG("Subscribe accessibility config observer successfully");
3552 #endif
3553 }
3554 
GetMinStreamVolume()3555 float AudioPolicyService::GetMinStreamVolume()
3556 {
3557     return audioPolicyManager_.GetMinStreamVolume();
3558 }
3559 
GetMaxStreamVolume()3560 float AudioPolicyService::GetMaxStreamVolume()
3561 {
3562     return audioPolicyManager_.GetMaxStreamVolume();
3563 }
3564 
IsVolumeUnadjustable()3565 bool AudioPolicyService::IsVolumeUnadjustable()
3566 {
3567     return audioPolicyManager_.IsVolumeUnadjustable();
3568 }
3569 
GetStreamVolumeInfoMap(StreamVolumeInfoMap & streamVolumeInfoMap)3570 void AudioPolicyService::GetStreamVolumeInfoMap(StreamVolumeInfoMap &streamVolumeInfoMap)
3571 {
3572     return audioPolicyManager_.GetStreamVolumeInfoMap(streamVolumeInfoMap);
3573 }
3574 
GetSystemVolumeInDb(AudioVolumeType volumeType,int32_t volumeLevel,DeviceType deviceType) const3575 float AudioPolicyService::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel,
3576     DeviceType deviceType) const
3577 {
3578     return audioPolicyManager_.GetSystemVolumeInDb(volumeType, volumeLevel, deviceType);
3579 }
3580 
QueryEffectManagerSceneMode(SupportedEffectConfig & supportedEffectConfig)3581 int32_t AudioPolicyService::QueryEffectManagerSceneMode(SupportedEffectConfig& supportedEffectConfig)
3582 {
3583     int32_t ret = audioEffectManager_.QueryEffectManagerSceneMode(supportedEffectConfig);
3584     return ret;
3585 }
3586 
RegisterDataObserver()3587 void AudioPolicyService::RegisterDataObserver()
3588 {
3589     CreateDataShareHelperInstance();
3590     std::string devicesName = "";
3591     int32_t ret = GetDeviceNameFromDataShareHelper(devicesName);
3592     AUDIO_INFO_LOG("RegisterDataObserver::UpdateDisplayName local name [%{public}s]", devicesName.c_str());
3593     if (ret != SUCCESS) {
3594         AUDIO_ERR_LOG("Local UpdateDisplayName init device failed");
3595         return;
3596     }
3597     SetDisplayName(devicesName, true);
3598     RegisterNameMonitorHelper();
3599 }
3600 
SetPlaybackCapturerFilterInfos(const AudioPlaybackCaptureConfig & config)3601 int32_t AudioPolicyService::SetPlaybackCapturerFilterInfos(const AudioPlaybackCaptureConfig &config)
3602 {
3603     if (!config.silentCapture) {
3604         LoadLoopback();
3605     }
3606     const sptr<IStandardAudioService> gsp = GetAudioServerProxy();
3607     if (gsp == nullptr) {
3608         AUDIO_ERR_LOG("SetPlaybackCapturerFilterInfos error for g_adProxy null");
3609         return ERR_OPERATION_FAILED;
3610     }
3611 
3612     if (gsp->SetCaptureSilentState(config.silentCapture)) {
3613         AUDIO_ERR_LOG("SetPlaybackCapturerFilterInfos, SetCaptureSilentState failed");
3614         return ERR_OPERATION_FAILED;
3615     }
3616 
3617     std::vector<int32_t> targetUsages;
3618     AUDIO_INFO_LOG("SetPlaybackCapturerFilterInfos");
3619     for (size_t i = 0; i < config.filterOptions.usages.size(); i++) {
3620         if (count(targetUsages.begin(), targetUsages.end(), config.filterOptions.usages[i]) == 0) {
3621             targetUsages.emplace_back(config.filterOptions.usages[i]); // deduplicate
3622         }
3623     }
3624 
3625     return gsp->SetSupportStreamUsage(targetUsages);
3626 }
3627 
UpdateOutputDeviceSelectedByCalling(DeviceType deviceType)3628 void AudioPolicyService::UpdateOutputDeviceSelectedByCalling(DeviceType deviceType)
3629 {
3630     if ((deviceType == DEVICE_TYPE_DEFAULT) || (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP)) {
3631         return;
3632     }
3633     auto uid = IPCSkeleton::GetCallingUid();
3634     std::lock_guard<std::mutex> lock(outputDeviceSelectedByCallingMutex_);
3635     if (deviceType == DEVICE_TYPE_NONE) {
3636         outputDeviceSelectedByCalling_.erase(uid);
3637         return;
3638     }
3639     outputDeviceSelectedByCalling_[uid] = deviceType;
3640 }
3641 
3642 } // namespace AudioStandard
3643 } // namespace OHOS
3644