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