• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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_errors.h"
17 #include "audio_focus_parser.h"
18 #include "iservice_registry.h"
19 #include "audio_log.h"
20 #include "hisysevent.h"
21 #include "system_ability_definition.h"
22 #include "audio_manager_listener_stub.h"
23 
24 #ifdef BLUETOOTH_ENABLE
25 #include "audio_bluetooth_manager.h"
26 #endif
27 
28 #include "audio_policy_service.h"
29 
30 
31 namespace OHOS {
32 namespace AudioStandard {
33 using namespace std;
34 
35 const uint32_t PCM_8_BIT = 8;
36 const uint32_t PCM_16_BIT = 16;
37 const uint32_t PCM_24_BIT = 24;
38 const uint32_t PCM_32_BIT = 32;
39 const uint32_t BT_BUFFER_ADJUSTMENT_FACTOR = 50;
40 static sptr<IStandardAudioService> g_adProxy = nullptr;
41 static int32_t startDeviceId = 1;
42 mutex g_adProxyMutex;
43 
~AudioPolicyService()44 AudioPolicyService::~AudioPolicyService()
45 {
46     AUDIO_ERR_LOG("~AudioPolicyService()");
47     Deinit();
48 }
49 
Init(void)50 bool AudioPolicyService::Init(void)
51 {
52     AUDIO_INFO_LOG("AudioPolicyService init");
53     serviceFlag_.reset();
54     audioPolicyManager_.Init();
55     if (!configParser_.LoadConfiguration()) {
56         AUDIO_ERR_LOG("Audio Config Load Configuration failed");
57         return false;
58     }
59     if (!configParser_.Parse()) {
60         AUDIO_ERR_LOG("Audio Config Parse failed");
61         return false;
62     }
63     std::unique_ptr<AudioToneParser> audioToneParser = make_unique<AudioToneParser>();
64     CHECK_AND_RETURN_RET_LOG(audioToneParser != nullptr, false, "Failed to create AudioToneParser");
65     std::string AUDIO_TONE_CONFIG_FILE = "system/etc/audio/audio_tone_dtmf_config.xml";
66 
67     if (audioToneParser->LoadConfig(toneDescriptorMap)) {
68         AUDIO_ERR_LOG("Audio Tone Load Configuration failed");
69         return false;
70     }
71 
72     std::unique_ptr<AudioFocusParser> audioFocusParser = make_unique<AudioFocusParser>();
73     CHECK_AND_RETURN_RET_LOG(audioFocusParser != nullptr, false, "Failed to create AudioFocusParser");
74     std::string AUDIO_FOCUS_CONFIG_FILE = "system/etc/audio/audio_interrupt_policy_config.xml";
75 
76     if (audioFocusParser->LoadConfig(focusMap_)) {
77         AUDIO_ERR_LOG("Audio Interrupt Load Configuration failed");
78         return false;
79     }
80 
81     if (deviceStatusListener_->RegisterDeviceStatusListener()) {
82         AUDIO_ERR_LOG("[Policy Service] Register for device status events failed");
83         return false;
84     }
85 
86     return true;
87 }
88 
GetAudioPolicyServiceProxy()89 const sptr<IStandardAudioService> AudioPolicyService::GetAudioPolicyServiceProxy()
90 {
91     AUDIO_DEBUG_LOG("[Policy Service] Start get audio policy service proxy.");
92     lock_guard<mutex> lock(g_adProxyMutex);
93 
94     if (g_adProxy == nullptr) {
95         auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
96         if (samgr == nullptr) {
97             AUDIO_ERR_LOG("[Policy Service] Get samgr failed.");
98             return nullptr;
99         }
100 
101         sptr<IRemoteObject> object = samgr->GetSystemAbility(AUDIO_DISTRIBUTED_SERVICE_ID);
102         if (object == nullptr) {
103             AUDIO_ERR_LOG("[Policy Service] audio service remote object is NULL.");
104             return nullptr;
105         }
106 
107         g_adProxy = iface_cast<IStandardAudioService>(object);
108         if (g_adProxy == nullptr) {
109             AUDIO_ERR_LOG("[Policy Service] init g_adProxy is NULL.");
110             return nullptr;
111         }
112     }
113     const sptr<IStandardAudioService> gsp = g_adProxy;
114     return gsp;
115 }
116 
InitKVStore()117 void AudioPolicyService::InitKVStore()
118 {
119     audioPolicyManager_.InitKVStore();
120 }
121 
ConnectServiceAdapter()122 bool AudioPolicyService::ConnectServiceAdapter()
123 {
124     if (!audioPolicyManager_.ConnectServiceAdapter()) {
125         AUDIO_ERR_LOG("AudioPolicyService::ConnectServiceAdapter  Error in connecting to audio service adapter");
126         return false;
127     }
128 
129     OnServiceConnected(AudioServiceIndex::AUDIO_SERVICE_INDEX);
130 
131     return true;
132 }
133 
Deinit(void)134 void AudioPolicyService::Deinit(void)
135 {
136     AUDIO_ERR_LOG("Policy service died. closing active ports");
137     std::for_each(IOHandles_.begin(), IOHandles_.end(), [&](std::pair<std::string, AudioIOHandle> handle) {
138         audioPolicyManager_.CloseAudioPort(handle.second);
139     });
140 
141     IOHandles_.clear();
142 #ifdef ACCESSIBILITY_ENABLE
143     accessibilityConfigListener_->UnsubscribeObserver();
144 #endif
145     deviceStatusListener_->UnRegisterDeviceStatusListener();
146 
147     if (isBtListenerRegistered) {
148         UnregisterBluetoothListener();
149     }
150     return;
151 }
152 
SetAudioSessionCallback(AudioSessionCallback * callback)153 int32_t AudioPolicyService::SetAudioSessionCallback(AudioSessionCallback *callback)
154 {
155     return audioPolicyManager_.SetAudioSessionCallback(callback);
156 }
157 
SetStreamVolume(AudioStreamType streamType,float volume)158 int32_t AudioPolicyService::SetStreamVolume(AudioStreamType streamType, float volume)
159 {
160     if (streamType == STREAM_VOICE_CALL) {
161         const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
162         if (gsp == nullptr) {
163             AUDIO_ERR_LOG("AudioPolicyService: SetVoiceVolume gsp null");
164         } else {
165             gsp->SetVoiceVolume(volume);
166         }
167     }
168     return audioPolicyManager_.SetStreamVolume(streamType, volume);
169 }
170 
GetStreamVolume(AudioStreamType streamType) const171 float AudioPolicyService::GetStreamVolume(AudioStreamType streamType) const
172 {
173     return audioPolicyManager_.GetStreamVolume(streamType);
174 }
175 
SetLowPowerVolume(int32_t streamId,float volume) const176 int32_t AudioPolicyService::SetLowPowerVolume(int32_t streamId, float volume) const
177 {
178     return streamCollector_.SetLowPowerVolume(streamId, volume);
179 }
180 
GetLowPowerVolume(int32_t streamId) const181 float AudioPolicyService::GetLowPowerVolume(int32_t streamId) const
182 {
183     return streamCollector_.GetLowPowerVolume(streamId);
184 }
185 
GetSingleStreamVolume(int32_t streamId) const186 float AudioPolicyService::GetSingleStreamVolume(int32_t streamId) const
187 {
188     return streamCollector_.GetSingleStreamVolume(streamId);
189 }
190 
SetStreamMute(AudioStreamType streamType,bool mute) const191 int32_t AudioPolicyService::SetStreamMute(AudioStreamType streamType, bool mute) const
192 {
193     return audioPolicyManager_.SetStreamMute(streamType, mute);
194 }
195 
SetSourceOutputStreamMute(int32_t uid,bool setMute) const196 int32_t AudioPolicyService::SetSourceOutputStreamMute(int32_t uid, bool setMute) const
197 {
198     return audioPolicyManager_.SetSourceOutputStreamMute(uid, setMute);
199 }
200 
201 
GetStreamMute(AudioStreamType streamType) const202 bool AudioPolicyService::GetStreamMute(AudioStreamType streamType) const
203 {
204     return audioPolicyManager_.GetStreamMute(streamType);
205 }
206 
PrintSinkInput(SinkInput sinkInput)207 inline std::string PrintSinkInput(SinkInput sinkInput)
208 {
209     std::stringstream value;
210     value << "streamId:[" << sinkInput.streamId << "] ";
211     value << "streamType:[" << sinkInput.streamType << "] ";
212     value << "uid:[" << sinkInput.uid << "] ";
213     value << "pid:[" << sinkInput.pid << "] ";
214     value << "statusMark:[" << sinkInput.statusMark << "] ";
215     value << "sinkName:[" << sinkInput.sinkName << "] ";
216     value << "startTime:[" << sinkInput.startTime << "]";
217     return value.str();
218 }
219 
GetSelectedDeviceInfo(int32_t uid,int32_t pid,AudioStreamType streamType)220 std::string AudioPolicyService::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType)
221 {
222     (void)streamType;
223 
224     if (!routerMap_.count(uid)) {
225         AUDIO_INFO_LOG("GetSelectedDeviceInfo no such uid[%{public}d]", uid);
226         return "";
227     }
228     std::string selectedDevice = "";
229     if (routerMap_[uid].second == pid) {
230         selectedDevice = routerMap_[uid].first;
231     } else if (routerMap_[uid].second == G_UNKNOWN_PID) {
232         routerMap_[uid].second = pid;
233         selectedDevice = routerMap_[uid].first;
234     } else {
235         AUDIO_INFO_LOG("GetSelectedDeviceInfo: uid[%{public}d] changed pid, get local as defalut", uid);
236         routerMap_.erase(uid);
237         selectedDevice = LOCAL_NETWORK_ID;
238     }
239 
240     if (LOCAL_NETWORK_ID == selectedDevice) {
241         AUDIO_INFO_LOG("GetSelectedDeviceInfo: uid[%{public}d]-->local.", uid);
242         return "";
243     }
244     // check if connected.
245     bool isConnected = false;
246     for (auto device : connectedDevices_) {
247         if (device->networkId_ == selectedDevice) {
248             isConnected = true;
249             break;
250         }
251     }
252 
253     if (isConnected) {
254         AUDIO_INFO_LOG("GetSelectedDeviceInfo result[%{public}s]", selectedDevice.c_str());
255         return selectedDevice;
256     } else {
257         routerMap_.erase(uid);
258         AUDIO_INFO_LOG("GetSelectedDeviceInfo device already disconnected.");
259         return "";
260     }
261 }
262 
NotifyRemoteRenderState(std::string networkId,std::string condition,std::string value)263 void AudioPolicyService::NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value)
264 {
265     AUDIO_INFO_LOG("NotifyRemoteRenderState device<%{public}s> condition:%{public}s value:%{public}s",
266         networkId.c_str(), condition.c_str(), value.c_str());
267 
268     vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
269     vector<SinkInput> targetSinkInputs = {};
270     for (auto sinkInput : sinkInputs) {
271         if (sinkInput.sinkName == networkId) {
272             targetSinkInputs.push_back(sinkInput);
273         }
274     }
275     AUDIO_INFO_LOG("NotifyRemoteRenderState move [%{public}zu] of all [%{public}zu]sink-inputs to local.",
276         targetSinkInputs.size(), sinkInputs.size());
277     sptr<AudioDeviceDescriptor> localDevice = new(std::nothrow) AudioDeviceDescriptor();
278     if (localDevice == nullptr) {
279         AUDIO_ERR_LOG("Device error: null device.");
280         return;
281     }
282     localDevice->networkId_ = LOCAL_NETWORK_ID;
283     localDevice->deviceRole_ = DeviceRole::OUTPUT_DEVICE;
284     localDevice->deviceType_ = DeviceType::DEVICE_TYPE_SPEAKER;
285 
286     int32_t ret = MoveToLocalOutputDevice(targetSinkInputs, localDevice);
287     CHECK_AND_RETURN_LOG((ret == SUCCESS), "MoveToLocalOutputDevice failed!");
288 
289     // Suspend device, notify audio stream manager that device has been changed.
290     ret = audioPolicyManager_.SuspendAudioDevice(networkId, true);
291     CHECK_AND_RETURN_LOG((ret == SUCCESS), "SuspendAudioDevice failed!");
292 
293     std::vector<sptr<AudioDeviceDescriptor>> desc = {};
294     desc.push_back(localDevice);
295     UpdateTrackerDeviceChange(desc);
296     AUDIO_INFO_LOG("NotifyRemoteRenderState success");
297 }
298 
SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)299 int32_t AudioPolicyService::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
300     std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
301 {
302     AUDIO_INFO_LOG("SelectOutputDevice start for uid[%{public}d]", audioRendererFilter->uid);
303     // check size == 1 && output device
304     int deviceSize = audioDeviceDescriptors.size();
305     if (deviceSize != 1 || audioDeviceDescriptors[0]->deviceRole_ != DeviceRole::OUTPUT_DEVICE) {
306         AUDIO_ERR_LOG("Device error: size[%{public}d] deviceRole[%{public}d]", deviceSize,
307             static_cast<int32_t>(audioDeviceDescriptors[0]->deviceRole_));
308         return ERR_INVALID_OPERATION;
309     }
310 
311     std::string networkId = audioDeviceDescriptors[0]->networkId_;
312     DeviceType deviceType = audioDeviceDescriptors[0]->deviceType_;
313 
314     // switch between local devices
315     if (!isCurrentRemoteRenderer && LOCAL_NETWORK_ID == networkId && currentActiveDevice_ != deviceType) {
316         if (deviceType == DeviceType::DEVICE_TYPE_DEFAULT) {
317             deviceType = FetchHighPriorityDevice(true);
318         }
319         return SelectNewDevice(DeviceRole::OUTPUT_DEVICE, deviceType);
320     }
321 
322     int32_t targetUid = audioRendererFilter->uid;
323     AudioStreamType targetStreamType = audioRendererFilter->streamType;
324     // move all sink-input.
325     bool moveAll = false;
326     if (targetUid == -1) {
327         AUDIO_INFO_LOG("move all sink.");
328         moveAll = true;
329         routerMap_.clear();
330     }
331 
332     // find sink-input id with audioRendererFilter
333     std::vector<SinkInput> targetSinkInputs = {};
334     vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
335 
336     for (size_t i = 0; i < sinkInputs.size(); i++) {
337         if (sinkInputs[i].uid == dAudioClientUid) {
338             AUDIO_INFO_LOG("Find sink-input with daudio[%{public}d]", sinkInputs[i].pid);
339             continue;
340         }
341         AUDIO_DEBUG_LOG("sinkinput[%{public}zu]:%{public}s", i, PrintSinkInput(sinkInputs[i]).c_str());
342         if (moveAll || (targetUid == sinkInputs[i].uid && targetStreamType == sinkInputs[i].streamType)) {
343             targetSinkInputs.push_back(sinkInputs[i]);
344         }
345     }
346 
347     // move target uid, but no stream played yet, record the routing info for first start.
348     if (!moveAll && targetSinkInputs.size() == 0) {
349         return RememberRoutingInfo(audioRendererFilter, audioDeviceDescriptors[0]);
350     }
351 
352     int32_t ret = SUCCESS;
353     if (LOCAL_NETWORK_ID == networkId) {
354         ret = MoveToLocalOutputDevice(targetSinkInputs, audioDeviceDescriptors[0]);
355     } else {
356         ret = MoveToRemoteOutputDevice(targetSinkInputs, audioDeviceDescriptors[0]);
357     }
358     UpdateTrackerDeviceChange(audioDeviceDescriptors);
359 
360     AUDIO_INFO_LOG("SelectOutputDevice result[%{public}d], [%{public}zu] moved.", ret, targetSinkInputs.size());
361     return ret;
362 }
363 
GetRemoteModuleName(std::string networkId,DeviceRole role)364 inline std::string GetRemoteModuleName(std::string networkId, DeviceRole role)
365 {
366     return networkId + (role == DeviceRole::OUTPUT_DEVICE ? "_out" : "_in");
367 }
368 
RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter,sptr<AudioDeviceDescriptor> deviceDescriptor)369 int32_t AudioPolicyService::RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter,
370     sptr<AudioDeviceDescriptor> deviceDescriptor)
371 {
372     AUDIO_INFO_LOG("RememberRoutingInfo for uid[%{public}d] device[%{public}s]", audioRendererFilter->uid,
373         deviceDescriptor->networkId_.c_str());
374     if (deviceDescriptor->networkId_ == LOCAL_NETWORK_ID) {
375         routerMap_[audioRendererFilter->uid] = std::pair(LOCAL_NETWORK_ID, G_UNKNOWN_PID);
376         return SUCCESS;
377     }
378     // remote device.
379     std::string networkId = deviceDescriptor->networkId_;
380     DeviceRole deviceRole = deviceDescriptor->deviceRole_;
381 
382     std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
383     if (!IOHandles_.count(moduleName)) {
384         AUDIO_ERR_LOG("Device error: no such device:%{public}s", networkId.c_str());
385         return ERR_INVALID_PARAM;
386     }
387     const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
388     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
389     int32_t ret = gsp->CheckRemoteDeviceState(networkId, deviceRole, true);
390     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!");
391 
392     routerMap_[audioRendererFilter->uid] = std::pair(networkId, G_UNKNOWN_PID);
393     return SUCCESS;
394 }
395 
MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,sptr<AudioDeviceDescriptor> localDeviceDescriptor)396 int32_t AudioPolicyService::MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,
397     sptr<AudioDeviceDescriptor> localDeviceDescriptor)
398 {
399     AUDIO_INFO_LOG("MoveToLocalOutputDevice for [%{public}zu] sink-inputs", sinkInputIds.size());
400     // check
401     if (LOCAL_NETWORK_ID != localDeviceDescriptor->networkId_) {
402         AUDIO_ERR_LOG("MoveToLocalOutputDevice failed: not a local device.");
403         return ERR_INVALID_OPERATION;
404     }
405 
406     DeviceType localDeviceType = localDeviceDescriptor->deviceType_;
407     if (localDeviceType != currentActiveDevice_) {
408         AUDIO_WARNING_LOG("MoveToLocalOutputDevice: device[%{public}d] not active, use device[%{public}d] instead.",
409             static_cast<int32_t>(localDeviceType), static_cast<int32_t>(currentActiveDevice_));
410     }
411 
412     // start move.
413     uint32_t sinkId = -1; // invalid sink id, use sink name instead.
414     std::string sinkName = GetPortName(currentActiveDevice_);
415     for (size_t i = 0; i < sinkInputIds.size(); i++) {
416         if (audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, sinkName) != SUCCESS) {
417             AUDIO_ERR_LOG("move [%{public}d] to local failed", sinkInputIds[i].streamId);
418             return ERROR;
419         }
420         routerMap_[sinkInputIds[i].uid] = std::pair(LOCAL_NETWORK_ID, sinkInputIds[i].pid);
421     }
422 
423     isCurrentRemoteRenderer = false;
424     return SUCCESS;
425 }
426 
OpenRemoteAudioDevice(std::string networkId,DeviceRole deviceRole,DeviceType deviceType,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)427 int32_t AudioPolicyService::OpenRemoteAudioDevice(std::string networkId, DeviceRole deviceRole, DeviceType deviceType,
428     sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
429 {
430     // open the test device. We should open it when device is online.
431     std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
432     AudioModuleInfo remoteDeviceInfo = ConstructRemoteAudioModuleInfo(networkId, deviceRole, deviceType);
433     AudioIOHandle remoteIOIdx = audioPolicyManager_.OpenAudioPort(remoteDeviceInfo);
434     AUDIO_DEBUG_LOG("OpenAudioPort remoteIOIdx %{public}d", remoteIOIdx);
435     CHECK_AND_RETURN_RET_LOG(remoteIOIdx != OPEN_PORT_FAILURE, ERR_INVALID_HANDLE, "OpenAudioPort failed %{public}d",
436         remoteIOIdx);
437     IOHandles_[moduleName] = remoteIOIdx;
438 
439     // If device already in list, remove it else do not modify the list.
440     auto isPresent = [&deviceType, &networkId] (const sptr<AudioDeviceDescriptor> &descriptor) {
441         return descriptor->deviceType_ == deviceType && descriptor->networkId_ == networkId;
442     };
443     connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent),
444         connectedDevices_.end());
445     connectedDevices_.insert(connectedDevices_.begin(), remoteDeviceDescriptor);
446     return SUCCESS;
447 }
448 
MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)449 int32_t AudioPolicyService::MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,
450     sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
451 {
452     AUDIO_INFO_LOG("MoveToRemoteOutputDevice for [%{public}zu] sink-inputs", sinkInputIds.size());
453 
454     std::string networkId = remoteDeviceDescriptor->networkId_;
455     DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_;
456     DeviceType deviceType = remoteDeviceDescriptor->deviceType_;
457 
458     if (networkId == LOCAL_NETWORK_ID) { // check: networkid
459         AUDIO_ERR_LOG("MoveToRemoteOutputDevice failed: not a remote device.");
460         return ERR_INVALID_OPERATION;
461     }
462 
463     uint32_t sinkId = -1; // invalid sink id, use sink name instead.
464     std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
465     if (IOHandles_.count(moduleName)) {
466         IOHandles_[moduleName]; // mIOHandle is module id, not equal to sink id.
467     } else {
468         AUDIO_ERR_LOG("no such device.");
469         if (!isOpenRemoteDevice) {
470             return ERR_INVALID_PARAM;
471         } else {
472             return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor);
473         }
474     }
475 
476     const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
477     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
478     CHECK_AND_RETURN_RET_LOG((gsp->CheckRemoteDeviceState(networkId, deviceRole, true) == SUCCESS),
479         ERR_OPERATION_FAILED, "remote device state is invalid!");
480 
481     // start move.
482     for (size_t i = 0; i < sinkInputIds.size(); i++) {
483         if (audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, networkId) != SUCCESS) {
484             AUDIO_ERR_LOG("move [%{public}d] failed", sinkInputIds[i].streamId);
485             return ERROR;
486         }
487         routerMap_[sinkInputIds[i].uid] = std::pair(networkId, sinkInputIds[i].pid);
488     }
489 
490     if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) {
491         AUDIO_WARNING_LOG("Not defult type[%{public}d] on device:[%{public}s]", deviceType, networkId.c_str());
492     }
493     isCurrentRemoteRenderer = true;
494     return SUCCESS;
495 }
496 
PrintSourceOutput(SourceOutput sourceOutput)497 inline std::string PrintSourceOutput(SourceOutput sourceOutput)
498 {
499     std::stringstream value;
500     value << "streamId:[" << sourceOutput.streamId << "] ";
501     value << "streamType:[" << sourceOutput.streamType << "] ";
502     value << "uid:[" << sourceOutput.uid << "] ";
503     value << "pid:[" << sourceOutput.pid << "] ";
504     value << "statusMark:[" << sourceOutput.statusMark << "] ";
505     value << "deviceSourceId:[" << sourceOutput.deviceSourceId << "] ";
506     value << "startTime:[" << sourceOutput.startTime << "]";
507     return value.str();
508 }
509 
SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)510 int32_t AudioPolicyService::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
511     std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
512 {
513     // check size == 1 && output device
514     int deviceSize = audioDeviceDescriptors.size();
515     if (deviceSize != 1 || audioDeviceDescriptors[0]->deviceRole_ != DeviceRole::INPUT_DEVICE) {
516         AUDIO_ERR_LOG("Device error: size[%{public}d] deviceRole[%{public}d]", deviceSize,
517             static_cast<int32_t>(audioDeviceDescriptors[0]->deviceRole_));
518         return ERR_INVALID_OPERATION;
519     }
520     std::string networkId = audioDeviceDescriptors[0]->networkId_;
521     DeviceType deviceType = audioDeviceDescriptors[0]->deviceType_;
522 
523     // switch between local devices
524     if (LOCAL_NETWORK_ID == networkId && activeInputDevice_ != deviceType) {
525         if (deviceType == DeviceType::DEVICE_TYPE_DEFAULT) {
526             deviceType = FetchHighPriorityDevice(false);
527         }
528         return SelectNewDevice(DeviceRole::INPUT_DEVICE, deviceType);
529     }
530 
531     if (!remoteCapturerSwitch) {
532         AUDIO_DEBUG_LOG("remote capturer capbility is not open now");
533         return SUCCESS;
534     }
535     int32_t targetUid = audioCapturerFilter->uid;
536     // move all source-output.
537     bool moveAll = false;
538     if (targetUid == -1) {
539         AUDIO_DEBUG_LOG("move all sink.");
540         moveAll = true;
541     }
542 
543     // find source-output id with audioCapturerFilter
544     std::vector<uint32_t> targetSourceOutputIds = {};
545     vector<SourceOutput> sourceOutputs = audioPolicyManager_.GetAllSourceOutputs();
546     for (size_t i = 0; i < sourceOutputs.size();i++) {
547         AUDIO_DEBUG_LOG("SourceOutput[%{public}zu]:%{public}s", i, PrintSourceOutput(sourceOutputs[i]).c_str());
548         if (moveAll || (targetUid == sourceOutputs[i].uid)) {
549             targetSourceOutputIds.push_back(sourceOutputs[i].paStreamId);
550         }
551     }
552 
553     int32_t ret = SUCCESS;
554     if (LOCAL_NETWORK_ID == networkId) {
555         ret = MoveToLocalInputDevice(targetSourceOutputIds, audioDeviceDescriptors[0]);
556     } else {
557         ret = MoveToRemoteInputDevice(targetSourceOutputIds, audioDeviceDescriptors[0]);
558     }
559 
560     AUDIO_INFO_LOG("SelectInputDevice result[%{public}d]", ret);
561     return ret;
562 }
563 
MoveToLocalInputDevice(std::vector<uint32_t> sourceOutputIds,sptr<AudioDeviceDescriptor> localDeviceDescriptor)564 int32_t AudioPolicyService::MoveToLocalInputDevice(std::vector<uint32_t> sourceOutputIds,
565     sptr<AudioDeviceDescriptor> localDeviceDescriptor)
566 {
567     AUDIO_INFO_LOG("MoveToLocalInputDevice start");
568     // check
569     if (LOCAL_NETWORK_ID != localDeviceDescriptor->networkId_) {
570         AUDIO_ERR_LOG("MoveToLocalInputDevice failed: not a local device.");
571         return ERR_INVALID_OPERATION;
572     }
573 
574     DeviceType localDeviceType = localDeviceDescriptor->deviceType_;
575     if (localDeviceType != activeInputDevice_) {
576         AUDIO_WARNING_LOG("MoveToLocalInputDevice: device[%{public}d] not active, use device[%{public}d] instead.",
577             static_cast<int32_t>(localDeviceType), static_cast<int32_t>(activeInputDevice_));
578     }
579 
580     // start move.
581     uint32_t sourceId = -1; // invalid source id, use source name instead.
582     std::string sourceName = GetPortName(activeInputDevice_);
583     for (size_t i = 0; i < sourceOutputIds.size(); i++) {
584         if (audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputIds[i], sourceId, sourceName) != SUCCESS) {
585             AUDIO_DEBUG_LOG("move [%{public}d] to local failed", sourceOutputIds[i]);
586             return ERROR;
587         }
588     }
589 
590     return SUCCESS;
591 }
592 
MoveToRemoteInputDevice(std::vector<uint32_t> sourceOutputIds,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)593 int32_t AudioPolicyService::MoveToRemoteInputDevice(std::vector<uint32_t> sourceOutputIds,
594     sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
595 {
596     AUDIO_INFO_LOG("MoveToRemoteInputDevice start");
597 
598     std::string networkId = remoteDeviceDescriptor->networkId_;
599     DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_;
600     DeviceType deviceType = remoteDeviceDescriptor->deviceType_;
601 
602     // check: networkid
603     if (networkId == LOCAL_NETWORK_ID) {
604         AUDIO_ERR_LOG("MoveToRemoteInputDevice failed: not a remote device.");
605         return ERR_INVALID_OPERATION;
606     }
607 
608     uint32_t sourceId = -1; // invalid sink id, use sink name instead.
609     std::string moduleName = GetRemoteModuleName(networkId, deviceRole);
610     if (IOHandles_.count(moduleName)) {
611         IOHandles_[moduleName]; // mIOHandle is module id, not equal to sink id.
612     } else {
613         AUDIO_ERR_LOG("no such device.");
614         if (!isOpenRemoteDevice) {
615             return ERR_INVALID_PARAM;
616         } else {
617             return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor);
618         }
619     }
620 
621     // start move.
622     for (size_t i = 0; i < sourceOutputIds.size(); i++) {
623         if (audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputIds[i], sourceId, networkId) != SUCCESS) {
624             AUDIO_DEBUG_LOG("move [%{public}d] failed", sourceOutputIds[i]);
625             return ERROR;
626         }
627     }
628 
629     if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) {
630         AUDIO_DEBUG_LOG("Not defult type[%{public}d] on device:[%{public}s]", deviceType, networkId.c_str());
631     }
632     return SUCCESS;
633 }
634 
IsStreamActive(AudioStreamType streamType) const635 bool AudioPolicyService::IsStreamActive(AudioStreamType streamType) const
636 {
637     return audioPolicyManager_.IsStreamActive(streamType);
638 }
639 
GetPortName(InternalDeviceType deviceType)640 std::string AudioPolicyService::GetPortName(InternalDeviceType deviceType)
641 {
642     std::string portName = PORT_NONE;
643     switch (deviceType) {
644         case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
645             portName = BLUETOOTH_SPEAKER;
646             break;
647         case InternalDeviceType::DEVICE_TYPE_SPEAKER:
648         case InternalDeviceType::DEVICE_TYPE_WIRED_HEADSET:
649         case InternalDeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
650         case InternalDeviceType::DEVICE_TYPE_USB_HEADSET:
651         case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
652             portName = PRIMARY_SPEAKER;
653             break;
654         case InternalDeviceType::DEVICE_TYPE_MIC:
655             portName = PRIMARY_MIC;
656             break;
657         case InternalDeviceType::DEVICE_TYPE_FILE_SINK:
658             portName = FILE_SINK;
659             break;
660         case InternalDeviceType::DEVICE_TYPE_FILE_SOURCE:
661             portName = FILE_SOURCE;
662             break;
663         default:
664             portName = PORT_NONE;
665             break;
666     }
667 
668     AUDIO_INFO_LOG("port name is %{public}s", portName.c_str());
669     return portName;
670 }
671 
672 // private method
ConstructRemoteAudioModuleInfo(std::string networkId,DeviceRole deviceRole,DeviceType deviceType)673 AudioModuleInfo AudioPolicyService::ConstructRemoteAudioModuleInfo(std::string networkId, DeviceRole deviceRole,
674     DeviceType deviceType)
675 {
676     AudioModuleInfo audioModuleInfo = {};
677 
678     if (deviceRole == DeviceRole::OUTPUT_DEVICE) {
679         audioModuleInfo.lib = "libmodule-hdi-sink.z.so";
680         audioModuleInfo.format = "s16le"; // 16bit little endian
681         audioModuleInfo.fixedLatency = "1"; // here we need to set latency fixed for a fixed buffer size.
682     } else if (deviceRole == DeviceRole::INPUT_DEVICE) {
683         audioModuleInfo.lib = "libmodule-hdi-source.z.so";
684         audioModuleInfo.format = "s16le"; // we assume it is bigger endian
685     } else {
686         AUDIO_ERR_LOG("Invalid flag provided %{public}d", static_cast<int32_t>(deviceType));
687     }
688 
689     audioModuleInfo.name = networkId; // used as "sink_name" in hdi_sink.c, hope we could use name to find target sink.
690     audioModuleInfo.networkId = networkId;
691 
692     std::stringstream typeValue;
693     typeValue << static_cast<int32_t>(deviceType);
694     audioModuleInfo.deviceType = typeValue.str();
695 
696     audioModuleInfo.adapterName = "remote";
697     audioModuleInfo.className = "remote"; // used in renderer_sink_adapter.c
698     audioModuleInfo.fileName = "remote_dump_file";
699 
700     audioModuleInfo.channels = "2";
701     audioModuleInfo.rate = "48000";
702     audioModuleInfo.bufferSize = "4096";
703 
704     return audioModuleInfo;
705 }
706 
GetDevices(DeviceFlag deviceFlag)707 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDevices(DeviceFlag deviceFlag)
708 {
709     AUDIO_INFO_LOG("Entered AudioPolicyService::%{public}s", __func__);
710     std::vector<sptr<AudioDeviceDescriptor>> deviceList = {};
711 
712     if (deviceFlag < DeviceFlag::OUTPUT_DEVICES_FLAG || deviceFlag > DeviceFlag::ALL_L_D_DEVICES_FLAG) {
713         AUDIO_ERR_LOG("Invalid flag provided %{public}d", deviceFlag);
714         return deviceList;
715     }
716 
717     if (deviceFlag == DeviceFlag::ALL_L_D_DEVICES_FLAG) {
718         return connectedDevices_;
719     }
720 
721     for (const auto& device : connectedDevices_) {
722         if (device == nullptr) {
723             continue;
724         }
725         bool filterAllLocal = deviceFlag == DeviceFlag::ALL_DEVICES_FLAG && device->networkId_ == LOCAL_NETWORK_ID;
726         bool filterLocalOutput = deviceFlag == DeviceFlag::OUTPUT_DEVICES_FLAG
727             && device->networkId_ == LOCAL_NETWORK_ID
728             && device->deviceRole_ == DeviceRole::OUTPUT_DEVICE;
729         bool filterLocalInput = deviceFlag == DeviceFlag::INPUT_DEVICES_FLAG
730             && device->networkId_ == LOCAL_NETWORK_ID
731             && device->deviceRole_ == DeviceRole::INPUT_DEVICE;
732 
733         bool filterAllRemote = deviceFlag == DeviceFlag::ALL_DISTRIBUTED_DEVICES_FLAG
734             && device->networkId_ != LOCAL_NETWORK_ID;
735         bool filterRemoteOutput = deviceFlag == DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG
736             && device->networkId_ != LOCAL_NETWORK_ID
737             && device->deviceRole_ == DeviceRole::OUTPUT_DEVICE;
738         bool filterRemoteInput = deviceFlag == DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG
739             && device->networkId_ != LOCAL_NETWORK_ID
740         && device->deviceRole_ == DeviceRole::INPUT_DEVICE;
741 
742         if (filterAllLocal || filterLocalOutput || filterLocalInput || filterAllRemote || filterRemoteOutput
743             || filterRemoteInput) {
744             sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*device);
745             deviceList.push_back(devDesc);
746         }
747     }
748 
749     AUDIO_INFO_LOG("GetDevices list size = [%{public}zu]", deviceList.size());
750     return deviceList;
751 }
752 
GetActiveOutputDeviceDescriptors()753 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetActiveOutputDeviceDescriptors()
754 {
755     AUDIO_INFO_LOG("Entered AudioPolicyService::%{public}s", __func__);
756     std::vector<sptr<AudioDeviceDescriptor>> deviceList = {};
757     for (const auto& device : connectedDevices_) {
758         if (device == nullptr) {
759             continue;
760         }
761         bool filterLocalOutput = ((currentActiveDevice_ == device->deviceType_)
762             && (device->networkId_ == LOCAL_NETWORK_ID)
763             && (device->deviceRole_ == DeviceRole::OUTPUT_DEVICE));
764         if (filterLocalOutput) {
765             sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*device);
766             deviceList.push_back(devDesc);
767             return deviceList;
768         }
769     }
770 
771     return deviceList;
772 }
773 
FetchHighPriorityDevice(bool isOutputDevice=true)774 DeviceType AudioPolicyService::FetchHighPriorityDevice(bool isOutputDevice = true)
775 {
776     AUDIO_DEBUG_LOG("Entered AudioPolicyService::%{public}s", __func__);
777     DeviceType priorityDevice = isOutputDevice ? DEVICE_TYPE_SPEAKER : DEVICE_TYPE_MIC;
778     std::vector<DeviceType> priorityList = isOutputDevice ? outputPriorityList_ : inputPriorityList_;
779     for (const auto &device : priorityList) {
780         auto isPresent = [&device] (const sptr<AudioDeviceDescriptor> &desc) {
781             CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
782             return desc->deviceType_ == device;
783         };
784 
785         auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
786         if (itr != connectedDevices_.end()) {
787             priorityDevice = (*itr)->deviceType_;
788             break;
789         }
790     }
791 
792     return priorityDevice;
793 }
794 
SetMicrophoneMute(bool isMute)795 int32_t AudioPolicyService::SetMicrophoneMute(bool isMute)
796 {
797     AUDIO_DEBUG_LOG("SetMicrophoneMute state[%{public}d]", isMute);
798     const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
799     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
800     return gsp->SetMicrophoneMute(isMute);
801 }
802 
IsMicrophoneMute()803 bool AudioPolicyService::IsMicrophoneMute()
804 {
805     AUDIO_DEBUG_LOG("Enter IsMicrophoneMute");
806     const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
807     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, false, "Service proxy unavailable");
808     return gsp->IsMicrophoneMute();
809 }
810 
UpdateActiveDeviceRoute(InternalDeviceType deviceType)811 void UpdateActiveDeviceRoute(InternalDeviceType deviceType)
812 {
813     AUDIO_DEBUG_LOG("UpdateActiveDeviceRoute Device type[%{public}d]", deviceType);
814 
815     auto ret = SUCCESS;
816 
817     switch (deviceType) {
818         case DEVICE_TYPE_BLUETOOTH_SCO:
819         case DEVICE_TYPE_USB_HEADSET:
820         case DEVICE_TYPE_WIRED_HEADSET: {
821             ret = g_adProxy->UpdateActiveDeviceRoute(deviceType, DeviceFlag::ALL_DEVICES_FLAG);
822             CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the route for %{public}d", deviceType);
823             break;
824         }
825         case DEVICE_TYPE_WIRED_HEADPHONES:
826         case DEVICE_TYPE_SPEAKER: {
827             ret = g_adProxy->UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG);
828             CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the route for %{public}d", deviceType);
829             break;
830         }
831         case DEVICE_TYPE_MIC: {
832             ret = g_adProxy->UpdateActiveDeviceRoute(deviceType, DeviceFlag::INPUT_DEVICES_FLAG);
833             CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the route for %{public}d", deviceType);
834             break;
835         }
836         default:
837             break;
838     }
839 }
840 
ConvertToHDIAudioFormat(AudioSampleFormat sampleFormat)841 static string ConvertToHDIAudioFormat(AudioSampleFormat sampleFormat)
842 {
843     switch (sampleFormat) {
844         case SAMPLE_U8:
845             return "u8";
846         case SAMPLE_S16LE:
847             return "s16le";
848         case SAMPLE_S24LE:
849             return "s24le";
850         case SAMPLE_S32LE:
851             return "s32le";
852         default:
853             return "";
854     }
855 }
856 
GetSampleFormatValue(AudioSampleFormat sampleFormat)857 static uint32_t GetSampleFormatValue(AudioSampleFormat sampleFormat)
858 {
859     switch (sampleFormat) {
860         case SAMPLE_U8:
861             return PCM_8_BIT;
862         case SAMPLE_S16LE:
863             return PCM_16_BIT;
864         case SAMPLE_S24LE:
865             return PCM_24_BIT;
866         case SAMPLE_S32LE:
867             return PCM_32_BIT;
868         default:
869             return PCM_16_BIT;
870     }
871 }
872 
SelectNewDevice(DeviceRole deviceRole,DeviceType deviceType)873 int32_t AudioPolicyService::SelectNewDevice(DeviceRole deviceRole, DeviceType deviceType)
874 {
875     int32_t result = SUCCESS;
876 
877     if (deviceRole == DeviceRole::OUTPUT_DEVICE) {
878         std::string activePort = GetPortName(currentActiveDevice_);
879         AUDIO_INFO_LOG("port %{public}s, active device %{public}d", activePort.c_str(), currentActiveDevice_);
880         audioPolicyManager_.SuspendAudioDevice(activePort, true);
881     }
882 
883     std::string portName = GetPortName(deviceType);
884     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, result, "Invalid port name %{public}s", portName.c_str());
885 
886     result = audioPolicyManager_.SelectDevice(deviceRole, deviceType, portName);
887     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, result, "SetDeviceActive failed %{public}d", result);
888     audioPolicyManager_.SuspendAudioDevice(portName, false);
889 
890     if (isUpdateRouteSupported_) {
891         DeviceFlag deviceFlag = deviceRole == DeviceRole::OUTPUT_DEVICE ? OUTPUT_DEVICES_FLAG : INPUT_DEVICES_FLAG;
892         const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
893         CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
894         gsp->UpdateActiveDeviceRoute(deviceType, deviceFlag);
895     }
896 
897     if (deviceRole == DeviceRole::OUTPUT_DEVICE) {
898         currentActiveDevice_ = deviceType;
899     } else {
900         activeInputDevice_ = deviceType;
901     }
902     return SUCCESS;
903 }
904 
ActivateNewDevice(DeviceType deviceType,bool isSceneActivation=false)905 int32_t AudioPolicyService::ActivateNewDevice(DeviceType deviceType, bool isSceneActivation = false)
906 {
907     int32_t result = SUCCESS;
908 
909     if (currentActiveDevice_ == deviceType) {
910         return result;
911     }
912 
913     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
914         auto primaryModulesPos = deviceClassInfo_.find(ClassType::TYPE_A2DP);
915         if (primaryModulesPos != deviceClassInfo_.end()) {
916             auto moduleInfoList = primaryModulesPos->second;
917             for (auto &moduleInfo : moduleInfoList) {
918                 if (IOHandles_.find(moduleInfo.name) == IOHandles_.end()) {
919                     AUDIO_INFO_LOG("Load a2dp module [%{public}s]", moduleInfo.name.c_str());
920                     AudioStreamInfo audioStreamInfo = {};
921                     GetActiveDeviceStreamInfo(deviceType, audioStreamInfo);
922                     uint32_t bufferSize
923                         = (audioStreamInfo.samplingRate * GetSampleFormatValue(audioStreamInfo.format)
924                             * audioStreamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR);
925                     AUDIO_INFO_LOG("a2dp rate: %{public}d, format: %{public}d, channel: %{public}d",
926                         audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
927                     moduleInfo.channels = to_string(audioStreamInfo.channels);
928                     moduleInfo.rate = to_string(audioStreamInfo.samplingRate);
929                     moduleInfo.format = ConvertToHDIAudioFormat(audioStreamInfo.format);
930                     moduleInfo.bufferSize = to_string(bufferSize);
931 
932                     AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
933                     CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
934                         "OpenAudioPort failed %{public}d", ioHandle);
935                     IOHandles_[moduleInfo.name] = ioHandle;
936                 }
937 
938                 std::string activePort = GetPortName(currentActiveDevice_);
939                 AUDIO_INFO_LOG("port %{public}s, active device %{public}d", activePort.c_str(), currentActiveDevice_);
940                 audioPolicyManager_.SuspendAudioDevice(activePort, true);
941             }
942         }
943     } else if (currentActiveDevice_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
944         std::string activePort = GetPortName(currentActiveDevice_);
945         audioPolicyManager_.SuspendAudioDevice(activePort, true);
946     }
947 
948     AudioIOHandle ioHandle = GetAudioIOHandle(deviceType);
949     std::string portName = GetPortName(deviceType);
950     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, result, "Invalid port name %{public}s", portName.c_str());
951 
952     result = audioPolicyManager_.SetDeviceActive(ioHandle, deviceType, portName, true);
953     CHECK_AND_RETURN_RET_LOG(portName != PORT_NONE, result, "SetDeviceActive failed %{public}d", result);
954     audioPolicyManager_.SuspendAudioDevice(portName, false);
955 
956     if (isUpdateRouteSupported_ && !isSceneActivation) {
957         if (deviceType == DEVICE_TYPE_SPEAKER && currentActiveDevice_ != DEVICE_TYPE_SPEAKER) {
958             AUDIO_INFO_LOG("Delay for device: [%{public}d]-->[%{public}d]", currentActiveDevice_, deviceType);
959             usleep(switchVolumeDelay_);
960         }
961         UpdateActiveDeviceRoute(deviceType);
962     }
963 
964     UpdateInputDeviceInfo(deviceType);
965 
966     return SUCCESS;
967 }
968 
ActivateNewDevice(std::string networkId,DeviceType deviceType,bool isRemote)969 int32_t AudioPolicyService::ActivateNewDevice(std::string networkId, DeviceType deviceType, bool isRemote)
970 {
971     if (isRemote) {
972         AudioModuleInfo moduleInfo = ConstructRemoteAudioModuleInfo(networkId, GetDeviceRole(deviceType), deviceType);
973         AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
974         CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
975             "OpenAudioPort failed %{public}d", ioHandle);
976         std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(deviceType));
977         IOHandles_[moduleName] = ioHandle;
978     }
979     return SUCCESS;
980 }
981 
SetDeviceActive(InternalDeviceType deviceType,bool active)982 int32_t AudioPolicyService::SetDeviceActive(InternalDeviceType deviceType, bool active)
983 {
984     AUDIO_DEBUG_LOG("[Policy Service] Device type[%{public}d] flag[%{public}d]", deviceType, active);
985     CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
986 
987     int32_t result = SUCCESS;
988 
989     if (!active) {
990         CHECK_AND_RETURN_RET_LOG(deviceType == currentActiveDevice_, SUCCESS, "This device is not active");
991         deviceType = FetchHighPriorityDevice();
992     }
993 
994     if (deviceType == currentActiveDevice_) {
995         AUDIO_INFO_LOG("Device already activated %{public}d. No need to activate again", currentActiveDevice_);
996         return SUCCESS;
997     }
998 
999     // Activate new device if its already connected
1000     auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &desc) {
1001         CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "SetDeviceActive::Invalid device descriptor");
1002         return ((deviceType == desc->deviceType_) || (deviceType == DEVICE_TYPE_FILE_SINK));
1003     };
1004 
1005     auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
1006     if (itr == connectedDevices_.end()) {
1007         AUDIO_ERR_LOG("Requested device not available %{public}d ", deviceType);
1008         return ERR_OPERATION_FAILED;
1009     }
1010 
1011     switch (deviceType) {
1012         case DEVICE_TYPE_SPEAKER:
1013             result = ActivateNewDevice(DEVICE_TYPE_SPEAKER);
1014             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Speaker activation err %{public}d", result);
1015             result = ActivateNewDevice(DEVICE_TYPE_MIC);
1016             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Microphone activation err %{public}d", result);
1017             break;
1018         case DEVICE_TYPE_FILE_SINK:
1019             result = ActivateNewDevice(DEVICE_TYPE_FILE_SINK);
1020             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "FILE_SINK activation err %{public}d", result);
1021             result = ActivateNewDevice(DEVICE_TYPE_FILE_SOURCE);
1022             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "FILE_SOURCE activation err %{public}d", result);
1023             break;
1024         default:
1025             result = ActivateNewDevice(deviceType);
1026             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Activation failed for %{public}d", deviceType);
1027             break;
1028     }
1029 
1030     currentActiveDevice_ = deviceType;
1031     return result;
1032 }
1033 
IsDeviceActive(InternalDeviceType deviceType) const1034 bool AudioPolicyService::IsDeviceActive(InternalDeviceType deviceType) const
1035 {
1036     AUDIO_INFO_LOG("Entered AudioPolicyService::%{public}s", __func__);
1037     return currentActiveDevice_ == deviceType;
1038 }
1039 
GetActiveOutputDevice() const1040 DeviceType AudioPolicyService::GetActiveOutputDevice() const
1041 {
1042     return currentActiveDevice_;
1043 }
1044 
GetActiveInputDevice() const1045 DeviceType AudioPolicyService::GetActiveInputDevice() const
1046 {
1047     return activeInputDevice_;
1048 }
1049 
SetRingerMode(AudioRingerMode ringMode)1050 int32_t AudioPolicyService::SetRingerMode(AudioRingerMode ringMode)
1051 {
1052     return audioPolicyManager_.SetRingerMode(ringMode);
1053 }
1054 
GetRingerMode() const1055 AudioRingerMode AudioPolicyService::GetRingerMode() const
1056 {
1057     return audioPolicyManager_.GetRingerMode();
1058 }
1059 
SetAudioScene(AudioScene audioScene)1060 int32_t AudioPolicyService::SetAudioScene(AudioScene audioScene)
1061 {
1062     const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
1063     CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable");
1064     audioScene_ = audioScene;
1065 
1066     auto priorityDev = FetchHighPriorityDevice();
1067     AUDIO_INFO_LOG("Priority device for setAudioScene: %{public}d", priorityDev);
1068 
1069     int32_t result = ActivateNewDevice(priorityDev, true);
1070     CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "Device activation failed [%{public}d]", result);
1071 
1072     currentActiveDevice_ = priorityDev;
1073 
1074     result = gsp->SetAudioScene(audioScene, priorityDev);
1075     CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "SetAudioScene failed [%{public}d]", result);
1076 
1077     return SUCCESS;
1078 }
1079 
GetAudioScene() const1080 AudioScene AudioPolicyService::GetAudioScene() const
1081 {
1082     AUDIO_INFO_LOG("GetAudioScene return value: %{public}d", audioScene_);
1083     return audioScene_;
1084 }
1085 
IsAudioInterruptEnabled() const1086 bool AudioPolicyService::IsAudioInterruptEnabled() const
1087 {
1088     return interruptEnabled_;
1089 }
1090 
OnAudioInterruptEnable(bool enable)1091 void AudioPolicyService::OnAudioInterruptEnable(bool enable)
1092 {
1093     interruptEnabled_ = enable;
1094 }
1095 
OnUpdateRouteSupport(bool isSupported)1096 void AudioPolicyService::OnUpdateRouteSupport(bool isSupported)
1097 {
1098     isUpdateRouteSupported_ = isSupported;
1099 }
1100 
GetActiveDeviceStreamInfo(DeviceType deviceType,AudioStreamInfo & streamInfo)1101 bool AudioPolicyService::GetActiveDeviceStreamInfo(DeviceType deviceType, AudioStreamInfo &streamInfo)
1102 {
1103     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1104         auto streamInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_);
1105         if (streamInfoPos != connectedA2dpDeviceMap_.end()) {
1106             streamInfo.samplingRate = streamInfoPos->second.samplingRate;
1107             streamInfo.format = streamInfoPos->second.format;
1108             streamInfo.channels = streamInfoPos->second.channels;
1109             return true;
1110         }
1111     }
1112 
1113     return false;
1114 }
1115 
IsConfigurationUpdated(DeviceType deviceType,const AudioStreamInfo & streamInfo)1116 bool AudioPolicyService::IsConfigurationUpdated(DeviceType deviceType, const AudioStreamInfo &streamInfo)
1117 {
1118     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1119         AudioStreamInfo audioStreamInfo = {};
1120         if (GetActiveDeviceStreamInfo(deviceType, audioStreamInfo)) {
1121             AUDIO_DEBUG_LOG("Device configurations current rate: %{public}d, format: %{public}d, channel: %{public}d",
1122                 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
1123             AUDIO_DEBUG_LOG("Device configurations updated rate: %{public}d, format: %{public}d, channel: %{public}d",
1124                 streamInfo.samplingRate, streamInfo.format, streamInfo.channels);
1125             if ((audioStreamInfo.samplingRate != streamInfo.samplingRate)
1126                 || (audioStreamInfo.channels != streamInfo.channels)
1127                 || (audioStreamInfo.format != streamInfo.format)) {
1128                 return true;
1129             }
1130         }
1131     }
1132 
1133     return false;
1134 }
1135 
UpdateConnectedDevices(const AudioDeviceDescriptor & deviceDescriptor,std::vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)1136 void AudioPolicyService::UpdateConnectedDevices(const AudioDeviceDescriptor &deviceDescriptor,
1137     std::vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected)
1138 {
1139     sptr<AudioDeviceDescriptor> audioDescriptor = nullptr;
1140 
1141     if (std::find(ioDeviceList.begin(), ioDeviceList.end(), deviceDescriptor.deviceType_) != ioDeviceList.end()) {
1142         AUDIO_INFO_LOG("Filling io device list for %{public}d", deviceDescriptor.deviceType_);
1143         audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(deviceDescriptor);
1144         audioDescriptor->deviceRole_ = INPUT_DEVICE;
1145         if ((deviceDescriptor.deviceType_ == DEVICE_TYPE_WIRED_HEADSET)
1146             || (deviceDescriptor.deviceType_ == DEVICE_TYPE_USB_HEADSET)) {
1147             auto isBuiltInMicPresent = [](const sptr<AudioDeviceDescriptor> &devDesc) {
1148                 CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor");
1149                 return (DEVICE_TYPE_MIC == devDesc->deviceType_);
1150             };
1151 
1152             auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isBuiltInMicPresent);
1153             if (itr != connectedDevices_.end()) {
1154                 audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0);
1155             }
1156         }
1157 
1158         desc.push_back(audioDescriptor);
1159         if (isConnected) {
1160             audioDescriptor->deviceId_ = startDeviceId++;
1161             connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
1162         }
1163 
1164         audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(deviceDescriptor);
1165         audioDescriptor->deviceRole_ = OUTPUT_DEVICE;
1166         if ((deviceDescriptor.deviceType_ == DEVICE_TYPE_WIRED_HEADSET)
1167             || (deviceDescriptor.deviceType_ == DEVICE_TYPE_USB_HEADSET)
1168             || (deviceDescriptor.deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES)) {
1169             auto isSpeakerPresent = [](const sptr<AudioDeviceDescriptor> &devDesc) {
1170                 CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor");
1171                 return (DEVICE_TYPE_SPEAKER == devDesc->deviceType_);
1172             };
1173 
1174             auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isSpeakerPresent);
1175             if (itr != connectedDevices_.end()) {
1176                 audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0);
1177             }
1178         }
1179         desc.push_back(audioDescriptor);
1180         if (isConnected) {
1181             audioDescriptor->deviceId_ = startDeviceId++;
1182             connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
1183         }
1184     } else {
1185         AUDIO_INFO_LOG("Filling non-io device list for %{public}d", deviceDescriptor.deviceType_);
1186         audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(deviceDescriptor);
1187         audioDescriptor->deviceRole_ = GetDeviceRole(deviceDescriptor.deviceType_);
1188         desc.push_back(audioDescriptor);
1189         if (isConnected) {
1190             audioDescriptor->deviceId_ = startDeviceId++;
1191             connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
1192         }
1193     }
1194 }
1195 
OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)1196 void AudioPolicyService::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress,
1197     const std::string& deviceName, const AudioStreamInfo& streamInfo)
1198 {
1199     AUDIO_INFO_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d]", devType, isConnected);
1200     int32_t result = ERROR;
1201     AudioDeviceDescriptor deviceDesc(devType, GetDeviceRole(devType));
1202     deviceDesc.SetDeviceInfo(deviceName, macAddress);
1203     deviceDesc.SetDeviceCapability(streamInfo, 0);
1204 
1205     UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, LOCAL_NETWORK_ID, isConnected,
1206         NO_REMOTE_ID);
1207     UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, LOCAL_NETWORK_ID, isConnected,
1208         NO_REMOTE_ID);
1209     deviceDesc.networkId_ = LOCAL_NETWORK_ID;
1210 
1211     // fill device change action for callback
1212     std::vector<sptr<AudioDeviceDescriptor>> deviceChangeDescriptor = {};
1213     auto isPresent = [&devType] (const sptr<AudioDeviceDescriptor> &descriptor) {
1214         return descriptor->deviceType_ == devType;
1215     };
1216 
1217     // If device already in list, remove it else do not modify the list
1218     connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent),
1219                             connectedDevices_.end());
1220 
1221     if (devType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1222         if (isConnected) {
1223             connectedA2dpDeviceMap_.insert(make_pair(macAddress, streamInfo));
1224             activeBTDevice_ = macAddress;
1225         } else {
1226             connectedA2dpDeviceMap_.erase(macAddress);
1227             activeBTDevice_ = "";
1228         }
1229     } else if ((devType == DEVICE_TYPE_BLUETOOTH_SCO) && isConnected && (GetAudioScene() == AUDIO_SCENE_DEFAULT)) {
1230         // For SCO device, add to connected device and donot activate now
1231         AUDIO_INFO_LOG("BT SCO device detected in non-call mode [%{public}d]", GetAudioScene());
1232         UpdateConnectedDevices(deviceDesc, deviceChangeDescriptor, isConnected);
1233         TriggerDeviceChangedCallback(deviceChangeDescriptor, isConnected);
1234         UpdateTrackerDeviceChange(deviceChangeDescriptor);
1235         return;
1236     }
1237 
1238     // new device found. If connected, add into active device list
1239     if (isConnected) {
1240         result = ActivateNewDevice(devType);
1241         CHECK_AND_RETURN_LOG(result == SUCCESS, "Failed to activate new device %{public}d", devType);
1242         currentActiveDevice_ = devType;
1243         UpdateConnectedDevices(deviceDesc, deviceChangeDescriptor, isConnected);
1244     } else {
1245         UpdateConnectedDevices(deviceDesc, deviceChangeDescriptor, isConnected);
1246 
1247         auto priorityDev = FetchHighPriorityDevice();
1248         AUDIO_INFO_LOG("Priority device is [%{public}d]", priorityDev);
1249 
1250         if (priorityDev == DEVICE_TYPE_SPEAKER) {
1251             result = ActivateNewDevice(DEVICE_TYPE_SPEAKER);
1252             CHECK_AND_RETURN_LOG(result == SUCCESS, "Failed to activate new device [%{public}d]", result);
1253 
1254             result = ActivateNewDevice(DEVICE_TYPE_MIC);
1255             CHECK_AND_RETURN_LOG(result == SUCCESS, "Failed to activate new device [%{public}d]", result);
1256         } else {
1257             result = ActivateNewDevice(priorityDev);
1258             CHECK_AND_RETURN_LOG(result == SUCCESS, "Failed to activate new device [%{public}d]", result);
1259         }
1260 
1261         if (devType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1262             if (IOHandles_.find(BLUETOOTH_SPEAKER) != IOHandles_.end()) {
1263                 audioPolicyManager_.CloseAudioPort(IOHandles_[BLUETOOTH_SPEAKER]);
1264                 IOHandles_.erase(BLUETOOTH_SPEAKER);
1265             }
1266         }
1267 
1268         currentActiveDevice_ = priorityDev;
1269     }
1270 
1271     TriggerDeviceChangedCallback(deviceChangeDescriptor, isConnected);
1272     UpdateTrackerDeviceChange(deviceChangeDescriptor);
1273 }
1274 
GetSupportedTones()1275 std::vector<int32_t> AudioPolicyService::GetSupportedTones()
1276 {
1277     std::vector<int> supportedToneList = {};
1278     for (auto i = toneDescriptorMap.begin(); i != toneDescriptorMap.end(); i++) {
1279         supportedToneList.push_back(i->first);
1280     }
1281     return supportedToneList;
1282 }
1283 
GetToneConfig(int32_t ltonetype)1284 std::shared_ptr<ToneInfo> AudioPolicyService::GetToneConfig(int32_t ltonetype)
1285 {
1286     if (toneDescriptorMap.find(ltonetype) == toneDescriptorMap.end()) {
1287         return nullptr;
1288     }
1289     AUDIO_DEBUG_LOG("AudioPolicyService GetToneConfig %{public}d", ltonetype);
1290     return toneDescriptorMap[ltonetype];
1291 }
1292 
OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)1293 void AudioPolicyService::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress,
1294     const std::string &deviceName, const AudioStreamInfo &streamInfo)
1295 {
1296     AUDIO_DEBUG_LOG("OnDeviceConfigurationChanged in");
1297     if ((deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) && !macAddress.compare(activeBTDevice_)
1298         && IsDeviceActive(deviceType)) {
1299         if (!IsConfigurationUpdated(deviceType, streamInfo)) {
1300             AUDIO_DEBUG_LOG("Audio configuration same");
1301             return;
1302         }
1303 
1304         uint32_t bufferSize
1305             = (streamInfo.samplingRate * GetSampleFormatValue(streamInfo.format)
1306                 * streamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR);
1307         AUDIO_DEBUG_LOG("Updated buffer size: %{public}d", bufferSize);
1308         connectedA2dpDeviceMap_[macAddress] = streamInfo;
1309 
1310         auto a2dpModulesPos = deviceClassInfo_.find(ClassType::TYPE_A2DP);
1311         if (a2dpModulesPos != deviceClassInfo_.end()) {
1312             auto moduleInfoList = a2dpModulesPos->second;
1313             for (auto &moduleInfo : moduleInfoList) {
1314                 if (IOHandles_.find(moduleInfo.name) != IOHandles_.end()) {
1315                     moduleInfo.channels = to_string(streamInfo.channels);
1316                     moduleInfo.rate = to_string(streamInfo.samplingRate);
1317                     moduleInfo.format = ConvertToHDIAudioFormat(streamInfo.format);
1318                     moduleInfo.bufferSize = to_string(bufferSize);
1319 
1320                     // First unload the existing bt sink
1321                     AUDIO_DEBUG_LOG("UnLoad existing a2dp module");
1322                     std::string currentActivePort = GetPortName(currentActiveDevice_);
1323                     AudioIOHandle activateDeviceIOHandle = IOHandles_[BLUETOOTH_SPEAKER];
1324                     audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
1325                     audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle);
1326 
1327                     // Load bt sink module again with new configuration
1328                     AUDIO_DEBUG_LOG("Reload a2dp module [%{public}s]", moduleInfo.name.c_str());
1329                     AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
1330                     CHECK_AND_RETURN_LOG(ioHandle != OPEN_PORT_FAILURE, "OpenAudioPort failed %{public}d", ioHandle);
1331                     IOHandles_[moduleInfo.name] = ioHandle;
1332                     std::string portName = GetPortName(deviceType);
1333                     audioPolicyManager_.SetDeviceActive(ioHandle, deviceType, portName, true);
1334                     audioPolicyManager_.SuspendAudioDevice(portName, false);
1335 
1336                     auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &descriptor) {
1337                         return descriptor->deviceType_ == deviceType;
1338                     };
1339 
1340                     sptr<AudioDeviceDescriptor> audioDescriptor
1341                         = new(std::nothrow) AudioDeviceDescriptor(deviceType, OUTPUT_DEVICE);
1342                     audioDescriptor->SetDeviceInfo(deviceName, macAddress);
1343                     audioDescriptor->SetDeviceCapability(streamInfo, 0);
1344                     std::replace_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent, audioDescriptor);
1345                     break;
1346                 }
1347             }
1348         }
1349     }
1350 }
1351 
RemoveDeviceInRouterMap(std::string networkId,std::unordered_map<int32_t,std::pair<std::string,int32_t>> & routerMap_)1352 inline void RemoveDeviceInRouterMap(std::string networkId,
1353     std::unordered_map<int32_t, std::pair<std::string, int32_t>> &routerMap_)
1354 {
1355     std::unordered_map<int32_t, std::pair<std::string, int32_t>>::iterator it;
1356     for (it = routerMap_.begin();it != routerMap_.end();) {
1357         if (it->second.first == networkId) {
1358             routerMap_.erase(it++);
1359         } else {
1360             it++;
1361         }
1362     }
1363 }
1364 
OnDeviceStatusUpdated(DStatusInfo statusInfo)1365 void AudioPolicyService::OnDeviceStatusUpdated(DStatusInfo statusInfo)
1366 {
1367     AUDIO_INFO_LOG("Device connection updated | HDI_PIN[%{public}d] CONNECT_STATUS[%{public}d] NETWORKID[%{public}s]",
1368         statusInfo.hdiPin, statusInfo.isConnected, statusInfo.networkId);
1369     DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin);
1370     const std::string networkId = statusInfo.networkId;
1371     if (GetDeviceRole(devType) == DeviceRole::INPUT_DEVICE) {
1372         return; // not support input device.
1373     }
1374     AudioDeviceDescriptor deviceDesc(devType, GetDeviceRole(devType));
1375     deviceDesc.SetDeviceInfo(statusInfo.deviceName, statusInfo.macAddress);
1376     deviceDesc.SetDeviceCapability(statusInfo.streamInfo, 0);
1377     deviceDesc.networkId_ = networkId;
1378 
1379     std::vector<sptr<AudioDeviceDescriptor>> deviceChangeDescriptor = {};
1380     for (auto devDes : connectedDevices_) {
1381         if (statusInfo.isConnected && devDes->deviceType_ == devType && devDes->networkId_ == networkId) {
1382             AUDIO_INFO_LOG("Device [%{public}s] Type [%{public}d] has connected already!", networkId.c_str(), devType);
1383             return;
1384         }
1385     }
1386 
1387     auto isPresent = [&devType, &networkId](const sptr<AudioDeviceDescriptor>& descriptor) {
1388         return descriptor->deviceType_ == devType && descriptor->networkId_ == networkId;
1389     };
1390     // If device already in list, remove it else do not modify the list
1391     connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent),
1392                             connectedDevices_.end());
1393     // new device found. If connected, add into active device list
1394     if (statusInfo.isConnected) {
1395         int32_t ret = ActivateNewDevice(statusInfo.networkId, devType,
1396             statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED);
1397         if (ret != SUCCESS) {
1398             AUDIO_ERR_LOG("=== DEVICE online but open audio device failed.");
1399             return;
1400         }
1401         const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
1402         if (gsp != nullptr && statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED) {
1403             gsp->NotifyDeviceInfo(networkId, true);
1404         }
1405     } else {
1406         std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(devType));
1407         if (IOHandles_.find(moduleName) != IOHandles_.end()) {
1408             audioPolicyManager_.CloseAudioPort(IOHandles_[moduleName]);
1409             IOHandles_.erase(moduleName);
1410         }
1411         RemoveDeviceInRouterMap(networkId, routerMap_);
1412     }
1413 
1414     UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, networkId, statusInfo.isConnected,
1415         statusInfo.mappingVolumeId);
1416     UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, networkId,
1417         statusInfo.isConnected, statusInfo.mappingInterruptId);
1418     UpdateConnectedDevices(deviceDesc, deviceChangeDescriptor, statusInfo.isConnected);
1419     TriggerDeviceChangedCallback(deviceChangeDescriptor, statusInfo.isConnected);
1420 }
1421 
OnServiceConnected(AudioServiceIndex serviceIndex)1422 void AudioPolicyService::OnServiceConnected(AudioServiceIndex serviceIndex)
1423 {
1424     AUDIO_INFO_LOG("[module_load]::OnServiceConnected for [%{public}d]", serviceIndex);
1425     CHECK_AND_RETURN_LOG(serviceIndex >= HDI_SERVICE_INDEX && serviceIndex <= AUDIO_SERVICE_INDEX, "invalid index");
1426 
1427     // If audio service or hdi service is not ready, donot load default modules
1428     lock_guard<mutex> lock(serviceFlagMutex_);
1429     serviceFlag_.set(serviceIndex, true);
1430     if (serviceFlag_.count() != MIN_SERVICE_COUNT) {
1431         AUDIO_INFO_LOG("[module_load]::hdi service or audio service not up. Cannot load default module now");
1432         return;
1433     }
1434 
1435     int32_t result = ERROR;
1436     AUDIO_INFO_LOG("[module_load]::HDI and AUDIO SERVICE is READY. Loading default modules");
1437     for (const auto &device : deviceClassInfo_) {
1438         if (device.first == ClassType::TYPE_PRIMARY || device.first == ClassType::TYPE_FILE_IO) {
1439             auto moduleInfoList = device.second;
1440             for (auto &moduleInfo : moduleInfoList) {
1441                 AUDIO_INFO_LOG("[module_load]::Load module[%{public}s]", moduleInfo.name.c_str());
1442                 moduleInfo.sinkLatency = sinkLatencyInMsec_ != 0 ? to_string(sinkLatencyInMsec_) : "";
1443                 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
1444                 if (ioHandle == OPEN_PORT_FAILURE) {
1445                     AUDIO_INFO_LOG("[module_load]::Open port failed");
1446                     continue;
1447                 }
1448                 IOHandles_[moduleInfo.name] = ioHandle;
1449                 auto devType = GetDeviceType(moduleInfo.name);
1450                 if (devType == DEVICE_TYPE_SPEAKER || devType == DEVICE_TYPE_MIC) {
1451                     result = audioPolicyManager_.SetDeviceActive(ioHandle, devType, moduleInfo.name, true);
1452                     if (result != SUCCESS) {
1453                         AUDIO_ERR_LOG("[module_load]::Device failed %{public}d", devType);
1454                         continue;
1455                     }
1456                     AddAudioDevice(moduleInfo, devType);
1457                 }
1458             }
1459         }
1460     }
1461 
1462     if (result == SUCCESS) {
1463         AUDIO_INFO_LOG("[module_load]::Setting speaker as active device on bootup");
1464         currentActiveDevice_ = DEVICE_TYPE_SPEAKER;
1465         activeInputDevice_ = DEVICE_TYPE_MIC;
1466     }
1467 }
1468 
OnServiceDisconnected(AudioServiceIndex serviceIndex)1469 void AudioPolicyService::OnServiceDisconnected(AudioServiceIndex serviceIndex)
1470 {
1471     AUDIO_ERR_LOG("OnServiceDisconnected for [%{public}d]", serviceIndex);
1472     CHECK_AND_RETURN_LOG(serviceIndex >= HDI_SERVICE_INDEX && serviceIndex <= AUDIO_SERVICE_INDEX, "invalid index");
1473     if (serviceIndex == HDI_SERVICE_INDEX) {
1474         AUDIO_ERR_LOG("Auto exit audio policy service for hdi service stopped!");
1475         _Exit(0);
1476     }
1477 }
1478 
OnMonoAudioConfigChanged(bool audioMono)1479 void AudioPolicyService::OnMonoAudioConfigChanged(bool audioMono)
1480 {
1481     AUDIO_INFO_LOG("AudioPolicyService::OnMonoAudioConfigChanged: audioMono = %{public}s", audioMono? "true": "false");
1482     const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
1483     if (gsp == nullptr) {
1484         AUDIO_ERR_LOG("Service proxy unavailable: g_adProxy null");
1485         return;
1486     }
1487     gsp->SetAudioMonoState(audioMono);
1488 }
1489 
OnAudioBalanceChanged(float audioBalance)1490 void AudioPolicyService::OnAudioBalanceChanged(float audioBalance)
1491 {
1492     AUDIO_INFO_LOG("AudioPolicyService::OnAudioBalanceChanged: audioBalance = %{public}f", audioBalance);
1493     const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
1494     if (gsp == nullptr) {
1495         AUDIO_ERR_LOG("Service proxy unavailable: g_adProxy null");
1496         return;
1497     }
1498     gsp->SetAudioBalanceValue(audioBalance);
1499 }
1500 
AddAudioDevice(AudioModuleInfo & moduleInfo,InternalDeviceType devType)1501 void AudioPolicyService::AddAudioDevice(AudioModuleInfo& moduleInfo, InternalDeviceType devType)
1502 {
1503     // add new device into active device list
1504     std::string volumeGroupName = GetGroupName(moduleInfo.name, VOLUME_TYPE);
1505     std::string interruptGroupName = GetGroupName(moduleInfo.name, INTERRUPT_TYPE);
1506     int32_t volumeGroupId = GROUP_ID_NONE;
1507     int32_t interruptGroupId = GROUP_ID_NONE;
1508     UpdateGroupInfo(GroupType::VOLUME_TYPE, volumeGroupName, volumeGroupId, LOCAL_NETWORK_ID, true,
1509         NO_REMOTE_ID);
1510     UpdateGroupInfo(GroupType::INTERRUPT_TYPE, interruptGroupName, interruptGroupId, LOCAL_NETWORK_ID,
1511         true, NO_REMOTE_ID);
1512 
1513     sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(devType,
1514         GetDeviceRole(moduleInfo.role), volumeGroupId, interruptGroupId, LOCAL_NETWORK_ID);
1515     if (!moduleInfo.rate.empty() && !moduleInfo.channels.empty()) {
1516         AudioStreamInfo streamInfo = {};
1517         streamInfo.samplingRate = static_cast<AudioSamplingRate>(stoi(moduleInfo.rate));
1518         streamInfo.channels = static_cast<AudioChannel>(stoi(moduleInfo.channels));
1519         audioDescriptor->SetDeviceCapability(streamInfo, 0);
1520     }
1521 
1522     audioDescriptor->deviceId_ = startDeviceId++;
1523     connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor);
1524 }
1525 
1526 // Parser callbacks
OnXmlParsingCompleted(const std::unordered_map<ClassType,std::list<AudioModuleInfo>> & xmlData)1527 void AudioPolicyService::OnXmlParsingCompleted(const std::unordered_map<ClassType, std::list<AudioModuleInfo>> &xmlData)
1528 {
1529     AUDIO_INFO_LOG("AudioPolicyService::%{public}s, device class num [%{public}zu]", __func__, xmlData.size());
1530     if (xmlData.empty()) {
1531         AUDIO_ERR_LOG("failed to parse xml file. Received data is empty");
1532         return;
1533     }
1534 
1535     deviceClassInfo_ = xmlData;
1536 }
1537 
OnVolumeGroupParsed(std::unordered_map<std::string,std::string> & volumeGroupData)1538 void AudioPolicyService::OnVolumeGroupParsed(std::unordered_map<std::string, std::string>& volumeGroupData)
1539 {
1540     AUDIO_INFO_LOG("AudioPolicyService::%{public}s, group data num [%{public}zu]", __func__, volumeGroupData.size());
1541     if (volumeGroupData.empty()) {
1542         AUDIO_ERR_LOG("failed to parse xml file. Received data is empty");
1543         return;
1544     }
1545 
1546     volumeGroupData_ = volumeGroupData;
1547 }
1548 
OnInterruptGroupParsed(std::unordered_map<std::string,std::string> & interruptGroupData)1549 void AudioPolicyService::OnInterruptGroupParsed(std::unordered_map<std::string, std::string>& interruptGroupData)
1550 {
1551     AUDIO_INFO_LOG("AudioPolicyService::%{public}s, group data num [%{public}zu]", __func__, interruptGroupData.size());
1552     if (interruptGroupData.empty()) {
1553         AUDIO_ERR_LOG("failed to parse xml file. Received data is empty");
1554         return;
1555     }
1556 
1557     interruptGroupData_ = interruptGroupData;
1558 }
1559 
SetDeviceChangeCallback(const int32_t clientId,const DeviceFlag flag,const sptr<IRemoteObject> & object)1560 int32_t AudioPolicyService::SetDeviceChangeCallback(const int32_t clientId, const DeviceFlag flag,
1561     const sptr<IRemoteObject> &object)
1562 {
1563     AUDIO_INFO_LOG("Entered AudioPolicyService::%{public}s", __func__);
1564 
1565     sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object);
1566     if (callback != nullptr) {
1567         deviceChangeCallbackMap_[clientId] = std::make_pair(flag, callback);
1568     }
1569 
1570     return SUCCESS;
1571 }
1572 
UnsetDeviceChangeCallback(const int32_t clientId)1573 int32_t AudioPolicyService::UnsetDeviceChangeCallback(const int32_t clientId)
1574 {
1575     AUDIO_INFO_LOG("Entered AudioPolicyService::%{public}s", __func__);
1576 
1577     if (deviceChangeCallbackMap_.erase(clientId)) {
1578         AUDIO_DEBUG_LOG("AudioPolicyServer:UnsetDeviceChangeCallback for clientID %{public}d done", clientId);
1579     } else {
1580         AUDIO_DEBUG_LOG("AudioPolicyServer:UnsetDeviceChangeCallback clientID %{public}d not present/unset already",
1581                         clientId);
1582     }
1583 
1584     return SUCCESS;
1585 }
1586 
RegisterAudioRendererEventListener(int32_t clientUID,const sptr<IRemoteObject> & object,bool hasBTPermission)1587 int32_t AudioPolicyService::RegisterAudioRendererEventListener(int32_t clientUID, const sptr<IRemoteObject> &object,
1588     bool hasBTPermission)
1589 {
1590     return streamCollector_.RegisterAudioRendererEventListener(clientUID, object, hasBTPermission);
1591 }
1592 
UnregisterAudioRendererEventListener(int32_t clientUID)1593 int32_t AudioPolicyService::UnregisterAudioRendererEventListener(int32_t clientUID)
1594 {
1595     return streamCollector_.UnregisterAudioRendererEventListener(clientUID);
1596 }
1597 
RegisterAudioCapturerEventListener(int32_t clientUID,const sptr<IRemoteObject> & object,bool hasBTPermission)1598 int32_t AudioPolicyService::RegisterAudioCapturerEventListener(int32_t clientUID, const sptr<IRemoteObject> &object,
1599     bool hasBTPermission)
1600 {
1601     return streamCollector_.RegisterAudioCapturerEventListener(clientUID, object, hasBTPermission);
1602 }
1603 
UnregisterAudioCapturerEventListener(int32_t clientUID)1604 int32_t AudioPolicyService::UnregisterAudioCapturerEventListener(int32_t clientUID)
1605 {
1606     return streamCollector_.UnregisterAudioCapturerEventListener(clientUID);
1607 }
1608 
UpdateDeviceInfo(DeviceInfo & deviceInfo,const sptr<AudioDeviceDescriptor> & desc,bool hasBTPermission)1609 static void UpdateDeviceInfo(DeviceInfo &deviceInfo, const sptr<AudioDeviceDescriptor> &desc, bool hasBTPermission)
1610 {
1611     deviceInfo.deviceType = desc->deviceType_;
1612     deviceInfo.deviceRole = desc->deviceRole_;
1613     deviceInfo.deviceId = desc->deviceId_;
1614     deviceInfo.channelMasks = desc->channelMasks_;
1615     deviceInfo.networkId = desc->networkId_;
1616 
1617     if (hasBTPermission) {
1618         deviceInfo.deviceName = desc->deviceName_;
1619         deviceInfo.macAddress = desc->macAddress_;
1620     } else {
1621         deviceInfo.deviceName = "";
1622         deviceInfo.macAddress = "";
1623     }
1624 
1625     deviceInfo.audioStreamInfo.samplingRate = desc->audioStreamInfo_.samplingRate;
1626     deviceInfo.audioStreamInfo.encoding = desc->audioStreamInfo_.encoding;
1627     deviceInfo.audioStreamInfo.format = desc->audioStreamInfo_.format;
1628     deviceInfo.audioStreamInfo.channels = desc->audioStreamInfo_.channels;
1629 }
1630 
UpdateStreamChangeDeviceInfo(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)1631 void AudioPolicyService::UpdateStreamChangeDeviceInfo(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
1632 {
1633     if (mode == AUDIO_MODE_PLAYBACK) {
1634         std::vector<sptr<AudioDeviceDescriptor>> outputDevices = GetDevices(OUTPUT_DEVICES_FLAG);
1635         DeviceType activeDeviceType = currentActiveDevice_;
1636         DeviceRole activeDeviceRole = OUTPUT_DEVICE;
1637         for (sptr<AudioDeviceDescriptor> desc : outputDevices) {
1638             if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
1639                 UpdateDeviceInfo(streamChangeInfo.audioRendererChangeInfo.outputDeviceInfo, desc, true);
1640                 break;
1641             }
1642         }
1643     } else {
1644         std::vector<sptr<AudioDeviceDescriptor>> inputDevices = GetDevices(INPUT_DEVICES_FLAG);
1645         DeviceType activeDeviceType = activeInputDevice_;
1646         DeviceRole activeDeviceRole = INPUT_DEVICE;
1647         for (sptr<AudioDeviceDescriptor> desc : inputDevices) {
1648             if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
1649                 UpdateDeviceInfo(streamChangeInfo.audioCapturerChangeInfo.inputDeviceInfo, desc, true);
1650                 break;
1651             }
1652         }
1653     }
1654 }
1655 
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object)1656 int32_t AudioPolicyService::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
1657     const sptr<IRemoteObject> &object)
1658 {
1659     UpdateStreamChangeDeviceInfo(mode, streamChangeInfo);
1660     return streamCollector_.RegisterTracker(mode, streamChangeInfo, object);
1661 }
1662 
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)1663 int32_t AudioPolicyService::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
1664 {
1665     AUDIO_INFO_LOG("Entered AudioPolicyService::%{public}s", __func__);
1666     UpdateStreamChangeDeviceInfo(mode, streamChangeInfo);
1667     return streamCollector_.UpdateTracker(mode, streamChangeInfo);
1668 }
1669 
GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos,bool hasBTPermission)1670 int32_t AudioPolicyService::GetCurrentRendererChangeInfos(
1671     vector<unique_ptr<AudioRendererChangeInfo>> &audioRendererChangeInfos, bool hasBTPermission)
1672 {
1673     int32_t status = streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
1674     if (status != SUCCESS) {
1675         AUDIO_ERR_LOG("AudioPolicyServer:: Get renderer change info failed");
1676         return status;
1677     }
1678 
1679     std::vector<sptr<AudioDeviceDescriptor>> outputDevices = GetDevices(OUTPUT_DEVICES_FLAG);
1680     DeviceType activeDeviceType = currentActiveDevice_;
1681     DeviceRole activeDeviceRole = OUTPUT_DEVICE;
1682     for (sptr<AudioDeviceDescriptor> desc : outputDevices) {
1683         if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
1684             size_t rendererInfosSize = audioRendererChangeInfos.size();
1685             for (size_t i = 0; i < rendererInfosSize; i++) {
1686                 UpdateDeviceInfo(audioRendererChangeInfos[i]->outputDeviceInfo, desc, hasBTPermission);
1687             }
1688         }
1689 
1690         return status;
1691     }
1692 
1693     return status;
1694 }
1695 
GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos,bool hasBTPermission)1696 int32_t AudioPolicyService::GetCurrentCapturerChangeInfos(
1697     vector<unique_ptr<AudioCapturerChangeInfo>> &audioCapturerChangeInfos, bool hasBTPermission)
1698 {
1699     int status = streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos);
1700     if (status != SUCCESS) {
1701         AUDIO_ERR_LOG("AudioPolicyServer:: Get capturer change info failed");
1702         return status;
1703     }
1704 
1705     std::vector<sptr<AudioDeviceDescriptor>> inputDevices = GetDevices(INPUT_DEVICES_FLAG);
1706     DeviceType activeDeviceType = activeInputDevice_;
1707     DeviceRole activeDeviceRole = INPUT_DEVICE;
1708     for (sptr<AudioDeviceDescriptor> desc : inputDevices) {
1709         if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
1710             size_t capturerInfosSize = audioCapturerChangeInfos.size();
1711             for (size_t i = 0; i < capturerInfosSize; i++) {
1712                 UpdateDeviceInfo(audioCapturerChangeInfos[i]->inputDeviceInfo, desc, hasBTPermission);
1713             }
1714         }
1715 
1716         return status;
1717     }
1718 
1719     return status;
1720 }
1721 
RegisteredTrackerClientDied(pid_t pid)1722 void AudioPolicyService::RegisteredTrackerClientDied(pid_t pid)
1723 {
1724     streamCollector_.RegisteredTrackerClientDied(static_cast<int32_t>(pid));
1725 }
1726 
RegisteredStreamListenerClientDied(pid_t pid)1727 void AudioPolicyService::RegisteredStreamListenerClientDied(pid_t pid)
1728 {
1729     streamCollector_.RegisteredStreamListenerClientDied(static_cast<int32_t>(pid));
1730 }
1731 
ReconfigureAudioChannel(const uint32_t & channelCount,DeviceType deviceType)1732 int32_t AudioPolicyService::ReconfigureAudioChannel(const uint32_t &channelCount, DeviceType deviceType)
1733 {
1734     if (currentActiveDevice_ != DEVICE_TYPE_FILE_SINK) {
1735         AUDIO_INFO_LOG("FILE_SINK_DEVICE is not active. Cannot reconfigure now");
1736         return ERROR;
1737     }
1738 
1739     std::string module = FILE_SINK;
1740 
1741     if (deviceType == DeviceType::DEVICE_TYPE_FILE_SINK) {
1742         CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_8 && channelCount >= MONO, ERROR, "Invalid sink channel");
1743         module = FILE_SINK;
1744     } else if (deviceType == DeviceType::DEVICE_TYPE_FILE_SOURCE) {
1745         CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_6 && channelCount >= MONO, ERROR, "Invalid src channel");
1746         module = FILE_SOURCE;
1747     } else {
1748         AUDIO_ERR_LOG("Invalid DeviceType");
1749         return ERROR;
1750     }
1751 
1752     if (IOHandles_.find(module) != IOHandles_.end()) {
1753         audioPolicyManager_.CloseAudioPort(IOHandles_[module]);
1754         IOHandles_.erase(module);
1755     }
1756 
1757     auto fileClass = deviceClassInfo_.find(ClassType::TYPE_FILE_IO);
1758     if (fileClass != deviceClassInfo_.end()) {
1759         auto moduleInfoList = fileClass->second;
1760         for (auto &moduleInfo : moduleInfoList) {
1761             if (module == moduleInfo.name) {
1762                 moduleInfo.channels = to_string(channelCount);
1763                 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
1764                 IOHandles_[moduleInfo.name] = ioHandle;
1765                 audioPolicyManager_.SetDeviceActive(ioHandle, deviceType, module, true);
1766             }
1767         }
1768     }
1769 
1770     return SUCCESS;
1771 }
1772 
1773 // private methods
GetAudioIOHandle(InternalDeviceType deviceType)1774 AudioIOHandle AudioPolicyService::GetAudioIOHandle(InternalDeviceType deviceType)
1775 {
1776     AudioIOHandle ioHandle;
1777     switch (deviceType) {
1778         case InternalDeviceType::DEVICE_TYPE_WIRED_HEADSET:
1779         case InternalDeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
1780         case InternalDeviceType::DEVICE_TYPE_USB_HEADSET:
1781         case InternalDeviceType::DEVICE_TYPE_SPEAKER:
1782         case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
1783             ioHandle = IOHandles_[PRIMARY_SPEAKER];
1784             break;
1785         case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
1786             ioHandle = IOHandles_[BLUETOOTH_SPEAKER];
1787             break;
1788         case InternalDeviceType::DEVICE_TYPE_MIC:
1789             ioHandle = IOHandles_[PRIMARY_MIC];
1790             break;
1791         case InternalDeviceType::DEVICE_TYPE_FILE_SINK:
1792             ioHandle = IOHandles_[FILE_SINK];
1793             break;
1794         case InternalDeviceType::DEVICE_TYPE_FILE_SOURCE:
1795             ioHandle = IOHandles_[FILE_SOURCE];
1796             break;
1797         default:
1798             ioHandle = IOHandles_[PRIMARY_MIC];
1799             break;
1800     }
1801     return ioHandle;
1802 }
1803 
GetDeviceType(const std::string & deviceName)1804 InternalDeviceType AudioPolicyService::GetDeviceType(const std::string &deviceName)
1805 {
1806     InternalDeviceType devType = InternalDeviceType::DEVICE_TYPE_NONE;
1807     if (deviceName == "Speaker") {
1808         devType = InternalDeviceType::DEVICE_TYPE_SPEAKER;
1809     } else if (deviceName == "Built_in_mic") {
1810         devType = InternalDeviceType::DEVICE_TYPE_MIC;
1811     } else if (deviceName == "fifo_output" || deviceName == "fifo_input") {
1812         devType = DEVICE_TYPE_BLUETOOTH_SCO;
1813     } else if (deviceName == "file_sink") {
1814         devType = DEVICE_TYPE_FILE_SINK;
1815     } else if (deviceName == "file_source") {
1816         devType = DEVICE_TYPE_FILE_SOURCE;
1817     }
1818 
1819     return devType;
1820 }
1821 
GetGroupName(const std::string & deviceName,const GroupType type)1822 std::string AudioPolicyService::GetGroupName(const std::string& deviceName, const GroupType type)
1823 {
1824     std::string groupName = GROUP_NAME_NONE;
1825     if (type == VOLUME_TYPE) {
1826         auto iter = volumeGroupData_.find(deviceName);
1827         if (iter != volumeGroupData_.end()) {
1828             groupName = iter->second;
1829         }
1830     } else {
1831         auto iter = interruptGroupData_.find(deviceName);
1832         if (iter != interruptGroupData_.end()) {
1833             groupName = iter->second;
1834         }
1835     }
1836     return groupName;
1837 }
1838 
WriteDeviceChangedSysEvents(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)1839 void AudioPolicyService::WriteDeviceChangedSysEvents(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected)
1840 {
1841     for (auto deviceDescriptor : desc) {
1842         if (deviceDescriptor != nullptr) {
1843             if ((deviceDescriptor->deviceType_ == DEVICE_TYPE_WIRED_HEADSET)
1844                 || (deviceDescriptor->deviceType_ == DEVICE_TYPE_USB_HEADSET)
1845                 || (deviceDescriptor->deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES)) {
1846                 HiviewDFX::HiSysEvent::Write("AUDIO", "AUDIO_HEADSET_CHANGE",
1847                     HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
1848                     "ISCONNECT", isConnected ? 1 : 0,
1849                     "HASMIC", 1,
1850                     "DEVICETYPE", deviceDescriptor->deviceType_);
1851             }
1852 
1853             if (!isConnected) {
1854                 continue;
1855             }
1856 
1857             if (deviceDescriptor->deviceRole_ == OUTPUT_DEVICE) {
1858                 vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs();
1859                 for (SinkInput sinkInput : sinkInputs) {
1860                     HiviewDFX::HiSysEvent::Write("AUDIO", "AUDIO_DEVICE_CHANGE",
1861                         HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
1862                         "ISOUTPUT", 1,
1863                         "STREAMID", sinkInput.streamId,
1864                         "STREAMTYPE", sinkInput.streamType,
1865                         "DEVICETYPE", deviceDescriptor->deviceType_);
1866                 }
1867             } else if (deviceDescriptor->deviceRole_ == INPUT_DEVICE) {
1868                 vector<SourceOutput> sourceOutputs = audioPolicyManager_.GetAllSourceOutputs();
1869                 for (SourceOutput sourceOutput : sourceOutputs) {
1870                     HiviewDFX::HiSysEvent::Write("AUDIO", "AUDIO_DEVICE_CHANGE",
1871                         HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
1872                         "ISOUTPUT", 0,
1873                         "STREAMID", sourceOutput.streamId,
1874                         "STREAMTYPE", sourceOutput.streamType,
1875                         "DEVICETYPE", deviceDescriptor->deviceType_);
1876                 }
1877             }
1878         }
1879     }
1880 }
1881 
UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> & desc)1882 void AudioPolicyService::UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> &desc)
1883 {
1884     for (sptr<AudioDeviceDescriptor> deviceDesc : desc) {
1885         if (deviceDesc->deviceRole_ == OUTPUT_DEVICE) {
1886             DeviceType activeDevice = currentActiveDevice_;
1887             auto isPresent = [&activeDevice] (const sptr<AudioDeviceDescriptor> &desc) {
1888                 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
1889                 return ((activeDevice == desc->deviceType_) && (OUTPUT_DEVICE == desc->deviceRole_));
1890             };
1891 
1892             auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
1893             if (itr != connectedDevices_.end()) {
1894                 DeviceInfo outputDevice = {};
1895                 UpdateDeviceInfo(outputDevice, *itr, true);
1896                 streamCollector_.UpdateTracker(AUDIO_MODE_PLAYBACK, outputDevice);
1897             }
1898         }
1899 
1900         if (deviceDesc->deviceRole_ == INPUT_DEVICE) {
1901             DeviceType activeDevice = activeInputDevice_;
1902             auto isPresent = [&activeDevice] (const sptr<AudioDeviceDescriptor> &desc) {
1903                 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor");
1904                 return ((activeDevice == desc->deviceType_) && (INPUT_DEVICE == desc->deviceRole_));
1905             };
1906 
1907             auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent);
1908             if (itr != connectedDevices_.end()) {
1909                 DeviceInfo inputDevice = {};
1910                 UpdateDeviceInfo(inputDevice, *itr, true);
1911                 streamCollector_.UpdateTracker(AUDIO_MODE_RECORD, inputDevice);
1912             }
1913         }
1914     }
1915 }
1916 
UpdateGroupInfo(GroupType type,std::string groupName,int32_t & groupId,std::string networkId,bool connected,int32_t mappingId)1917 void AudioPolicyService::UpdateGroupInfo(GroupType type, std::string groupName, int32_t& groupId, std::string networkId,
1918     bool connected, int32_t mappingId)
1919 {
1920     ConnectType connectType = CONNECT_TYPE_LOCAL;
1921     if (networkId != LOCAL_NETWORK_ID) {
1922         connectType = CONNECT_TYPE_DISTRIBUTED;
1923     }
1924     if (type == GroupType::VOLUME_TYPE) {
1925         auto isPresent = [&groupName, &networkId] (const sptr<VolumeGroupInfo> &volumeInfo) {
1926             return ((groupName == volumeInfo->groupName_) || (networkId == volumeInfo->networkId_));
1927         };
1928 
1929         auto iter = std::find_if(volumeGroups_.begin(), volumeGroups_.end(), isPresent);
1930         if (iter != volumeGroups_.end()) {
1931             groupId = (*iter)->volumeGroupId_;
1932             // if status is disconnected, remove the group that has none audio device
1933             std::vector<sptr<AudioDeviceDescriptor>> devsInGroup = GetDevicesForGroup(type, groupId);
1934             if (!connected && devsInGroup.size() == 0) {
1935                 volumeGroups_.erase(iter);
1936             }
1937             return;
1938         }
1939         if (groupName != GROUP_NAME_NONE && connected) {
1940             groupId = AudioGroupHandle::GetInstance().GetNextId(type);
1941             sptr<VolumeGroupInfo> volumeGroupInfo = new(std::nothrow) VolumeGroupInfo(groupId,
1942                 mappingId, groupName, networkId, connectType);
1943             volumeGroups_.push_back(volumeGroupInfo);
1944         }
1945     } else {
1946         auto isPresent = [&groupName, &networkId] (const sptr<InterruptGroupInfo> &info) {
1947             return ((groupName == info->groupName_) || (networkId == info->networkId_));
1948         };
1949 
1950         auto iter = std::find_if(interruptGroups_.begin(), interruptGroups_.end(), isPresent);
1951         if (iter != interruptGroups_.end()) {
1952             groupId = (*iter)->interruptGroupId_;
1953             // if status is disconnected, remove the group that has none audio device
1954             std::vector<sptr<AudioDeviceDescriptor>> devsInGroup = GetDevicesForGroup(type, groupId);
1955             if (!connected && devsInGroup.size() == 0) {
1956                 interruptGroups_.erase(iter);
1957             }
1958             return;
1959         }
1960         if (groupName != GROUP_NAME_NONE && connected) {
1961             groupId = AudioGroupHandle::GetInstance().GetNextId(type);
1962             sptr<InterruptGroupInfo> interruptGroupInfo = new(std::nothrow) InterruptGroupInfo(groupId, mappingId,
1963                 groupName, networkId, connectType);
1964             interruptGroups_.push_back(interruptGroupInfo);
1965         }
1966     }
1967 }
1968 
GetDevicesForGroup(GroupType type,int32_t groupId)1969 std::vector<sptr<OHOS::AudioStandard::AudioDeviceDescriptor>> AudioPolicyService::GetDevicesForGroup(GroupType type,
1970     int32_t groupId)
1971 {
1972     std::vector<sptr<OHOS::AudioStandard::AudioDeviceDescriptor>> devices = {};
1973     for (auto devDes : connectedDevices_) {
1974         bool inVolumeGroup = type == VOLUME_TYPE && devDes->volumeGroupId_ == groupId;
1975         bool inInterruptGroup = type == INTERRUPT_TYPE && devDes->interruptGroupId_ == groupId;
1976 
1977         if (inVolumeGroup || inInterruptGroup) {
1978             sptr<AudioDeviceDescriptor> device = new AudioDeviceDescriptor(*devDes);
1979             devices.push_back(device);
1980         }
1981     }
1982     return devices;
1983 }
1984 
TriggerDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)1985 void AudioPolicyService::TriggerDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected)
1986 {
1987     DeviceChangeAction deviceChangeAction;
1988     deviceChangeAction.type = isConnected ? DeviceChangeType::CONNECT : DeviceChangeType::DISCONNECT;
1989 
1990     WriteDeviceChangedSysEvents(desc, isConnected);
1991 
1992     for (auto it = deviceChangeCallbackMap_.begin(); it != deviceChangeCallbackMap_.end(); ++it) {
1993         deviceChangeAction.deviceDescriptors = DeviceFilterByFlag(it->second.first, desc);
1994         if (it->second.second && deviceChangeAction.deviceDescriptors.size() > 0) {
1995             it->second.second->OnDeviceChange(deviceChangeAction);
1996         }
1997     }
1998 }
1999 
DeviceFilterByFlag(DeviceFlag flag,const std::vector<sptr<AudioDeviceDescriptor>> & desc)2000 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::DeviceFilterByFlag(DeviceFlag flag,
2001     const std::vector<sptr<AudioDeviceDescriptor>>& desc)
2002 {
2003     std::vector<sptr<AudioDeviceDescriptor>> descRet;
2004     DeviceRole role = DEVICE_ROLE_NONE;
2005     switch (flag) {
2006         case DeviceFlag::ALL_DEVICES_FLAG:
2007             for (sptr<AudioDeviceDescriptor> var : desc) {
2008                 if (var->networkId_ == LOCAL_NETWORK_ID) {
2009                     descRet.insert(descRet.end(), var);
2010                 }
2011             }
2012             break;
2013         case DeviceFlag::ALL_DISTRIBUTED_DEVICES_FLAG:
2014             for (sptr<AudioDeviceDescriptor> var : desc) {
2015                 if (var->networkId_ != LOCAL_NETWORK_ID) {
2016                     descRet.insert(descRet.end(), var);
2017                 }
2018             }
2019             break;
2020         case DeviceFlag::ALL_L_D_DEVICES_FLAG:
2021             descRet = desc;
2022             break;
2023         case DeviceFlag::OUTPUT_DEVICES_FLAG:
2024         case DeviceFlag::INPUT_DEVICES_FLAG:
2025             role = flag == INPUT_DEVICES_FLAG ? INPUT_DEVICE : OUTPUT_DEVICE;
2026             for (sptr<AudioDeviceDescriptor> var : desc) {
2027                 if (var->networkId_ == LOCAL_NETWORK_ID && var->deviceRole_ == role) {
2028                     descRet.insert(descRet.end(), var);
2029                 }
2030             }
2031             break;
2032         case DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG:
2033         case DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG:
2034             role = flag == DISTRIBUTED_INPUT_DEVICES_FLAG ? INPUT_DEVICE : OUTPUT_DEVICE;
2035             for (sptr<AudioDeviceDescriptor> var : desc) {
2036                 if (var->networkId_ != LOCAL_NETWORK_ID && var->deviceRole_ == role) {
2037                     descRet.insert(descRet.end(), var);
2038                 }
2039             }
2040             break;
2041         default:
2042             AUDIO_INFO_LOG("AudioPolicyService::%{public}s:deviceFlag type are not supported", __func__);
2043             break;
2044     }
2045     return descRet;
2046 }
2047 
GetDeviceRole(DeviceType deviceType) const2048 DeviceRole AudioPolicyService::GetDeviceRole(DeviceType deviceType) const
2049 {
2050     switch (deviceType) {
2051         case DeviceType::DEVICE_TYPE_SPEAKER:
2052         case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
2053         case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
2054         case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
2055         case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
2056         case DeviceType::DEVICE_TYPE_USB_HEADSET:
2057             return DeviceRole::OUTPUT_DEVICE;
2058         case DeviceType::DEVICE_TYPE_MIC:
2059             return DeviceRole::INPUT_DEVICE;
2060         default:
2061             return DeviceRole::DEVICE_ROLE_NONE;
2062     }
2063 }
2064 
GetDeviceRole(const std::string & role)2065 DeviceRole AudioPolicyService::GetDeviceRole(const std::string &role)
2066 {
2067     if (role == ROLE_SINK) {
2068         return DeviceRole::OUTPUT_DEVICE;
2069     } else if (role == ROLE_SOURCE) {
2070         return DeviceRole::INPUT_DEVICE;
2071     } else {
2072         return DeviceRole::DEVICE_ROLE_NONE;
2073     }
2074 }
2075 
GetDeviceRole(AudioPin pin) const2076 DeviceRole AudioPolicyService::GetDeviceRole(AudioPin pin) const
2077 {
2078     switch (pin) {
2079         case OHOS::AudioStandard::AUDIO_PIN_NONE:
2080             return DeviceRole::DEVICE_ROLE_NONE;
2081         case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER:
2082         case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET:
2083         case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT:
2084         case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI:
2085         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB:
2086         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT:
2087         case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT:
2088             return DeviceRole::OUTPUT_DEVICE;
2089         case OHOS::AudioStandard::AUDIO_PIN_IN_MIC:
2090         case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC:
2091         case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN:
2092         case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT:
2093         case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT:
2094             return DeviceRole::INPUT_DEVICE;
2095         default:
2096             return DeviceRole::DEVICE_ROLE_NONE;
2097     }
2098 }
2099 
OnAudioLatencyParsed(uint64_t latency)2100 void AudioPolicyService::OnAudioLatencyParsed(uint64_t latency)
2101 {
2102     audioLatencyInMsec_ = latency;
2103 }
2104 
GetAudioLatencyFromXml() const2105 int32_t AudioPolicyService::GetAudioLatencyFromXml() const
2106 {
2107     return audioLatencyInMsec_;
2108 }
2109 
OnSinkLatencyParsed(uint32_t latency)2110 void AudioPolicyService::OnSinkLatencyParsed(uint32_t latency)
2111 {
2112     sinkLatencyInMsec_ = latency;
2113 }
2114 
GetSinkLatencyFromXml() const2115 uint32_t AudioPolicyService::GetSinkLatencyFromXml() const
2116 {
2117     return sinkLatencyInMsec_;
2118 }
2119 
UpdateInputDeviceInfo(DeviceType deviceType)2120 void AudioPolicyService::UpdateInputDeviceInfo(DeviceType deviceType)
2121 {
2122     AUDIO_DEBUG_LOG("Current input device is %{public}d", activeInputDevice_);
2123 
2124     switch (deviceType) {
2125         case DEVICE_TYPE_SPEAKER:
2126         case DEVICE_TYPE_BLUETOOTH_A2DP:
2127             activeInputDevice_ = DEVICE_TYPE_MIC;
2128             break;
2129         case DEVICE_TYPE_FILE_SINK:
2130             activeInputDevice_ = DEVICE_TYPE_FILE_SOURCE;
2131             break;
2132         case DEVICE_TYPE_WIRED_HEADSET:
2133         case DEVICE_TYPE_USB_HEADSET:
2134         case DEVICE_TYPE_BLUETOOTH_SCO:
2135             activeInputDevice_ = deviceType;
2136             break;
2137         default:
2138             break;
2139     }
2140 
2141     AUDIO_DEBUG_LOG("Input device updated to %{public}d", activeInputDevice_);
2142 }
2143 
UpdateStreamState(int32_t clientUid,StreamSetStateEventInternal & streamSetStateEventInternal)2144 int32_t AudioPolicyService::UpdateStreamState(int32_t clientUid,
2145     StreamSetStateEventInternal &streamSetStateEventInternal)
2146 {
2147     return streamCollector_.UpdateStreamState(clientUid, streamSetStateEventInternal);
2148 }
2149 
GetDeviceTypeFromPin(AudioPin hdiPin)2150 DeviceType AudioPolicyService::GetDeviceTypeFromPin(AudioPin hdiPin)
2151 {
2152     switch (hdiPin) {
2153         case OHOS::AudioStandard::AUDIO_PIN_NONE:
2154             break;
2155         case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER:
2156         case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT:
2157             return DeviceType::DEVICE_TYPE_SPEAKER;
2158         case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET:
2159             break;
2160         case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT:
2161             break;
2162         case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI:
2163             break;
2164         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB:
2165             break;
2166         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT:
2167             break;
2168         case OHOS::AudioStandard::AUDIO_PIN_IN_MIC:
2169         case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT:
2170             return DeviceType::DEVICE_TYPE_MIC;
2171         case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC:
2172             break;
2173         case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN:
2174             break;
2175         case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT:
2176             break;
2177         default:
2178             break;
2179     }
2180     return DeviceType::DEVICE_TYPE_DEFAULT;
2181 }
2182 
GetVolumeGroupInfos()2183 std::vector<sptr<VolumeGroupInfo>> AudioPolicyService::GetVolumeGroupInfos()
2184 {
2185     std::vector<sptr<VolumeGroupInfo>> volumeGroupInfos = {};
2186 
2187     for (auto& v : volumeGroups_) {
2188         sptr<VolumeGroupInfo> info = new(std::nothrow) VolumeGroupInfo(v->volumeGroupId_, v->mappingId_, v->groupName_,
2189             v->networkId_, v->connectType_);
2190         volumeGroupInfos.push_back(info);
2191     }
2192     return volumeGroupInfos;
2193 }
2194 
SetParameterCallback(const std::shared_ptr<AudioParameterCallback> & callback)2195 void AudioPolicyService::SetParameterCallback(const std::shared_ptr<AudioParameterCallback>& callback)
2196 {
2197     AUDIO_INFO_LOG("Enter AudioPolicyService::SetParameterCallback");
2198     auto parameterChangeCbStub = new(std::nothrow) AudioManagerListenerStub();
2199     if (parameterChangeCbStub == nullptr) {
2200         AUDIO_ERR_LOG("SetDeviceChangeCallback: parameterChangeCbStub null");
2201         return;
2202     }
2203     const sptr<IStandardAudioService> gsp = GetAudioPolicyServiceProxy();
2204     if (gsp == nullptr) {
2205         AUDIO_ERR_LOG("SetDeviceChangeCallback: g_adProxy null");
2206         return;
2207     }
2208     parameterChangeCbStub->SetParameterCallback(callback);
2209 
2210     sptr<IRemoteObject> object = parameterChangeCbStub->AsObject();
2211     if (object == nullptr) {
2212         AUDIO_ERR_LOG("AudioPolicyService: listenerStub->AsObject is nullptr..");
2213         delete parameterChangeCbStub;
2214         return;
2215     }
2216     AUDIO_INFO_LOG("AudioPolicyService: SetParameterCallback call SetParameterCallback.");
2217     gsp->SetParameterCallback(object);
2218 }
2219 
RegisterBluetoothListener()2220 void AudioPolicyService::RegisterBluetoothListener()
2221 {
2222 #ifdef BLUETOOTH_ENABLE
2223     AUDIO_INFO_LOG("Enter AudioPolicyService::RegisterBluetoothListener");
2224     Bluetooth::RegisterDeviceObserver(deviceStatusListener_->deviceObserver_);
2225     Bluetooth::AudioA2dpManager::RegisterBluetoothA2dpListener();
2226     Bluetooth::AudioHfpManager::RegisterBluetoothScoListener();
2227     isBtListenerRegistered = true;
2228 #endif
2229 }
2230 
UnregisterBluetoothListener()2231 void AudioPolicyService::UnregisterBluetoothListener()
2232 {
2233 #ifdef BLUETOOTH_ENABLE
2234     AUDIO_INFO_LOG("Enter AudioPolicyService::UnregisterBluetoothListener");
2235     Bluetooth::UnregisterDeviceObserver();
2236     Bluetooth::AudioA2dpManager::UnregisterBluetoothA2dpListener();
2237     Bluetooth::AudioHfpManager::UnregisterBluetoothScoListener();
2238     isBtListenerRegistered = false;
2239 #endif
2240 }
2241 
SubscribeAccessibilityConfigObserver()2242 void AudioPolicyService::SubscribeAccessibilityConfigObserver()
2243 {
2244 #ifdef ACCESSIBILITY_ENABLE
2245     accessibilityConfigListener_->SubscribeObserver();
2246     AUDIO_INFO_LOG("Subscribe accessibility config observer successfully");
2247 #endif
2248 }
2249 } // namespace AudioStandard
2250 } // namespace OHOS
2251