1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef ST_AUDIO_POLICY_SERVICE_H
17 #define ST_AUDIO_POLICY_SERVICE_H
18 
19 #include <bitset>
20 #include <list>
21 #include <string>
22 #include <unordered_map>
23 #include <unordered_set>
24 #include <mutex>
25 #include "singleton.h"
26 #include "audio_group_handle.h"
27 #include "audio_info.h"
28 #include "audio_manager_base.h"
29 #include "audio_policy_client_proxy.h"
30 #include "audio_policy_manager_factory.h"
31 #include "audio_stream_collector.h"
32 #include "audio_router_center.h"
33 #include "datashare_helper.h"
34 #include "ipc_skeleton.h"
35 #include "power_mgr_client.h"
36 #ifdef FEATURE_DTMF_TONE
37 #include "audio_tone_parser.h"
38 #endif
39 
40 #ifdef ACCESSIBILITY_ENABLE
41 #include "accessibility_config_listener.h"
42 #else
43 #include "iaudio_accessibility_config_observer.h"
44 #endif
45 #include "device_status_listener.h"
46 #include "iaudio_policy_interface.h"
47 #include "iport_observer.h"
48 #include "audio_policy_parser_factory.h"
49 #include "audio_effect_manager.h"
50 #include "audio_volume_config.h"
51 #include "policy_provider_stub.h"
52 #include "audio_device_manager.h"
53 #include "audio_device_parser.h"
54 #include "audio_state_manager.h"
55 #include "audio_pnp_server.h"
56 #include "audio_policy_server_handler.h"
57 
58 #ifdef BLUETOOTH_ENABLE
59 #include "audio_server_death_recipient.h"
60 #include "audio_bluetooth_manager.h"
61 #include "bluetooth_device_manager.h"
62 #endif
63 
64 namespace OHOS {
65 namespace AudioStandard {
66 enum A2dpOffloadConnectionState : int32_t {
67     CONNECTION_STATUS_DISCONNECTED = 0,
68     CONNECTION_STATUS_CONNECTING = 1,
69     CONNECTION_STATUS_CONNECTED = 2,
70     CONNECTION_STATUS_TIMEOUT = 3,
71 };
72 
73 class AudioA2dpOffloadManager;
74 
75 class AudioPolicyService : public IPortObserver, public IDeviceStatusObserver,
76     public IAudioAccessibilityConfigObserver, public IPolicyProvider {
77 public:
GetAudioPolicyService()78     static AudioPolicyService& GetAudioPolicyService()
79     {
80         static AudioPolicyService audioPolicyService;
81         return audioPolicyService;
82     }
83 
84     bool Init(void);
85     void Deinit(void);
86     void InitKVStore();
87     bool ConnectServiceAdapter();
88 
89     void OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status);
90 
91     void OnBlockedStatusUpdated(DeviceType devType, DeviceBlockStatus status);
92 
93     void TriggerMicrophoneBlockedCallback(const std::vector<sptr<AudioDeviceDescriptor>> &desc,
94         DeviceBlockStatus status);
95 
96     int32_t GetMaxVolumeLevel(AudioVolumeType volumeType) const;
97 
98     int32_t GetMinVolumeLevel(AudioVolumeType volumeType) const;
99 
100     int32_t SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel);
101 
102     int32_t SelectDealSafeVolume(AudioStreamType streamType, int32_t volumeLevel);
103 
104     int32_t GetSystemVolumeLevel(AudioStreamType streamType);
105 
106     float GetSystemVolumeDb(AudioStreamType streamType) const;
107 
108     int32_t SetLowPowerVolume(int32_t streamId, float volume) const;
109 
110     float GetLowPowerVolume(int32_t streamId) const;
111 
112     void HandlePowerStateChanged(PowerMgr::PowerState state);
113 
114     float GetSingleStreamVolume(int32_t streamId) const;
115 
116     int32_t SetStreamMute(AudioStreamType streamType, bool mute,
117         const StreamUsage &streamUsage = STREAM_USAGE_UNKNOWN);
118 
119     int32_t SetSourceOutputStreamMute(int32_t uid, bool setMute) const;
120 
121     bool GetStreamMute(AudioStreamType streamType);
122 
123     bool IsStreamActive(AudioStreamType streamType) const;
124 
125     void NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value);
126 
127     void NotifyUserSelectionEventToBt(sptr<AudioDeviceDescriptor> audioDeviceDescriptor);
128 
129     bool IsArmUsbDevice(const AudioDeviceDescriptor &desc);
130 
131     int32_t SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
132         std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors);
133     int32_t SelectFastOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
134         sptr<AudioDeviceDescriptor> deviceDescriptor);
135 
136     std::string GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType);
137 
138     int32_t SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
139         std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors);
140 
141     std::vector<sptr<AudioDeviceDescriptor>> GetDevices(DeviceFlag deviceFlag);
142 
143     std::vector<sptr<AudioDeviceDescriptor>> GetDevicesInner(DeviceFlag deviceFlag);
144 
145     int32_t SetWakeUpAudioCapturer(InternalAudioCapturerOptions options);
146 
147     int32_t SetWakeUpAudioCapturerFromAudioServer(const AudioProcessConfig &config);
148 
149     int32_t NotifyCapturerAdded(AudioCapturerInfo capturerInfo, AudioStreamInfo streamInfo, uint32_t sessionId);
150 
151     int32_t CloseWakeUpAudioCapturer();
152 
153     int32_t NotifyWakeUpCapturerRemoved();
154 
155     bool IsAbsVolumeSupported();
156 
157     int32_t SetDeviceActive(InternalDeviceType deviceType, bool active);
158 
159     bool IsDeviceActive(InternalDeviceType deviceType);
160 
161     DeviceType GetActiveOutputDevice();
162 
163     unique_ptr<AudioDeviceDescriptor> GetActiveOutputDeviceDescriptor();
164 
165     DeviceType GetActiveInputDevice();
166 
167     int32_t SetRingerMode(AudioRingerMode ringMode);
168 
169     AudioRingerMode GetRingerMode() const;
170 
171     int32_t SetMicrophoneMute(bool isMute);
172 
173     int32_t SetMicrophoneMutePersistent(const bool isMute);
174 
175     int32_t InitPersistentMicrophoneMuteState(bool &isMute);
176 
177     bool GetPersistentMicMuteState();
178 
179     bool IsMicrophoneMute();
180 
181     int32_t SetAudioScene(AudioScene audioScene);
182 
183     AudioScene GetAudioScene(bool hasSystemPermission = true) const;
184 
185     int32_t GetAudioLatencyFromXml() const;
186 
187     uint32_t GetSinkLatencyFromXml() const;
188 
189     int32_t GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo, const std::string &bundleName);
190 
191     int32_t GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo);
192 
193     int32_t SetSystemSoundUri(const std::string &key, const std::string &uri);
194 
195     std::string GetSystemSoundUri(const std::string &key);
196 
197     void SetNormalVoipFlag(const bool &normalVoipFlag);
198 
199     int32_t GetVoipRendererFlag(const std::string &sinkPortName, const std::string &networkId,
200         const AudioSamplingRate &samplingRate);
201 
202     bool GetVoipConfig();
203 
204     // Audio Policy Parser callbacks
205     void OnAudioPolicyXmlParsingCompleted(const std::unordered_map<AdaptersType, AudioAdapterInfo> adapterInfoMap);
206 
207     // Parser callbacks
208     void OnXmlParsingCompleted(const std::unordered_map<ClassType, std::list<AudioModuleInfo>> &xmldata);
209 
210     void OnVolumeGroupParsed(std::unordered_map<std::string, std::string>& volumeGroupData);
211 
212     void OnInterruptGroupParsed(std::unordered_map<std::string, std::string>& interruptGroupData);
213 
214     void OnGlobalConfigsParsed(GlobalConfigs &globalConfigs);
215 
216     void OnVoipConfigParsed(bool enableFastVoip);
217 
218     void OnUpdateRouteSupport(bool isSupported);
219 
220     int32_t GetDeviceNameFromDataShareHelper(std::string &deviceName);
221 
222     void SetDisplayName(const std::string &deviceName, bool isLocalDevice);
223 
224     bool IsDataShareReady();
225 
226     void SetDataShareReady(std::atomic<bool> isDataShareReady);
227 
228     int32_t ResumeStreamState();
229 #ifdef FEATURE_DTMF_TONE
230     std::vector<int32_t> GetSupportedTones();
231 
232     std::shared_ptr<ToneInfo> GetToneConfig(int32_t ltonetype);
233 #endif
234 
235     void OnDeviceStatusUpdated(DeviceType devType, bool isConnected,
236         const std::string &macAddress, const std::string &deviceName,
237         const AudioStreamInfo &streamInfo);
238     void OnDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected);
239 
240     void OnPnpDeviceStatusUpdated(DeviceType devType, bool isConnected);
241 
242     void OnPnpDeviceStatusUpdated(DeviceType devType, bool isConnected,
243         const std::string &name, const std::string &adderess);
244 
245     void OnDeviceConfigurationChanged(DeviceType deviceType,
246         const std::string &macAddress, const std::string &deviceName,
247         const AudioStreamInfo &streamInfo);
248 
249     void OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop = false);
250 
251     void checkOffloadAvailable(AudioModuleInfo& moduleInfo);
252 
253     void OnServiceDisconnected(AudioServiceIndex serviceIndex);
254 
255     void OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress);
256 
257     void OnMonoAudioConfigChanged(bool audioMono);
258 
259     void OnAudioBalanceChanged(float audioBalance);
260 
261     void LoadEffectLibrary();
262 
263     int32_t SetAudioStreamRemovedCallback(AudioStreamRemovedCallback *callback);
264 
265     void AddAudioPolicyClientProxyMap(int32_t clientPid, const sptr<IAudioPolicyClient>& cb);
266 
267     void ReduceAudioPolicyClientProxyMap(pid_t clientPid);
268 
269     int32_t SetPreferredDevice(const PreferredType preferredType, const sptr<AudioDeviceDescriptor> &desc);
270 
271     int32_t SetPreferredOutputDeviceChangeCallback(const int32_t clientId, const sptr<IRemoteObject> &object,
272         bool hasBTPermission);
273 
274     int32_t SetPreferredInputDeviceChangeCallback(const int32_t clientId, const sptr<IRemoteObject> &object,
275         bool hasBTPermission);
276 
277     int32_t UnsetPreferredOutputDeviceChangeCallback(const int32_t clientId);
278 
279     int32_t UnsetPreferredInputDeviceChangeCallback(const int32_t clientId);
280 
281     int32_t RegisterAudioRendererEventListener(int32_t clientPid, const sptr<IRemoteObject> &object,
282         bool hasBTPermission, bool hasSysPermission);
283 
284     int32_t UnregisterAudioRendererEventListener(int32_t clientPid);
285 
286     int32_t RegisterAudioCapturerEventListener(int32_t clientPid, const sptr<IRemoteObject> &object,
287         bool hasBTPermission, bool hasSysPermission);
288 
289     int32_t UnregisterAudioCapturerEventListener(int32_t clientPid);
290 
291     int32_t SetAvailableDeviceChangeCallback(const int32_t clientId, const AudioDeviceUsage usage,
292         const sptr<IRemoteObject> &object, bool hasBTPermission);
293 
294     int32_t UnsetAvailableDeviceChangeCallback(const int32_t clientId, AudioDeviceUsage usage);
295 
296     int32_t SetQueryClientTypeCallback(const sptr<IRemoteObject> &object);
297 
298     int32_t RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
299         const sptr<IRemoteObject> &object, const int32_t apiVersion);
300 
301     int32_t UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo);
302 
303     int32_t GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>> &audioRendererChangeInfos,
304         bool hasBTPermission, bool hasSystemPermission);
305 
306     int32_t GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>> &audioCapturerChangeInfos,
307         bool hasBTPermission, bool hasSystemPermission);
308 
309     void RegisteredTrackerClientDied(pid_t uid);
310 
311     void ClientDiedDisconnectScoNormal();
312 
313     void ClientDiedDisconnectScoRecognition();
314 
315     int32_t ReconfigureAudioChannel(const uint32_t &count, DeviceType deviceType);
316 
317     void OnAudioLatencyParsed(uint64_t latency);
318 
319     void OnSinkLatencyParsed(uint32_t latency);
320 
321     int32_t UpdateStreamState(int32_t clientUid, StreamSetStateEventInternal &streamSetStateEventInternal);
322 
323     DeviceType GetDeviceTypeFromPin(AudioPin pin);
324 
325     std::vector<sptr<VolumeGroupInfo>> GetVolumeGroupInfos();
326 
327     void SetParameterCallback(const std::shared_ptr<AudioParameterCallback>& callback);
328 
329     void RegiestPolicy();
330 
331     // override for IPolicyProvider
332     int32_t GetProcessDeviceInfo(const AudioProcessConfig &config, bool lockFlag, DeviceInfo &deviceInfo);
333 
334     int32_t InitSharedVolume(std::shared_ptr<AudioSharedMemory> &buffer);
335 
336     bool GetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume &vol);
337 
338 #ifdef BLUETOOTH_ENABLE
339     static void BluetoothServiceCrashedCallback(pid_t pid);
340 #endif
341 
342     void RegisterBluetoothListener();
343 
344     void SubscribeAccessibilityConfigObserver();
345 
346     std::vector<sptr<AudioDeviceDescriptor>> GetPreferredOutputDeviceDescriptors(AudioRendererInfo &rendererInfo,
347         std::string networkId = LOCAL_NETWORK_ID);
348 
349     std::vector<sptr<AudioDeviceDescriptor>> GetPreferredInputDeviceDescriptors(AudioCapturerInfo &captureInfo,
350         std::string networkId = LOCAL_NETWORK_ID);
351 
352     std::vector<sptr<AudioDeviceDescriptor>> GetPreferredOutputDeviceDescInner(AudioRendererInfo &rendererInfo,
353         std::string networkId = LOCAL_NETWORK_ID);
354 
355     std::vector<sptr<AudioDeviceDescriptor>> GetPreferredInputDeviceDescInner(AudioCapturerInfo &captureInfo,
356         std::string networkId = LOCAL_NETWORK_ID);
357 
358     int32_t SetClientCallbacksEnable(const CallbackChange &callbackchange, const bool &enable);
359 
360     float GetMinStreamVolume(void);
361 
362     float GetMaxStreamVolume(void);
363 
364     int32_t GetMaxRendererInstances();
365 
366     int32_t CheckMaxRendererInstances();
367 
368     void RegisterDataObserver();
369 
370     bool IsVolumeUnadjustable();
371 
372     void GetStreamVolumeInfoMap(StreamVolumeInfoMap &streamVolumeInfos);
373 
374     float GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel, DeviceType deviceType) const;
375 
376     int32_t QueryEffectManagerSceneMode(SupportedEffectConfig &supportedEffectConfig);
377 
378     void UpdateDescWhenNoBTPermission(vector<sptr<AudioDeviceDescriptor>> &desc);
379 
380     int32_t SetPlaybackCapturerFilterInfos(const AudioPlaybackCaptureConfig &config);
381 
382     int32_t SetCaptureSilentState(bool state);
383 
384     int32_t GetHardwareOutputSamplingRate(const sptr<AudioDeviceDescriptor> &desc);
385 
386     vector<sptr<MicrophoneDescriptor>> GetAudioCapturerMicrophoneDescriptors(int32_t sessionId);
387 
388     vector<sptr<MicrophoneDescriptor>> GetAvailableMicrophones();
389 
390     int32_t SetDeviceAbsVolumeSupported(const std::string &macAddress, const bool support);
391 
392     bool IsAbsVolumeScene() const;
393 
394     bool IsVgsVolumeSupported() const;
395 
396     int32_t SetA2dpDeviceVolume(const std::string &macAddress, const int32_t volume, bool internalCall = false);
397 
398     int32_t OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo, AudioStreamInfo streamInfo);
399 
400     void OnCapturerSessionRemoved(uint64_t sessionID);
401 
402     std::vector<unique_ptr<AudioDeviceDescriptor>> GetAvailableDevices(AudioDeviceUsage usage);
403 
404     void TriggerAvailableDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected);
405 
406     void OffloadStreamSetCheck(uint32_t sessionId);
407 
408     void OffloadStreamReleaseCheck(uint32_t sessionId);
409 
410     void RemoteOffloadStreamRelease(uint32_t sessionId);
411 
412     int32_t OffloadStopPlaying(const std::vector<int32_t> &sessionIds);
413 
414     int32_t OffloadGetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp);
415 
416     int32_t GetAndSaveClientType(uint32_t uid, const std::string &bundleName);
417 
418     void GetA2dpOffloadCodecAndSendToDsp();
419 
420     int32_t HandleA2dpDeviceInOffload(BluetoothOffloadState a2dpOffloadFlag);
421 
422     int32_t HandleA2dpDeviceOutOffload(BluetoothOffloadState a2dpOffloadFlag);
423 
424     void ConfigDistributedRoutingRole(const sptr<AudioDeviceDescriptor> descriptor, CastType type);
425 
426     DistributedRoutingInfo GetDistributedRoutingRoleInfo();
427 
428     void OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command);
429 
430     void DeviceUpdateClearRecongnitionStatus(AudioDeviceDescriptor &desc);
431 
432     void UpdateA2dpOffloadFlagBySpatialService(
433         const std::string& macAddress, std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnableMap);
434 
435     std::vector<sptr<AudioDeviceDescriptor>> DeviceFilterByUsageInner(AudioDeviceUsage usage,
436         const std::vector<sptr<AudioDeviceDescriptor>>& descs);
437 
438     int32_t SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address);
439 
440     std::unique_ptr<AudioDeviceDescriptor> GetActiveBluetoothDevice();
441 
442     ConverterConfig GetConverterConfig();
443 
444     void FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo,
445         const AudioStreamDeviceChangeReasonExt reason);
446 
447     void FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo);
448 
449     float GetMaxAmplitude(const int32_t deviceId);
450 
451     int32_t TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
452 
453     int32_t DisableSafeMediaVolume();
454 
455     int32_t SafeVolumeDialogDisapper();
456 
457     void NotifyAccountsChanged(const int &id);
458 
459     int32_t ActivateConcurrencyFromServer(AudioPipeType incomingPipe);
460 
461     // for hidump
462     void DevicesInfoDump(std::string &dumpString);
463     void AudioModeDump(std::string &dumpString);
464     void AudioPolicyParserDump(std::string &dumpString);
465     void XmlParsedDataMapDump(std::string &dumpString);
466     void StreamVolumesDump(std::string &dumpString);
467     void DeviceVolumeInfosDump(std::string &dumpString, DeviceVolumeInfoMap &deviceVolumeInfos);
468     void AudioStreamDump(std::string &dumpString);
469     void GetVolumeConfigDump(std::string &dumpString);
470     void GetGroupInfoDump(std::string &dumpString);
471     void GetCallStatusDump(std::string &dumpString);
472     void GetRingerModeDump(std::string &dumpString);
473     void GetMicrophoneDescriptorsDump(std::string &dumpString);
474     void GetCapturerStreamDump(std::string &dumpString);
475     void GetSafeVolumeDump(std::string &dumpString);
476     void GetOffloadStatusDump(std::string &dumpString);
477     void EffectManagerInfoDump(std::string &dumpString);
478     void MicrophoneMuteInfoDump(std::string &dumpString);
479 
480     int32_t GetCurActivateCount();
481     void CheckStreamMode(const int64_t activateSessionId);
482 
483     int32_t MoveToNewPipe(const uint32_t sessionId, const AudioPipeType pipeType);
484     int32_t DynamicUnloadModule(const AudioPipeType pipeType);
485 
486     int32_t SetAudioConcurrencyCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object);
487 
488     int32_t UnsetAudioConcurrencyCallback(const uint32_t sessionID);
489 
490     int32_t ActivateAudioConcurrency(const AudioPipeType &pipeType);
491 
492     void OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName);
493 
494     int32_t ResetRingerModeMute();
495 
496     bool IsRingerModeMute();
497 
498     AudioScene GetLastAudioScene() const;
499 
500     void SetRotationToEffect(const uint32_t rotate);
501     void FetchStreamForA2dpOffload(const bool &requireReset);
502     void UpdateSessionConnectionState(const int32_t &sessionID, const int32_t &state);
503     bool getFastControlParam();
504 
505     int32_t SetVoiceRingtoneMute(bool isMute);
506 
507     int32_t SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionID,
508         const StreamUsage streamUsage, bool isRunning);
509 
510     int32_t LoadSplitModule(const std::string &splitArgs, const std::string &networkId);
511 private:
AudioPolicyService()512     AudioPolicyService()
513         :audioPolicyManager_(AudioPolicyManagerFactory::GetAudioPolicyManager()),
514         audioPolicyConfigParser_(AudioPolicyParserFactory::GetInstance().CreateParser(*this)),
515         streamCollector_(AudioStreamCollector::GetAudioStreamCollector()),
516         audioRouterCenter_(AudioRouterCenter::GetAudioRouterCenter()),
517         audioEffectManager_(AudioEffectManager::GetAudioEffectManager()),
518         audioDeviceManager_(AudioDeviceManager::GetAudioDeviceManager()),
519         audioStateManager_(AudioStateManager::GetAudioStateManager()),
520         audioPolicyServerHandler_(DelayedSingleton<AudioPolicyServerHandler>::GetInstance()),
521         audioPnpServer_(AudioPnpServer::GetAudioPnpServer())
522     {
523 #ifdef ACCESSIBILITY_ENABLE
524         accessibilityConfigListener_ = std::make_shared<AccessibilityConfigListener>(*this);
525 #endif
526         deviceStatusListener_ = std::make_unique<DeviceStatusListener>(*this);
527     }
528 
529     ~AudioPolicyService();
530 
531     void UpdateDeviceInfo(DeviceInfo &deviceInfo, const sptr<AudioDeviceDescriptor> &desc, bool hasBTPermission,
532         bool hasSystemPermission);
533 
534     std::string GetSinkPortName(InternalDeviceType deviceType, AudioPipeType pipeType = PIPE_TYPE_UNKNOWN);
535 
536     std::string GetSourcePortName(InternalDeviceType deviceType);
537 
538     int32_t RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter,
539         sptr<AudioDeviceDescriptor> deviceDescriptor);
540 
541     int32_t MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,
542         sptr<AudioDeviceDescriptor> localDeviceDescriptor);
543 
544     std::vector<SinkInput> FilterSinkInputs(sptr<AudioRendererFilter> audioRendererFilter, bool moveAll);
545 
546     std::vector<SinkInput> FilterSinkInputs(int32_t sessionId);
547 
548     std::vector<SourceOutput> FilterSourceOutputs(int32_t sessionId);
549 
550     int32_t MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,
551         sptr<AudioDeviceDescriptor> remoteDeviceDescriptor);
552 
553     int32_t MoveToLocalInputDevice(std::vector<SourceOutput> sourceOutputIds,
554         sptr<AudioDeviceDescriptor> localDeviceDescriptor);
555 
556     int32_t MoveToRemoteInputDevice(std::vector<SourceOutput> sourceOutputIds,
557         sptr<AudioDeviceDescriptor> remoteDeviceDescriptor);
558 
559     AudioModuleInfo ConstructRemoteAudioModuleInfo(std::string networkId,
560         DeviceRole deviceRole, DeviceType deviceType);
561 
562     bool FillWakeupStreamPropInfo(const AudioStreamInfo &streamInfo, PipeInfo *pipeInfo,
563         AudioModuleInfo &audioModuleInfo);
564     bool ConstructWakeupAudioModuleInfo(const AudioStreamInfo &streamInfo, AudioModuleInfo &audioModuleInfo);
565 
566     AudioIOHandle GetSinkIOHandle(InternalDeviceType deviceType);
567 
568     AudioIOHandle GetSourceIOHandle(InternalDeviceType deviceType);
569 
570     int32_t OpenRemoteAudioDevice(std::string networkId, DeviceRole deviceRole, DeviceType deviceType,
571         sptr<AudioDeviceDescriptor> remoteDeviceDescriptor);
572 
573     InternalDeviceType GetDeviceType(const std::string &deviceName);
574 
575     std::string GetGroupName(const std::string& deviceName, const GroupType type);
576 
577     bool IsDeviceConnected(sptr<AudioDeviceDescriptor> &audioDeviceDescriptors) const;
578 
579     int32_t DeviceParamsCheck(DeviceRole targetRole,
580         std::vector<sptr<AudioDeviceDescriptor>> &audioDeviceDescriptors) const;
581 
582     DeviceRole GetDeviceRole(DeviceType deviceType) const;
583 
584     DeviceRole GetDeviceRole(const std::string &role);
585 
586     int32_t SwitchActiveA2dpDevice(const sptr<AudioDeviceDescriptor> &deviceDescriptor);
587 
588     int32_t HandleActiveDevice(DeviceType deviceType);
589 
590     int32_t LoadA2dpModule();
591 
592     int32_t LoadUsbModule(string deviceInfo, DeviceRole deviceRole);
593 
594     int32_t LoadDpModule(string deviceInfo);
595 
596     int32_t LoadDefaultUsbModule(DeviceRole deviceRole);
597 
598     int32_t RehandlePnpDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address);
599 
600     int32_t HandleArmUsbDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address);
601 
602     int32_t HandleDpDevice(DeviceType deviceType, const std::string &address);
603 
604     int32_t GetModuleInfo(ClassType classType, std::string &moduleInfoStr);
605 
606     void MoveToNewOutputDevice(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
607         vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices,
608         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
609 
610     void MoveToNewInputDevice(unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo,
611         unique_ptr<AudioDeviceDescriptor> &inputDevice);
612 
613     int32_t SetRenderDeviceForUsage(StreamUsage streamUsage, sptr<AudioDeviceDescriptor> desc);
614 
615     void SetCaptureDeviceForUsage(AudioScene scene, SourceType srcType, sptr<AudioDeviceDescriptor> desc);
616 
617     DeviceRole GetDeviceRole(AudioPin pin) const;
618 
619     void UnmutePortAfterMuteDuration(int32_t muteDuration, std::string portName, DeviceType deviceType);
620 
621     int32_t ActivateNewDevice(std::string networkId, DeviceType deviceType, bool isRemote);
622 
623     int32_t HandleScoOutputDeviceFetched(unique_ptr<AudioDeviceDescriptor> &desc,
624         vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
625         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
626 
627     void FetchOutputDevice(vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
628         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
629 
630     bool IsFastFromA2dpToA2dp(const std::unique_ptr<AudioDeviceDescriptor> &desc,
631         const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
632         const AudioStreamDeviceChangeReasonExt reason);
633 
634     void FetchStreamForA2dpMchStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
635         vector<std::unique_ptr<AudioDeviceDescriptor>> &descs);
636 
637     int32_t HandleScoInputDeviceFetched(unique_ptr<AudioDeviceDescriptor> &desc,
638         vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos);
639 
640     void FetchInputDevice(vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos,
641         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
642 
643     int32_t HandleDeviceChangeForFetchInputDevice(unique_ptr<AudioDeviceDescriptor> &desc,
644         unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo);
645 
646     void BluetoothScoFetch(unique_ptr<AudioDeviceDescriptor> &desc,
647         vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos, SourceType sourceType);
648 
649     void BluetoothScoDisconectForRecongnition();
650 
651     void FetchDevice(bool isOutputDevice = true,
652         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
653 
654     void UpdateConnectedDevicesWhenConnecting(const AudioDeviceDescriptor& updatedDesc,
655         std::vector<sptr<AudioDeviceDescriptor>>& descForCb);
656 
657     void UpdateConnectedDevicesWhenDisconnecting(const AudioDeviceDescriptor& updatedDesc,
658         std::vector<sptr<AudioDeviceDescriptor>> &descForCb);
659 
660     void TriggerDeviceChangedCallback(const std::vector<sptr<AudioDeviceDescriptor>> &devChangeDesc, bool connection);
661 
662     void GetAllRunningStreamSession(std::vector<int32_t> &allSessions, bool doStop = false);
663 
664     void WriteDeviceChangedSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected);
665 
666     void WriteOutDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> &deviceDescriptor,
667         const SinkInput &sinkInput);
668 
669     void WriteInDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> &deviceDescriptor,
670         const SourceOutput &sourceOutput);
671 
672     void WriteSelectOutputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &selectedDesc,
673     StreamUsage strUsage);
674 
675     void WriteSelectInputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &selectedDesc,
676         SourceType srcType, AudioScene scene);
677 
678     bool GetActiveDeviceStreamInfo(DeviceType deviceType, AudioStreamInfo &streamInfo);
679 
680     bool IsConfigurationUpdated(DeviceType deviceType, const AudioStreamInfo &streamInfo);
681 
682     void UpdateInputDeviceInfo(DeviceType deviceType);
683 
684     void UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> &desc);
685 
686     void UpdateGroupInfo(GroupType type, std::string groupName, int32_t& groupId, std::string networkId,
687         bool connected, int32_t mappingId);
688 
689     void AddAudioDevice(AudioModuleInfo& moduleInfo, InternalDeviceType devType);
690 
691     void OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor& deviceDescriptor);
692 
693     void OnPreferredInputDeviceUpdated(DeviceType deviceType, std::string networkId);
694 
695     void OnPreferredDeviceUpdated(const AudioDeviceDescriptor& deviceDescriptor, DeviceType activeInputDevice);
696 
697     std::vector<sptr<AudioDeviceDescriptor>> GetDevicesForGroup(GroupType type, int32_t groupId);
698 
699     void SetVolumeForSwitchDevice(DeviceType deviceType, const std::string &newSinkName = PORT_NONE);
700 
701     void UpdateVolumeForLowLatency();
702 
703     void SetVoiceCallVolume(int32_t volume);
704 
705     std::string GetVolumeGroupType(DeviceType deviceType);
706 
707     int32_t ReloadA2dpAudioPort(AudioModuleInfo &moduleInfo, const AudioStreamInfo& audioStreamInfo);
708 
709     void RemoveDeviceInRouterMap(std::string networkId);
710 
711     void RemoveDeviceInFastRouterMap(std::string networkId);
712 
713     void UpdateDisplayName(sptr<AudioDeviceDescriptor> deviceDescriptor);
714 
715     void RegisterRemoteDevStatusCallback();
716 
717     void UpdateLocalGroupInfo(bool isConnected, const std::string& macAddress,
718         const std::string& deviceName, const DeviceStreamInfo& streamInfo, AudioDeviceDescriptor& deviceDesc);
719 
720     int32_t HandleLocalDeviceConnected(AudioDeviceDescriptor &updatedDesc);
721 
722     int32_t HandleLocalDeviceDisconnected(const AudioDeviceDescriptor &updatedDesc);
723 
724     void UpdateActiveA2dpDeviceWhenDisconnecting(const std::string& macAddress);
725 
726     void UpdateEffectDefaultSink(DeviceType deviceType);
727 
728     void LoadSinksForCapturer();
729 
730     void LoadInnerCapturerSink(string moduleName, AudioStreamInfo streamInfo);
731 
732     DeviceType FindConnectedHeadset();
733 
734     std::shared_ptr<DataShare::DataShareHelper> CreateDataShareHelperInstance();
735 
736     void RegisterNameMonitorHelper();
737 
738     bool IsConnectedOutputDevice(const sptr<AudioDeviceDescriptor> &desc);
739 
740     void AddMicrophoneDescriptor(sptr<AudioDeviceDescriptor> &deviceDescriptor);
741 
742     void RemoveMicrophoneDescriptor(sptr<AudioDeviceDescriptor> &deviceDescriptor);
743 
744     void AddAudioCapturerMicrophoneDescriptor(int32_t sessionId, DeviceType devType);
745 
746     void UpdateAudioCapturerMicrophoneDescriptor(DeviceType devType);
747 
748     void RemoveAudioCapturerMicrophoneDescriptor(int32_t uid);
749 
750     void SetOffloadMode();
751 
752     void ResetOffloadMode(int32_t sessionId);
753 
754     bool GetOffloadAvailableFromXml() const;
755 
756     void SetOffloadAvailableFromXML(AudioModuleInfo &moduleInfo);
757 
758     bool CheckActiveOutputDeviceSupportOffload();
759 
760     bool OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo &moduleInfo);
761 
762     int32_t FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo, StreamPropInfo &targetInfo,
763         SourceType &targetSourceType);
764 
765     void StoreDistributedRoutingRoleInfo(const sptr<AudioDeviceDescriptor> descriptor, CastType type);
766 
767     void AddEarpiece();
768 
769     void FetchOutputDeviceWhenNoRunningStream();
770 
771     void FetchInputDeviceWhenNoRunningStream();
772 
773     void UpdateActiveDeviceRoute(InternalDeviceType deviceType, DeviceFlag deviceFlag);
774 
775     void UpdateActiveDevicesRoute(std::vector<std::pair<InternalDeviceType, DeviceFlag>> &activeDevices);
776 
777     void UpdateDualToneState(const bool &enable, const int32_t &sessionId);
778 
779     int32_t ActivateA2dpDevice(unique_ptr<AudioDeviceDescriptor> &desc,
780         vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
781         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
782 
783     int32_t ActivateA2dpDeviceWhenDescEnabled(unique_ptr<AudioDeviceDescriptor> &desc,
784         vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
785         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
786 
787     void ResetToSpeaker(DeviceType devType);
788 
789     void UpdateConnectedDevicesWhenConnectingForOutputDevice(const AudioDeviceDescriptor &updatedDesc,
790         std::vector<sptr<AudioDeviceDescriptor>> &descForCb);
791 
792     void UpdateConnectedDevicesWhenConnectingForInputDevice(const AudioDeviceDescriptor &updatedDesc,
793         std::vector<sptr<AudioDeviceDescriptor>> &descForCb);
794 
795     bool IsSameDevice(unique_ptr<AudioDeviceDescriptor> &desc, DeviceInfo &deviceInfo);
796 
797     bool IsSameDevice(unique_ptr<AudioDeviceDescriptor> &desc, const AudioDeviceDescriptor &deviceDesc);
798 
799     void UpdateOffloadWhenActiveDeviceSwitchFromA2dp();
800 
801     bool IsRendererStreamRunning(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo);
802 
803     bool NeedRehandleA2DPDevice(unique_ptr<AudioDeviceDescriptor> &desc);
804 
805     void MuteSinkPort(const std::string &portName, int32_t duration, bool isSync);
806 
807     void MuteSinkPort(const std::string &oldSinkname, const std::string &newSinkName,
808         AudioStreamDeviceChangeReasonExt reason);
809 
810     void MuteDefaultSinkPort();
811 
812     void SetVoiceCallMuteForSwitchDevice();
813 
814     void MuteSinkPortForSwtichDevice(unique_ptr<AudioRendererChangeInfo>& rendererChangeInfo,
815         vector<std::unique_ptr<AudioDeviceDescriptor>>& outputDevices, const AudioStreamDeviceChangeReasonExt reason);
816 
817     std::string GetSinkName(const DeviceInfo& desc, int32_t sessionId);
818 
819     std::string GetSinkName(const AudioDeviceDescriptor& desc, int32_t sessionId);
820 
821     void RectifyModuleInfo(AudioModuleInfo &moduleInfo, std::list<AudioModuleInfo> &moduleInfoList,
822         SourceInfo &targetInfo);
823 
824     void ClearScoDeviceSuspendState(string macAddress = "");
825 
826     PipeInfo& GetPipeInfoByPipeName(std::string &supportPipe, AudioAdapterInfo &adapterInfo);
827 
828     int32_t CheckDeviceCapability(AudioAdapterInfo &adapterInfo, int32_t flag, DeviceType deviceType);
829 
830     bool IsConfigInfoHasAttribute(std::list<ConfigInfo> &configInfos, std::string value);
831 
832     int32_t OpenPortAndInsertIOHandle(const std::string &moduleName, const AudioModuleInfo &moduleInfo);
833 
834     int32_t ClosePortAndEraseIOHandle(const std::string &moduleName);
835 
836     DeviceUsage GetDeviceUsage(const AudioDeviceDescriptor &desc);
837 
838     void UnloadInnerCapturerSink(string moduleName);
839 
840     void HandleRemoteCastDevice(bool isConnected, AudioStreamInfo streamInfo = {});
841 
842     int32_t HandleDeviceChangeForFetchOutputDevice(unique_ptr<AudioDeviceDescriptor> &desc,
843         unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo);
844 
845     bool IsWiredHeadSet(const DeviceType &deviceType);
846 
847     bool IsBlueTooth(const DeviceType &deviceType);
848 
849     int32_t DealWithSafeVolume(const int32_t volumeLevel, bool isA2dpDevice);
850 
851     void CreateCheckMusicActiveThread();
852 
853     void CreateSafeVolumeDialogThread();
854 
855     void SetDeviceSafeVolumeStatus();
856 
857     void CheckBlueToothActiveMusicTime(int32_t safeVolume);
858 
859     void CheckWiredActiveMusicTime(int32_t safeVolume);
860 
861     void RestoreSafeVolume(AudioStreamType streamType, int32_t safeVolume);
862 
863     int32_t CheckActiveMusicTime();
864 
865     int32_t ShowDialog();
866 
867     int32_t GetVoipDeviceInfo(const AudioProcessConfig &config, DeviceInfo &deviceInfo, int32_t type,
868         std::vector<sptr<AudioDeviceDescriptor>> &preferredDeviceList);
869 
870     int32_t GetPreferredOutputStreamTypeInner(StreamUsage streamUsage, DeviceType deviceType, int32_t flags,
871         std::string &networkId, AudioSamplingRate &samplingRate);
872 
873     int32_t GetPreferredInputStreamTypeInner(SourceType sourceType, DeviceType deviceType, int32_t flags,
874         const std::string &networkId, const AudioSamplingRate &samplingRate);
875 
876     int32_t GetPreferredInputStreamTypeFromDeviceInfo(AudioAdapterInfo &adapterInfo,
877         DeviceType deviceType, int32_t flags);
878 
879     bool NotifyRecreateRendererStream(std::unique_ptr<AudioDeviceDescriptor> &desc,
880         const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
881         const AudioStreamDeviceChangeReasonExt reason);
882 
883     void TriggerRecreateRendererStreamCallback(int32_t callerPid, int32_t sessionId, int32_t streamFlag,
884         const AudioStreamDeviceChangeReasonExt reason);
885 
886     bool NotifyRecreateDirectStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
887         const AudioStreamDeviceChangeReasonExt reason);
888 
889     bool IsDirectSupportedDevice(DeviceType deviceType);
890 
891     bool UpdateDevice(unique_ptr<AudioDeviceDescriptor> &desc, const AudioStreamDeviceChangeReasonExt reason,
892         const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo);
893 
894     bool NotifyRecreateCapturerStream(bool isUpdateActiveDevice,
895         const std::unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo,
896         const AudioStreamDeviceChangeReasonExt reason);
897 
898     void TriggerRecreateCapturerStreamCallback(int32_t callerPid, int32_t sessionId, int32_t streamFlag,
899         const AudioStreamDeviceChangeReasonExt reason);
900 
901     bool HasLowLatencyCapability(DeviceType deviceType, bool isRemote);
902 
903     int32_t HandleAbsBluetoothVolume(const std::string &macAddress, const int32_t volumeLevel);
904 
905     void WriteServiceStartupError(string reason);
906 
907     bool LoadToneDtmfConfig();
908 
909     void CreateRecoveryThread();
910     void RecoveryPreferredDevices();
911 
912     int32_t HandleRecoveryPreferredDevices(int32_t preferredType, int32_t deviceType,
913         int32_t usageOrSourceType);
914 
915     void WriteOutputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> &desc,
916         const AudioStreamDeviceChangeReason reason);
917     void WriteInputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> &desc,
918         const AudioStreamDeviceChangeReason reason);
919 
920     bool CheckStreamOffloadMode(int64_t activateSessionId, AudioStreamType streamType);
921     AudioModuleInfo ConstructOffloadAudioModuleInfo(DeviceType deviceType);
922     int32_t LoadOffloadModule();
923     int32_t UnloadOffloadModule();
924     int32_t MoveToOutputDevice(uint32_t sessionId, std::string portName);
925 
926     bool CheckStreamMultichannelMode(const int64_t activateSessionId);
927     AudioModuleInfo ConstructMchAudioModuleInfo(DeviceType deviceType);
928     int32_t LoadMchModule();
929     int32_t UnloadMchModule();
930 
931     int32_t MoveToNewPipeInner(const uint32_t sessionId, const AudioPipeType pipeType);
932 
933     void UpdateRoute(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
934         vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices);
935 
936     bool IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType &deviceType);
937 
938     bool SelectRingerOrAlarmDevices(const vector<std::unique_ptr<AudioDeviceDescriptor>> &descs,
939         const unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo);
940 
941     void DealAudioSceneOutputDevices(const AudioScene &audioScene, std::vector<DeviceType> &activeOutputDevices,
942         bool &haveArmUsbDevice);
943 
944     bool IsA2dpOrArmUsbDevice(const InternalDeviceType &deviceType);
945 
946     void UpdateAllUserSelectDevice(vector<unique_ptr<AudioDeviceDescriptor>> &userSelectDeviceMap,
947         AudioDeviceDescriptor &desc, const sptr<AudioDeviceDescriptor> &selectDesc);
948 
949     void SetAbsVolumeSceneAsync(const std::string &macAddress, const bool support);
950 
951     void SetSharedAbsVolumeScene(const bool support);
952 
953     void LoadHdiEffectModel();
954 
955     void UpdateEffectBtOffloadSupported(const bool &isSupported);
956 
957     int32_t ScoInputDeviceFetchedForRecongnition(bool handleFlag, const std::string &address,
958         ConnectState connectState);
959 
960     bool IsA2dpOffloadConnected();
961 
962     void SetCurrenInputDevice(const AudioDeviceDescriptor &desc);
963 
964     AudioDeviceDescriptor GetCurrentInputDevice();
965 
966     DeviceType GetCurrentInputDeviceType();
967 
968     void SetCurrentInputDeviceType(DeviceType deviceType);
969 
970     void SetCurrentOutputDevice(const AudioDeviceDescriptor &desc);
971 
972     void SetCurrentOutputDeviceType(DeviceType deviceType);
973 
974     AudioDeviceDescriptor GetCurrentOutputDevice();
975 
976     DeviceType GetCurrentOutputDeviceType();
977 
978     DeviceCategory GetCurrentOutputDeviceCategory();
979 
980     std::string GetCurrentOutputDeviceNetworkId();
981 
982     std::string GetCurrentOutputDeviceMacAddr();
983 
984     void SendA2dpConnectedWhileRunning(const RendererState &rendererState, const uint32_t &sessionId);
985 
986     int32_t ConnectVirtualDevice(sptr<AudioDeviceDescriptor> &desc);
987     void UpdateDeviceList(AudioDeviceDescriptor &updatedDesc, bool isConnected,
988         std::vector<sptr<AudioDeviceDescriptor>> &descForCb,
989         AudioStreamDeviceChangeReasonExt &reason);
990     void UpdateDefaultOutputDeviceWhenStopping(int32_t uid);
991 
992     void SetDefaultDeviceLoadFlag(bool isLoad);
993 
994     int32_t ErasePreferredDeviceByType(const PreferredType preferredType);
995 
996     void CheckAndNotifyUserSelectedDevice(const sptr<AudioDeviceDescriptor> &deviceDescriptor);
997 
998     bool GetAudioEffectOffloadFlag();
999     void ResetOffloadModeOnSpatializationChanged(std::vector<int32_t> &allSessions);
1000 
1001     bool CheckSpatializationAndEffectState();
1002 
1003     void FetchStreamForSpkMchStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
1004     vector<std::unique_ptr<AudioDeviceDescriptor>> &descs);
1005 
1006     void ResetOffloadAndMchMode(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
1007         vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices);
1008 
1009     void JudgeIfLoadMchModule();
1010 
1011     const sptr<IStandardAudioService> GetAudioServerProxy();
1012 
1013     int32_t SelectFastInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
1014         sptr<AudioDeviceDescriptor> deviceDescriptor);
1015 
1016     void GetAudioAdapterInfos(std::unordered_map<AdaptersType, AudioAdapterInfo> &adapterInfoMap);
1017 
1018     void GetVolumeGroupData(std::unordered_map<std::string, std::string>& volumeGroupData);
1019 
1020     void GetInterruptGroupData(std::unordered_map<std::string, std::string>& interruptGroupData);
1021 
1022     void GetDeviceClassInfo(std::unordered_map<ClassType, std::list<AudioModuleInfo>> &deviceClassInfo);
1023 
1024     void GetGlobalConfigs(GlobalConfigs &globalConfigs);
1025 
1026     int32_t HandleSpecialDeviceType(DeviceType &devType, bool &isConnected, const std::string &address);
1027 
1028     void ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType, const std::string &macAddress,
1029         const std::string &deviceName, const AudioStreamInfo &streamInfo);
1030 
1031     void HandleOfflineDistributedDevice();
1032 
1033     int32_t HandleDistributedDeviceUpdate(DStatusInfo &statusInfo,
1034         std::vector<sptr<AudioDeviceDescriptor>> &descForCb);
1035 
1036     void OnServiceConnected(AudioServiceIndex serviceIndex);
1037 
1038     void LoadModernInnerCapSink();
1039 
1040     void HandleAudioCaptureState(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo);
1041 
1042     AudioStreamType GetStreamType(int32_t sessionId);
1043 
1044     int32_t GetChannelCount(uint32_t sessionId);
1045 
1046     int32_t GetUid(int32_t sessionId);
1047 
1048     bool SetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume vol);
1049 
1050     void UnregisterBluetoothListener();
1051 
1052     void GetEffectManagerInfo();
1053 
1054     std::vector<unique_ptr<AudioDeviceDescriptor>> GetAvailableDevicesInner(AudioDeviceUsage usage);
1055 
1056     void UpdateA2dpOffloadFlagForAllStream(std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnableMap,
1057         DeviceType deviceType = DEVICE_TYPE_NONE);
1058 
1059     int32_t UpdateA2dpOffloadFlagForAllStream(DeviceType deviceType = DEVICE_TYPE_NONE);
1060 
1061     int32_t OffloadStartPlaying(const std::vector<int32_t> &sessionIds);
1062 
1063 #ifdef BLUETOOTH_ENABLE
1064     void UpdateA2dpOffloadFlag(const std::vector<Bluetooth::A2dpStreamInfo> &allActiveSessions,
1065         DeviceType deviceType = DEVICE_TYPE_NONE);
1066 
1067     void CheckAndActiveHfpDevice(AudioDeviceDescriptor &desc);
1068 #endif
1069 
1070     void OnPreferredStateUpdated(AudioDeviceDescriptor &desc,
1071         const DeviceInfoUpdateCommand updateCommand, AudioStreamDeviceChangeReasonExt &reason);
1072 
1073     void CheckForA2dpSuspend(AudioDeviceDescriptor &desc);
1074 
1075     void UnloadA2dpModule();
1076 
1077     std::vector<sptr<AudioDeviceDescriptor>> GetDumpDevices(DeviceFlag deviceFlag);
1078     std::vector<sptr<AudioDeviceDescriptor>> GetDumpDeviceInfo(std::string &dumpString, DeviceFlag deviceFlag);
1079     bool IsStreamSupported(AudioStreamType streamType);
1080     bool IsVoiceCallRelatedScene();
1081 private:
1082     bool isUpdateRouteSupported_ = true;
1083     bool isCurrentRemoteRenderer = false;
1084     bool remoteCapturerSwitch_ = false;
1085     bool isOpenRemoteDevice = false;
1086     static bool isBtListenerRegistered;
1087     bool isPnpDeviceConnected = false;
1088     bool hasModulesLoaded = false;
1089     bool hasEarpiece_ = false;
1090     const int32_t G_UNKNOWN_PID = -1;
1091     int32_t dAudioClientUid = 3055;
1092     int32_t maxRendererInstances_ = 128;
1093     uint64_t audioLatencyInMsec_ = 50;
1094     uint32_t sinkLatencyInMsec_ {0};
1095     bool isOffloadAvailable_ = false;
1096     bool enableFastVoip_ = false;
1097     bool enableDualHalToneState_ = false;
1098     int32_t enableDualHalToneSessionId_ = -1;
1099     int32_t shouldUpdateDeviceDueToDualTone_ = false;
1100     bool isFastControlled_ = false;
1101     bool isVoiceRingtoneMute_ = false;
1102 
1103     std::unordered_map<std::string, DeviceType> spatialDeviceMap_;
1104 
1105     BluetoothOffloadState a2dpOffloadFlag_ = NO_A2DP_DEVICE;
1106     std::mutex switchA2dpOffloadMutex_;
1107 
1108     std::bitset<MIN_SERVICE_COUNT> serviceFlag_;
1109     std::mutex serviceFlagMutex_;
1110     DeviceType effectActiveDevice_ = DEVICE_TYPE_NONE;
1111     std::mutex curOutputDevice_; // lock this mutex to operate currentActiveDevice_
1112     AudioDeviceDescriptor currentActiveDevice_ = AudioDeviceDescriptor(DEVICE_TYPE_NONE, DEVICE_ROLE_NONE);
1113     std::mutex curInputDevice_; // lock this mutex to operate currentActiveInputDevice_
1114     AudioDeviceDescriptor currentActiveInputDevice_ = AudioDeviceDescriptor(DEVICE_TYPE_NONE, DEVICE_ROLE_NONE);
1115     std::vector<std::pair<DeviceType, bool>> pnpDeviceList_;
1116 
1117     std::mutex routerMapMutex_; // unordered_map is not concurrently-secure
1118     mutable std::mutex a2dpDeviceMapMutex_;
1119     std::unordered_map<int32_t, std::pair<std::string, int32_t>> routerMap_;
1120     std::unordered_map<int32_t, std::pair<std::string, DeviceRole>> fastRouterMap_; // key:uid value:<netWorkId, Role>
1121     IAudioPolicyInterface& audioPolicyManager_;
1122     Parser& audioPolicyConfigParser_;
1123 #ifdef FEATURE_DTMF_TONE
1124     std::unordered_map<int32_t, std::shared_ptr<ToneInfo>> toneDescriptorMap;
1125 #endif
1126     AudioStreamCollector& streamCollector_;
1127     AudioRouterCenter& audioRouterCenter_;
1128 #ifdef ACCESSIBILITY_ENABLE
1129     std::shared_ptr<AccessibilityConfigListener> accessibilityConfigListener_;
1130 #endif
1131     std::unique_ptr<DeviceStatusListener> deviceStatusListener_;
1132     std::vector<sptr<AudioDeviceDescriptor>> connectedDevices_;
1133     std::vector<sptr<MicrophoneDescriptor>> connectedMicrophones_;
1134     std::unordered_map<int32_t, sptr<MicrophoneDescriptor>> audioCaptureMicrophoneDescriptor_;
1135     std::unordered_map<std::string, A2dpDeviceConfigInfo> connectedA2dpDeviceMap_;
1136     std::string activeBTDevice_;
1137 
1138     AudioScene audioScene_ = AUDIO_SCENE_DEFAULT;
1139     AudioScene lastAudioScene_ = AUDIO_SCENE_DEFAULT;
1140     std::unordered_map<ClassType, std::list<AudioModuleInfo>> deviceClassInfo_ = {};
1141     std::unordered_map<AdaptersType, AudioAdapterInfo> adapterInfoMap_ {};
1142 
1143     std::mutex ioHandlesMutex_;
1144     std::unordered_map<std::string, AudioIOHandle> IOHandles_ = {};
1145 
1146     std::shared_ptr<AudioSharedMemory> policyVolumeMap_ = nullptr;
1147     volatile Volume *volumeVector_ = nullptr;
1148     volatile bool *sharedAbsVolumeScene_ = nullptr;
1149 
1150     std::vector<DeviceType> outputPriorityList_ = {
1151         DEVICE_TYPE_BLUETOOTH_SCO,
1152         DEVICE_TYPE_BLUETOOTH_A2DP,
1153         DEVICE_TYPE_DP,
1154         DEVICE_TYPE_USB_HEADSET,
1155         DEVICE_TYPE_WIRED_HEADSET,
1156         DEVICE_TYPE_SPEAKER
1157     };
1158     std::vector<DeviceType> inputPriorityList_ = {
1159         DEVICE_TYPE_BLUETOOTH_SCO,
1160         DEVICE_TYPE_BLUETOOTH_A2DP,
1161         DEVICE_TYPE_USB_HEADSET,
1162         DEVICE_TYPE_WIRED_HEADSET,
1163         DEVICE_TYPE_WAKEUP,
1164         DEVICE_TYPE_MIC
1165     };
1166 
1167     std::vector<sptr<VolumeGroupInfo>> volumeGroups_;
1168     std::vector<sptr<InterruptGroupInfo>> interruptGroups_;
1169     std::unordered_map<std::string, std::string> volumeGroupData_;
1170     std::unordered_map<std::string, std::string> interruptGroupData_;
1171     GlobalConfigs globalConfigs_;
1172     AudioEffectManager& audioEffectManager_;
1173 
1174     bool isMicrophoneMuteTemporary_ = false;
1175 
1176     bool isMicrophoneMutePersistent_ = false;
1177 
1178     mutable std::shared_mutex deviceStatusUpdateSharedMutex_;
1179 
1180     bool hasArmUsbDevice_ = false;
1181     bool hasHifiUsbDevice_ = false; // Only the first usb device is supported now, hifi or arm.
1182     bool hasDpDevice_ = false; // Only the first dp device is supported.
1183 
1184     AudioDeviceManager &audioDeviceManager_;
1185     AudioStateManager &audioStateManager_;
1186     std::shared_ptr<AudioPolicyServerHandler> audioPolicyServerHandler_;
1187     AudioPnpServer &audioPnpServer_;
1188 
1189     std::optional<uint32_t> offloadSessionID_;
1190     PowerMgr::PowerState currentPowerState_ = PowerMgr::PowerState::AWAKE;
1191     bool currentOffloadSessionIsBackground_ = false;
1192     std::mutex offloadMutex_;
1193 
1194     AudioModuleInfo primaryMicModuleInfo_ = {};
1195     std::mutex defaultDeviceLoadMutex_;
1196     std::condition_variable loadDefaultDeviceCV_;
1197     std::atomic<bool> isPrimaryMicModuleInfoLoaded_ = false;
1198     std::atomic<bool> isAdapterInfoMap_ = false;
1199 
1200     std::mutex moveDeviceMutex_;
1201     std::condition_variable moveDeviceCV_;
1202     std::atomic<bool> moveDeviceFinished_ = false;
1203 
1204     std::unordered_map<uint32_t, SessionInfo> sessionWithNormalSourceType_;
1205 
1206     DistributedRoutingInfo distributedRoutingInfo_ = {
1207         .descriptor = nullptr,
1208         .type = CAST_TYPE_NULL
1209     };
1210 
1211     // sourceType is SOURCE_TYPE_PLAYBACK_CAPTURE, SOURCE_TYPE_WAKEUP or SOURCE_TYPE_VIRTUAL_CAPTURE
1212     std::unordered_map<uint32_t, SessionInfo> sessionWithSpecialSourceType_;
1213 
1214     static std::map<std::string, std::string> sinkPortStrToClassStrMap_;
1215     static std::map<std::string, uint32_t> formatStrToEnum;
1216     static std::map<std::string, ClassType> classStrToEnum;
1217 
1218     std::unordered_set<uint32_t> sessionIdisRemovedSet_;
1219 
1220     SourceType currentSourceType = SOURCE_TYPE_MIC;
1221     uint32_t currentRate = 0;
1222 
1223     bool updateA2dpOffloadLogFlag = false;
1224     std::mutex checkSpatializedMutex_;
1225     SafeStatus safeStatusBt_ = SAFE_UNKNOWN;
1226     SafeStatus safeStatus_ = SAFE_UNKNOWN;
1227     int64_t activeSafeTimeBt_ = 0;
1228     int64_t activeSafeTime_ = 0;
1229     std::time_t startSafeTimeBt_ = 0;
1230     std::time_t startSafeTime_ = 0;
1231     bool userSelect_ = false;
1232     std::unique_ptr<std::thread> calculateLoopSafeTime_ = nullptr;
1233     std::mutex checkMusicActiveThreadMutex_; // lock calculateLoopSafeTime_
1234     bool safeVolumeExit_ = false;
1235     bool isAbsBtFirstBoot_ = true;
1236     bool normalVoipFlag_ = false;
1237 
1238     std::mutex dialogMutex_;
1239     std::atomic<bool> isDialogSelectDestroy_ = false;
1240     std::condition_variable dialogSelectCondition_;
1241 
1242     std::unique_ptr<std::thread> safeVolumeDialogThrd_ = nullptr;
1243     std::atomic<bool> isSafeVolumeDialogShowing_ = false;
1244     std::mutex safeVolumeMutex_;
1245 
1246     DeviceType priorityOutputDevice_ = DEVICE_TYPE_INVALID;
1247     DeviceType priorityInputDevice_ = DEVICE_TYPE_INVALID;
1248     ConnectType conneceType_ = CONNECT_TYPE_LOCAL;
1249 
1250     SupportedEffectConfig supportedEffectConfig_;
1251     ConverterConfig converterConfig_;
1252 
1253     std::unique_ptr<std::thread> RecoveryDevicesThread_ = nullptr;
1254 
1255     std::mutex offloadCloseMutex_;
1256     std::mutex offloadOpenMutex_;
1257     std::atomic<bool> isOffloadOpened_ = false;
1258     std::condition_variable offloadCloseCondition_;
1259 
1260     std::mutex ringerModeMuteMutex_;
1261     std::atomic<bool> ringerModeMute_ = true;
1262     std::condition_variable ringerModeMuteCondition_;
1263     std::atomic<bool> isPolicyConfigParsered_ = false;
1264     std::shared_ptr<AudioA2dpOffloadManager> audioA2dpOffloadManager_ = nullptr;
1265 
1266     bool isBTReconnecting_ = false;
1267 };
1268 
1269 class AudioA2dpOffloadManager final : public Bluetooth::AudioA2dpPlayingStateChangedListener,
1270     public enable_shared_from_this<AudioA2dpOffloadManager> {
1271 public:
AudioA2dpOffloadManager(AudioPolicyService * audioPolicyService)1272     AudioA2dpOffloadManager(AudioPolicyService *audioPolicyService) : audioPolicyService_(audioPolicyService) {};
Init()1273     void Init() {Bluetooth::AudioA2dpManager::RegisterA2dpPlayingStateChangedListener(shared_from_this());};
GetA2dOffloadConnectionState()1274     A2dpOffloadConnectionState GetA2dOffloadConnectionState() {return currentOffloadConnectionState_;};
1275 
1276     void ConnectA2dpOffload(const std::string &deviceAddress, const vector<int32_t> &sessionIds);
1277     void OnA2dpPlayingStateChanged(const std::string &deviceAddress, int32_t playingState) override;
1278 
1279     void WaitForConnectionCompleted();
1280     bool IsA2dpOffloadConnecting(int32_t sessionId);
1281 private:
1282     A2dpOffloadConnectionState currentOffloadConnectionState_ = CONNECTION_STATUS_DISCONNECTED;
1283     std::vector<int32_t> connectionTriggerSessionIds_;
1284     std::string a2dpOffloadDeviceAddress_ = "";
1285     AudioPolicyService *audioPolicyService_ = nullptr;
1286     std::mutex connectionMutex_;
1287     std::condition_variable connectionCV_;
1288     static const int32_t CONNECTION_TIMEOUT_IN_MS = 1000; // 1000ms
1289 };
1290 } // namespace AudioStandard
1291 } // namespace OHOS
1292 
1293 #endif // ST_AUDIO_POLICY_SERVICE_H
1294