• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_service.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, AudioDeviceDescriptor &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 GetHardwareOutputSamplingRate(const sptr<AudioDeviceDescriptor> &desc);
381 
382     vector<sptr<MicrophoneDescriptor>> GetAudioCapturerMicrophoneDescriptors(int32_t sessionId);
383 
384     vector<sptr<MicrophoneDescriptor>> GetAvailableMicrophones();
385 
386     int32_t SetDeviceAbsVolumeSupported(const std::string &macAddress, const bool support);
387 
388     bool IsAbsVolumeScene() const;
389 
390     bool IsVgsVolumeSupported() const;
391 
392     int32_t SetA2dpDeviceVolume(const std::string &macAddress, const int32_t volume, bool internalCall = false);
393 
394     int32_t OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo, AudioStreamInfo streamInfo);
395 
396     void OnCapturerSessionRemoved(uint64_t sessionID);
397 
398     std::vector<unique_ptr<AudioDeviceDescriptor>> GetAvailableDevices(AudioDeviceUsage usage);
399 
400     void TriggerAvailableDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected);
401 
402     void OffloadStreamSetCheck(uint32_t sessionId);
403 
404     void OffloadStreamReleaseCheck(uint32_t sessionId);
405 
406     void RemoteOffloadStreamRelease(uint32_t sessionId);
407 
408     int32_t OffloadStopPlaying(const std::vector<int32_t> &sessionIds);
409 
410     int32_t OffloadGetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp);
411 
412     int32_t GetAndSaveClientType(uint32_t uid, const std::string &bundleName);
413 
414     void GetA2dpOffloadCodecAndSendToDsp();
415 
416     int32_t HandleA2dpDeviceInOffload(BluetoothOffloadState a2dpOffloadFlag);
417 
418     int32_t HandleA2dpDeviceOutOffload(BluetoothOffloadState a2dpOffloadFlag);
419 
420     void ConfigDistributedRoutingRole(const sptr<AudioDeviceDescriptor> descriptor, CastType type);
421 
422     DistributedRoutingInfo GetDistributedRoutingRoleInfo();
423 
424     void OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command);
425 
426     void DeviceUpdateClearRecongnitionStatus(AudioDeviceDescriptor &desc);
427 
428     void UpdateA2dpOffloadFlagBySpatialService(
429         const std::string& macAddress, std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnableMap);
430 
431     std::vector<sptr<AudioDeviceDescriptor>> DeviceFilterByUsageInner(AudioDeviceUsage usage,
432         const std::vector<sptr<AudioDeviceDescriptor>>& descs);
433 
434     int32_t SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address);
435 
436     std::unique_ptr<AudioDeviceDescriptor> GetActiveBluetoothDevice();
437 
438     ConverterConfig GetConverterConfig();
439 
440     void FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo,
441         const AudioStreamDeviceChangeReasonExt reason);
442 
443     void FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo);
444 
445     float GetMaxAmplitude(const int32_t deviceId);
446 
447     int32_t TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
448 
449     int32_t DisableSafeMediaVolume();
450 
451     int32_t SafeVolumeDialogDisapper();
452 
453     void NotifyAccountsChanged(const int &id);
454 
455     int32_t ActivateConcurrencyFromServer(AudioPipeType incomingPipe);
456 
457     // for hidump
458     void DevicesInfoDump(std::string &dumpString);
459     void AudioModeDump(std::string &dumpString);
460     void AudioPolicyParserDump(std::string &dumpString);
461     void XmlParsedDataMapDump(std::string &dumpString);
462     void StreamVolumesDump(std::string &dumpString);
463     void DeviceVolumeInfosDump(std::string &dumpString, DeviceVolumeInfoMap &deviceVolumeInfos);
464     void AudioStreamDump(std::string &dumpString);
465     void GetVolumeConfigDump(std::string &dumpString);
466     void GetGroupInfoDump(std::string &dumpString);
467     void GetCallStatusDump(std::string &dumpString);
468     void GetRingerModeDump(std::string &dumpString);
469     void GetMicrophoneDescriptorsDump(std::string &dumpString);
470     void GetCapturerStreamDump(std::string &dumpString);
471     void GetSafeVolumeDump(std::string &dumpString);
472     void GetOffloadStatusDump(std::string &dumpString);
473     void EffectManagerInfoDump(std::string &dumpString);
474     void MicrophoneMuteInfoDump(std::string &dumpString);
475 
476     int32_t GetCurActivateCount();
477     void CheckStreamMode(const int64_t activateSessionId);
478 
479     int32_t MoveToNewPipe(const uint32_t sessionId, const AudioPipeType pipeType);
480     int32_t DynamicUnloadModule(const AudioPipeType pipeType);
481 
482     int32_t SetAudioConcurrencyCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object);
483 
484     int32_t UnsetAudioConcurrencyCallback(const uint32_t sessionID);
485 
486     int32_t ActivateAudioConcurrency(const AudioPipeType &pipeType);
487 
488     void OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName);
489 
490     int32_t ResetRingerModeMute();
491 
492     bool IsRingerModeMute();
493 
494     // for effect V3
495     int32_t GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray);
496     int32_t SetAudioEffectProperty(const AudioEffectPropertyArrayV3 &propertyArray);
497     int32_t GetAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray);
498 
499     AudioScene GetLastAudioScene() const;
500 
501     void SetRotationToEffect(const uint32_t rotate);
502     void FetchStreamForA2dpOffload(const bool &requireReset);
503     void UpdateSessionConnectionState(const int32_t &sessionID, const int32_t &state);
504     bool getFastControlParam();
505 
506     int32_t SetVoiceRingtoneMute(bool isMute);
507 
508     int32_t SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionID,
509         const StreamUsage streamUsage, bool isRunning);
510 
511     int32_t LoadSplitModule(const std::string &splitArgs, const std::string &networkId);
512 private:
AudioPolicyService()513     AudioPolicyService()
514         :audioPolicyManager_(AudioPolicyManagerFactory::GetAudioPolicyManager()),
515         audioPolicyConfigParser_(AudioPolicyParserFactory::GetInstance().CreateParser(*this)),
516         streamCollector_(AudioStreamCollector::GetAudioStreamCollector()),
517         audioRouterCenter_(AudioRouterCenter::GetAudioRouterCenter()),
518         audioEffectService_(AudioEffectService::GetAudioEffectService()),
519         audioDeviceManager_(AudioDeviceManager::GetAudioDeviceManager()),
520         audioStateManager_(AudioStateManager::GetAudioStateManager()),
521         audioPolicyServerHandler_(DelayedSingleton<AudioPolicyServerHandler>::GetInstance()),
522         audioPnpServer_(AudioPnpServer::GetAudioPnpServer())
523     {
524 #ifdef ACCESSIBILITY_ENABLE
525         accessibilityConfigListener_ = std::make_shared<AccessibilityConfigListener>(*this);
526 #endif
527         deviceStatusListener_ = std::make_unique<DeviceStatusListener>(*this);
528     }
529 
530     ~AudioPolicyService();
531 
532     void UpdateDeviceInfo(AudioDeviceDescriptor &deviceInfo, const sptr<AudioDeviceDescriptor> &desc,
533         bool hasBTPermission, bool hasSystemPermission);
534 
535     std::string GetSinkPortName(InternalDeviceType deviceType, AudioPipeType pipeType = PIPE_TYPE_UNKNOWN);
536 
537     std::string GetSourcePortName(InternalDeviceType deviceType);
538 
539     int32_t RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter,
540         sptr<AudioDeviceDescriptor> deviceDescriptor);
541 
542     int32_t MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,
543         sptr<AudioDeviceDescriptor> localDeviceDescriptor);
544 
545     std::vector<SinkInput> FilterSinkInputs(sptr<AudioRendererFilter> audioRendererFilter, bool moveAll);
546 
547     std::vector<SinkInput> FilterSinkInputs(int32_t sessionId);
548 
549     std::vector<SourceOutput> FilterSourceOutputs(int32_t sessionId);
550 
551     int32_t MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,
552         sptr<AudioDeviceDescriptor> remoteDeviceDescriptor);
553 
554     int32_t MoveToLocalInputDevice(std::vector<SourceOutput> sourceOutputIds,
555         sptr<AudioDeviceDescriptor> localDeviceDescriptor);
556 
557     int32_t MoveToRemoteInputDevice(std::vector<SourceOutput> sourceOutputIds,
558         sptr<AudioDeviceDescriptor> remoteDeviceDescriptor);
559 
560     AudioModuleInfo ConstructRemoteAudioModuleInfo(std::string networkId,
561         DeviceRole deviceRole, DeviceType deviceType);
562 
563     bool FillWakeupStreamPropInfo(const AudioStreamInfo &streamInfo, PipeInfo *pipeInfo,
564         AudioModuleInfo &audioModuleInfo);
565     bool ConstructWakeupAudioModuleInfo(const AudioStreamInfo &streamInfo, AudioModuleInfo &audioModuleInfo);
566 
567     AudioIOHandle GetSinkIOHandle(InternalDeviceType deviceType);
568 
569     AudioIOHandle GetSourceIOHandle(InternalDeviceType deviceType);
570 
571     int32_t OpenRemoteAudioDevice(std::string networkId, DeviceRole deviceRole, DeviceType deviceType,
572         sptr<AudioDeviceDescriptor> remoteDeviceDescriptor);
573 
574     InternalDeviceType GetDeviceType(const std::string &deviceName);
575 
576     std::string GetGroupName(const std::string& deviceName, const GroupType type);
577 
578     bool IsDeviceConnected(sptr<AudioDeviceDescriptor> &audioDeviceDescriptors) const;
579 
580     int32_t DeviceParamsCheck(DeviceRole targetRole,
581         std::vector<sptr<AudioDeviceDescriptor>> &audioDeviceDescriptors) const;
582 
583     DeviceRole GetDeviceRole(DeviceType deviceType) const;
584 
585     DeviceRole GetDeviceRole(const std::string &role);
586 
587     int32_t SwitchActiveA2dpDevice(const sptr<AudioDeviceDescriptor> &deviceDescriptor);
588 
589     int32_t HandleActiveDevice(DeviceType deviceType);
590 
591     int32_t LoadA2dpModule();
592 
593     int32_t LoadUsbModule(string deviceInfo, DeviceRole deviceRole);
594 
595     int32_t LoadDpModule(string deviceInfo);
596 
597     int32_t LoadDefaultUsbModule(DeviceRole deviceRole);
598 
599     int32_t RehandlePnpDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address);
600 
601     int32_t HandleArmUsbDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address);
602 
603     int32_t HandleDpDevice(DeviceType deviceType, const std::string &address);
604 
605     int32_t GetModuleInfo(ClassType classType, std::string &moduleInfoStr);
606 
607     void MoveToNewOutputDevice(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
608         vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices,
609         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
610 
611     void MoveToNewInputDevice(unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo,
612         unique_ptr<AudioDeviceDescriptor> &inputDevice);
613 
614     int32_t SetRenderDeviceForUsage(StreamUsage streamUsage, sptr<AudioDeviceDescriptor> desc);
615 
616     void SetCaptureDeviceForUsage(AudioScene scene, SourceType srcType, sptr<AudioDeviceDescriptor> desc);
617 
618     DeviceRole GetDeviceRole(AudioPin pin) const;
619 
620     void UnmutePortAfterMuteDuration(int32_t muteDuration, std::string portName, DeviceType deviceType);
621 
622     int32_t ActivateNewDevice(std::string networkId, DeviceType deviceType, bool isRemote);
623 
624     int32_t HandleScoOutputDeviceFetched(unique_ptr<AudioDeviceDescriptor> &desc,
625         vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
626         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
627 
628     void FetchOutputDevice(vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
629         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
630 
631     bool IsFastFromA2dpToA2dp(const std::unique_ptr<AudioDeviceDescriptor> &desc,
632         const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
633         const AudioStreamDeviceChangeReasonExt reason);
634 
635     void FetchStreamForA2dpMchStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
636         vector<std::unique_ptr<AudioDeviceDescriptor>> &descs);
637 
638     int32_t HandleScoInputDeviceFetched(unique_ptr<AudioDeviceDescriptor> &desc,
639         vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos);
640 
641     void FetchInputDevice(vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos,
642         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
643 
644     int32_t HandleDeviceChangeForFetchInputDevice(unique_ptr<AudioDeviceDescriptor> &desc,
645         unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo);
646 
647     void BluetoothScoFetch(unique_ptr<AudioDeviceDescriptor> &desc,
648         vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos, SourceType sourceType);
649 
650     void BluetoothScoDisconectForRecongnition();
651 
652     void FetchDevice(bool isOutputDevice = true,
653         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
654 
655     void UpdateConnectedDevicesWhenConnecting(const AudioDeviceDescriptor& updatedDesc,
656         std::vector<sptr<AudioDeviceDescriptor>>& descForCb);
657 
658     void UpdateConnectedDevicesWhenDisconnecting(const AudioDeviceDescriptor& updatedDesc,
659         std::vector<sptr<AudioDeviceDescriptor>> &descForCb);
660 
661     void TriggerDeviceChangedCallback(const std::vector<sptr<AudioDeviceDescriptor>> &devChangeDesc, bool connection);
662 
663     void GetAllRunningStreamSession(std::vector<int32_t> &allSessions, bool doStop = false);
664 
665     void WriteDeviceChangedSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected);
666 
667     void WriteOutDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> &deviceDescriptor,
668         const SinkInput &sinkInput);
669 
670     void WriteInDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> &deviceDescriptor,
671         const SourceOutput &sourceOutput);
672 
673     void WriteSelectOutputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &selectedDesc,
674     StreamUsage strUsage);
675 
676     void WriteSelectInputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &selectedDesc,
677         SourceType srcType, AudioScene scene);
678 
679     bool GetActiveDeviceStreamInfo(DeviceType deviceType, AudioStreamInfo &streamInfo);
680 
681     bool IsConfigurationUpdated(DeviceType deviceType, const AudioStreamInfo &streamInfo);
682 
683     void UpdateInputDeviceInfo(DeviceType deviceType);
684 
685     void UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> &desc);
686 
687     void UpdateGroupInfo(GroupType type, std::string groupName, int32_t& groupId, std::string networkId,
688         bool connected, int32_t mappingId);
689 
690     void AddAudioDevice(AudioModuleInfo& moduleInfo, InternalDeviceType devType);
691 
692     void OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor& deviceDescriptor);
693 
694     void OnPreferredInputDeviceUpdated(DeviceType deviceType, std::string networkId);
695 
696     void OnPreferredDeviceUpdated(const AudioDeviceDescriptor& deviceDescriptor, DeviceType activeInputDevice);
697 
698     std::vector<sptr<AudioDeviceDescriptor>> GetDevicesForGroup(GroupType type, int32_t groupId);
699 
700     void SetVolumeForSwitchDevice(DeviceType deviceType, const std::string &newSinkName = PORT_NONE);
701 
702     void UpdateVolumeForLowLatency();
703 
704     void SetVoiceCallVolume(int32_t volume);
705 
706     std::string GetVolumeGroupType(DeviceType deviceType);
707 
708     int32_t ReloadA2dpAudioPort(AudioModuleInfo &moduleInfo, const AudioStreamInfo& audioStreamInfo);
709 
710     void RemoveDeviceInRouterMap(std::string networkId);
711 
712     void RemoveDeviceInFastRouterMap(std::string networkId);
713 
714     void UpdateDisplayName(sptr<AudioDeviceDescriptor> deviceDescriptor);
715 
716     void RegisterRemoteDevStatusCallback();
717 
718     void UpdateLocalGroupInfo(bool isConnected, const std::string& macAddress,
719         const std::string& deviceName, const DeviceStreamInfo& streamInfo, AudioDeviceDescriptor& deviceDesc);
720 
721     int32_t HandleLocalDeviceConnected(AudioDeviceDescriptor &updatedDesc);
722 
723     int32_t HandleLocalDeviceDisconnected(const AudioDeviceDescriptor &updatedDesc);
724 
725     void UpdateActiveA2dpDeviceWhenDisconnecting(const std::string& macAddress);
726 
727     void UpdateEffectDefaultSink(DeviceType deviceType);
728 
729     void LoadSinksForCapturer();
730 
731     void LoadInnerCapturerSink(string moduleName, AudioStreamInfo streamInfo);
732 
733     DeviceType FindConnectedHeadset();
734 
735     std::shared_ptr<DataShare::DataShareHelper> CreateDataShareHelperInstance();
736 
737     void RegisterNameMonitorHelper();
738 
739     bool IsConnectedOutputDevice(const sptr<AudioDeviceDescriptor> &desc);
740 
741     void AddMicrophoneDescriptor(sptr<AudioDeviceDescriptor> &deviceDescriptor);
742 
743     void RemoveMicrophoneDescriptor(sptr<AudioDeviceDescriptor> &deviceDescriptor);
744 
745     void AddAudioCapturerMicrophoneDescriptor(int32_t sessionId, DeviceType devType);
746 
747     void UpdateAudioCapturerMicrophoneDescriptor(DeviceType devType);
748 
749     void RemoveAudioCapturerMicrophoneDescriptor(int32_t uid);
750 
751     void SetOffloadMode();
752 
753     void ResetOffloadMode(int32_t sessionId);
754 
755     bool GetOffloadAvailableFromXml() const;
756 
757     void SetOffloadAvailableFromXML(AudioModuleInfo &moduleInfo);
758 
759     bool CheckActiveOutputDeviceSupportOffload();
760 
761     bool OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo &moduleInfo);
762 
763     int32_t FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo, StreamPropInfo &targetInfo,
764         SourceType &targetSourceType);
765 
766     void StoreDistributedRoutingRoleInfo(const sptr<AudioDeviceDescriptor> descriptor, CastType type);
767 
768     void AddEarpiece();
769 
770     void FetchOutputDeviceWhenNoRunningStream();
771 
772     void FetchInputDeviceWhenNoRunningStream();
773 
774     void UpdateActiveDeviceRoute(InternalDeviceType deviceType, DeviceFlag deviceFlag);
775 
776     void UpdateActiveDevicesRoute(std::vector<std::pair<InternalDeviceType, DeviceFlag>> &activeDevices);
777 
778     void UpdateDualToneState(const bool &enable, const int32_t &sessionId);
779 
780     int32_t ActivateA2dpDevice(unique_ptr<AudioDeviceDescriptor> &desc,
781         vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
782         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
783 
784     int32_t ActivateA2dpDeviceWhenDescEnabled(unique_ptr<AudioDeviceDescriptor> &desc,
785         vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos,
786         const AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN);
787 
788     void ResetToSpeaker(DeviceType devType);
789 
790     void UpdateConnectedDevicesWhenConnectingForOutputDevice(const AudioDeviceDescriptor &updatedDesc,
791         std::vector<sptr<AudioDeviceDescriptor>> &descForCb);
792 
793     void UpdateConnectedDevicesWhenConnectingForInputDevice(const AudioDeviceDescriptor &updatedDesc,
794         std::vector<sptr<AudioDeviceDescriptor>> &descForCb);
795 
796     bool IsSameDevice(unique_ptr<AudioDeviceDescriptor> &desc, AudioDeviceDescriptor &deviceInfo);
797 
798     bool IsSameDevice(unique_ptr<AudioDeviceDescriptor> &desc, const AudioDeviceDescriptor &deviceDesc);
799 
800     void UpdateOffloadWhenActiveDeviceSwitchFromA2dp();
801 
802     bool IsRendererStreamRunning(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo);
803 
804     bool NeedRehandleA2DPDevice(unique_ptr<AudioDeviceDescriptor> &desc);
805 
806     void MuteSinkPort(const std::string &portName, int32_t duration, bool isSync);
807 
808     void MutePrimaryOrOffloadSink(const std::string &sinkName, int64_t muteTime);
809 
810     void MuteSinkPort(const std::string &oldSinkName, const std::string &newSinkName,
811         AudioStreamDeviceChangeReasonExt reason);
812 
813     void MuteDefaultSinkPort();
814 
815     void SetVoiceCallMuteForSwitchDevice();
816 
817     void MuteSinkPortForSwtichDevice(unique_ptr<AudioRendererChangeInfo>& rendererChangeInfo,
818         vector<std::unique_ptr<AudioDeviceDescriptor>>& outputDevices, const AudioStreamDeviceChangeReasonExt reason);
819 
820     std::string GetSinkName(const AudioDeviceDescriptor& desc, int32_t sessionId);
821 
822     void RectifyModuleInfo(AudioModuleInfo &moduleInfo, std::list<AudioModuleInfo> &moduleInfoList,
823         SourceInfo &targetInfo);
824 
825     void ClearScoDeviceSuspendState(string macAddress = "");
826 
827     PipeInfo& GetPipeInfoByPipeName(std::string &supportPipe, AudioAdapterInfo &adapterInfo);
828 
829     int32_t CheckDeviceCapability(AudioAdapterInfo &adapterInfo, int32_t flag, DeviceType deviceType);
830 
831     bool IsConfigInfoHasAttribute(std::list<ConfigInfo> &configInfos, std::string value);
832 
833     int32_t OpenPortAndInsertIOHandle(const std::string &moduleName, const AudioModuleInfo &moduleInfo);
834 
835     int32_t ClosePortAndEraseIOHandle(const std::string &moduleName);
836 
837     DeviceUsage GetDeviceUsage(const AudioDeviceDescriptor &desc);
838 
839     void UnloadInnerCapturerSink(string moduleName);
840 
841     void HandleRemoteCastDevice(bool isConnected, AudioStreamInfo streamInfo = {});
842 
843     int32_t HandleDeviceChangeForFetchOutputDevice(unique_ptr<AudioDeviceDescriptor> &desc,
844         unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo);
845 
846     bool IsWiredHeadSet(const DeviceType &deviceType);
847 
848     bool IsBlueTooth(const DeviceType &deviceType);
849 
850     int32_t DealWithSafeVolume(const int32_t volumeLevel, bool isA2dpDevice);
851 
852     void CreateCheckMusicActiveThread();
853 
854     void CreateSafeVolumeDialogThread();
855 
856     void SetDeviceSafeVolumeStatus();
857 
858     void CheckBlueToothActiveMusicTime(int32_t safeVolume);
859 
860     void CheckWiredActiveMusicTime(int32_t safeVolume);
861 
862     void RestoreSafeVolume(AudioStreamType streamType, int32_t safeVolume);
863 
864     int32_t CheckActiveMusicTime();
865 
866     int32_t ShowDialog();
867 
868     int32_t GetVoipDeviceInfo(const AudioProcessConfig &config, AudioDeviceDescriptor &deviceInfo, int32_t type,
869         std::vector<sptr<AudioDeviceDescriptor>> &preferredDeviceList);
870 
871     int32_t GetPreferredOutputStreamTypeInner(StreamUsage streamUsage, DeviceType deviceType, int32_t flags,
872         std::string &networkId, AudioSamplingRate &samplingRate);
873 
874     int32_t GetPreferredInputStreamTypeInner(SourceType sourceType, DeviceType deviceType, int32_t flags,
875         const std::string &networkId, const AudioSamplingRate &samplingRate);
876 
877     int32_t GetPreferredInputStreamTypeFromDeviceInfo(AudioAdapterInfo &adapterInfo,
878         DeviceType deviceType, int32_t flags);
879 
880     bool NotifyRecreateRendererStream(std::unique_ptr<AudioDeviceDescriptor> &desc,
881         const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
882         const AudioStreamDeviceChangeReasonExt reason);
883 
884     void TriggerRecreateRendererStreamCallback(int32_t callerPid, int32_t sessionId, int32_t streamFlag,
885         const AudioStreamDeviceChangeReasonExt reason);
886 
887     bool NotifyRecreateDirectStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
888         const AudioStreamDeviceChangeReasonExt reason);
889 
890     bool IsDirectSupportedDevice(DeviceType deviceType);
891 
892     bool UpdateDevice(unique_ptr<AudioDeviceDescriptor> &desc, const AudioStreamDeviceChangeReasonExt reason,
893         const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo);
894 
895     bool NotifyRecreateCapturerStream(bool isUpdateActiveDevice,
896         const std::unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo,
897         const AudioStreamDeviceChangeReasonExt reason);
898 
899     void TriggerRecreateCapturerStreamCallback(int32_t callerPid, int32_t sessionId, int32_t streamFlag,
900         const AudioStreamDeviceChangeReasonExt reason);
901 
902     bool HasLowLatencyCapability(DeviceType deviceType, bool isRemote);
903 
904     int32_t HandleAbsBluetoothVolume(const std::string &macAddress, const int32_t volumeLevel);
905 
906     void WriteServiceStartupError(string reason);
907 
908     bool LoadToneDtmfConfig();
909 
910     void CreateRecoveryThread();
911     void RecoveryPreferredDevices();
912 
913     int32_t HandleRecoveryPreferredDevices(int32_t preferredType, int32_t deviceType,
914         int32_t usageOrSourceType);
915 
916     void WriteOutputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> &desc,
917         const AudioStreamDeviceChangeReason reason);
918     void WriteInputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> &desc,
919         const AudioStreamDeviceChangeReason reason);
920 
921     bool CheckStreamOffloadMode(int64_t activateSessionId, AudioStreamType streamType);
922     AudioModuleInfo ConstructOffloadAudioModuleInfo(DeviceType deviceType);
923     int32_t LoadOffloadModule();
924     int32_t UnloadOffloadModule();
925     int32_t MoveToOutputDevice(uint32_t sessionId, std::string portName);
926 
927     bool CheckStreamMultichannelMode(const int64_t activateSessionId);
928     AudioModuleInfo ConstructMchAudioModuleInfo(DeviceType deviceType);
929     int32_t LoadMchModule();
930     int32_t UnloadMchModule();
931 
932     int32_t MoveToNewPipeInner(const uint32_t sessionId, const AudioPipeType pipeType);
933 
934     void UpdateRoute(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
935         vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices);
936 
937     bool IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType &deviceType);
938 
939     bool SelectRingerOrAlarmDevices(const vector<std::unique_ptr<AudioDeviceDescriptor>> &descs,
940         const unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo);
941 
942     void DealAudioSceneOutputDevices(const AudioScene &audioScene, std::vector<DeviceType> &activeOutputDevices,
943         bool &haveArmUsbDevice);
944 
945     bool IsA2dpOrArmUsbDevice(const InternalDeviceType &deviceType);
946 
947     void UpdateAllUserSelectDevice(vector<unique_ptr<AudioDeviceDescriptor>> &userSelectDeviceMap,
948         AudioDeviceDescriptor &desc, const sptr<AudioDeviceDescriptor> &selectDesc);
949 
950     void SetAbsVolumeSceneAsync(const std::string &macAddress, const bool support);
951 
952     void SetSharedAbsVolumeScene(const bool support);
953 
954     void LoadHdiEffectModel();
955 
956     void UpdateEffectBtOffloadSupported(const bool &isSupported);
957 
958     int32_t ScoInputDeviceFetchedForRecongnition(bool handleFlag, const std::string &address,
959         ConnectState connectState);
960 
961     bool IsA2dpOffloadConnected();
962 
963     void SetCurrenInputDevice(const AudioDeviceDescriptor &desc);
964 
965     AudioDeviceDescriptor GetCurrentInputDevice();
966 
967     DeviceType GetCurrentInputDeviceType();
968 
969     void SetCurrentInputDeviceType(DeviceType deviceType);
970 
971     void SetCurrentOutputDevice(const AudioDeviceDescriptor &desc);
972 
973     void SetCurrentOutputDeviceType(DeviceType deviceType);
974 
975     AudioDeviceDescriptor GetCurrentOutputDevice();
976 
977     DeviceType GetCurrentOutputDeviceType();
978 
979     DeviceCategory GetCurrentOutputDeviceCategory();
980 
981     std::string GetCurrentOutputDeviceNetworkId();
982 
983     std::string GetCurrentOutputDeviceMacAddr();
984 
985     void SendA2dpConnectedWhileRunning(const RendererState &rendererState, const uint32_t &sessionId);
986 
987     int32_t ConnectVirtualDevice(sptr<AudioDeviceDescriptor> &desc);
988     void UpdateDeviceList(AudioDeviceDescriptor &updatedDesc, bool isConnected,
989         std::vector<sptr<AudioDeviceDescriptor>> &descForCb,
990         AudioStreamDeviceChangeReasonExt &reason);
991     void UpdateDefaultOutputDeviceWhenStopping(int32_t uid);
992 
993     void SetDefaultDeviceLoadFlag(bool isLoad);
994 
995     int32_t ErasePreferredDeviceByType(const PreferredType preferredType);
996 
997     void CheckAndNotifyUserSelectedDevice(const sptr<AudioDeviceDescriptor> &deviceDescriptor);
998 
999     bool GetAudioEffectOffloadFlag();
1000     void ResetOffloadModeOnSpatializationChanged(std::vector<int32_t> &allSessions);
1001 
1002     bool CheckSpatializationAndEffectState();
1003 
1004     void FetchStreamForSpkMchStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
1005     vector<std::unique_ptr<AudioDeviceDescriptor>> &descs);
1006 
1007     void ResetOffloadAndMchMode(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo,
1008         vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices);
1009 
1010     void JudgeIfLoadMchModule();
1011 
1012     const sptr<IStandardAudioService> GetAudioServerProxy();
1013 
1014     int32_t SelectFastInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
1015         sptr<AudioDeviceDescriptor> deviceDescriptor);
1016 
1017     void GetAudioAdapterInfos(std::unordered_map<AdaptersType, AudioAdapterInfo> &adapterInfoMap);
1018 
1019     void GetVolumeGroupData(std::unordered_map<std::string, std::string>& volumeGroupData);
1020 
1021     void GetInterruptGroupData(std::unordered_map<std::string, std::string>& interruptGroupData);
1022 
1023     void GetDeviceClassInfo(std::unordered_map<ClassType, std::list<AudioModuleInfo>> &deviceClassInfo);
1024 
1025     void GetGlobalConfigs(GlobalConfigs &globalConfigs);
1026 
1027     int32_t HandleSpecialDeviceType(DeviceType &devType, bool &isConnected, const std::string &address);
1028 
1029     void ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType, const std::string &macAddress,
1030         const std::string &deviceName, const AudioStreamInfo &streamInfo);
1031 
1032     void HandleOfflineDistributedDevice();
1033 
1034     int32_t HandleDistributedDeviceUpdate(DStatusInfo &statusInfo,
1035         std::vector<sptr<AudioDeviceDescriptor>> &descForCb);
1036 
1037     void OnServiceConnected(AudioServiceIndex serviceIndex);
1038 
1039     void LoadModernInnerCapSink();
1040 
1041     void HandleAudioCaptureState(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo);
1042 
1043     AudioStreamType GetStreamType(int32_t sessionId);
1044 
1045     int32_t GetChannelCount(uint32_t sessionId);
1046 
1047     int32_t GetUid(int32_t sessionId);
1048 
1049     bool SetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume vol);
1050 
1051     void UnregisterBluetoothListener();
1052 
1053     void GetEffectManagerInfo();
1054 
1055     std::vector<unique_ptr<AudioDeviceDescriptor>> GetAvailableDevicesInner(AudioDeviceUsage usage);
1056 
1057     void UpdateA2dpOffloadFlagForAllStream(std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnableMap,
1058         DeviceType deviceType = DEVICE_TYPE_NONE);
1059 
1060     int32_t UpdateA2dpOffloadFlagForAllStream(DeviceType deviceType = DEVICE_TYPE_NONE);
1061 
1062     int32_t OffloadStartPlaying(const std::vector<int32_t> &sessionIds);
1063 
1064 #ifdef BLUETOOTH_ENABLE
1065     void UpdateA2dpOffloadFlag(const std::vector<Bluetooth::A2dpStreamInfo> &allActiveSessions,
1066         DeviceType deviceType = DEVICE_TYPE_NONE);
1067 
1068     void CheckAndActiveHfpDevice(AudioDeviceDescriptor &desc);
1069 #endif
1070 
1071     void OnPreferredStateUpdated(AudioDeviceDescriptor &desc,
1072         const DeviceInfoUpdateCommand updateCommand, AudioStreamDeviceChangeReasonExt &reason);
1073 
1074     void CheckForA2dpSuspend(AudioDeviceDescriptor &desc);
1075 
1076     void UnloadA2dpModule();
1077 
1078     std::vector<sptr<AudioDeviceDescriptor>> GetDumpDevices(DeviceFlag deviceFlag);
1079     std::vector<sptr<AudioDeviceDescriptor>> GetDumpDeviceInfo(std::string &dumpString, DeviceFlag deviceFlag);
1080     bool IsStreamSupported(AudioStreamType streamType);
1081     bool IsVoiceCallRelatedScene();
1082 private:
1083     bool isUpdateRouteSupported_ = true;
1084     bool isCurrentRemoteRenderer = false;
1085     bool remoteCapturerSwitch_ = false;
1086     bool isOpenRemoteDevice = false;
1087     static bool isBtListenerRegistered;
1088     bool isPnpDeviceConnected = false;
1089     bool hasModulesLoaded = false;
1090     bool hasEarpiece_ = false;
1091     const int32_t G_UNKNOWN_PID = -1;
1092     int32_t dAudioClientUid = 3055;
1093     int32_t maxRendererInstances_ = 128;
1094     uint64_t audioLatencyInMsec_ = 50;
1095     uint32_t sinkLatencyInMsec_ {0};
1096     bool isOffloadAvailable_ = false;
1097     bool enableFastVoip_ = false;
1098     bool enableDualHalToneState_ = false;
1099     int32_t enableDualHalToneSessionId_ = -1;
1100     int32_t shouldUpdateDeviceDueToDualTone_ = false;
1101     bool isFastControlled_ = true;
1102     bool isVoiceRingtoneMute_ = false;
1103 
1104     std::unordered_map<std::string, DeviceType> spatialDeviceMap_;
1105 
1106     BluetoothOffloadState a2dpOffloadFlag_ = NO_A2DP_DEVICE;
1107     std::mutex switchA2dpOffloadMutex_;
1108 
1109     std::bitset<MIN_SERVICE_COUNT> serviceFlag_;
1110     std::mutex serviceFlagMutex_;
1111     DeviceType effectActiveDevice_ = DEVICE_TYPE_NONE;
1112     std::mutex curOutputDevice_; // lock this mutex to operate currentActiveDevice_
1113     AudioDeviceDescriptor currentActiveDevice_ = AudioDeviceDescriptor(DEVICE_TYPE_NONE, DEVICE_ROLE_NONE);
1114     std::mutex curInputDevice_; // lock this mutex to operate currentActiveInputDevice_
1115     AudioDeviceDescriptor currentActiveInputDevice_ = AudioDeviceDescriptor(DEVICE_TYPE_NONE, DEVICE_ROLE_NONE);
1116     std::vector<std::pair<DeviceType, bool>> pnpDeviceList_;
1117 
1118     std::mutex routerMapMutex_; // unordered_map is not concurrently-secure
1119     mutable std::mutex a2dpDeviceMapMutex_;
1120     std::unordered_map<int32_t, std::pair<std::string, int32_t>> routerMap_;
1121     std::unordered_map<int32_t, std::pair<std::string, DeviceRole>> fastRouterMap_; // key:uid value:<netWorkId, Role>
1122     IAudioPolicyInterface& audioPolicyManager_;
1123     Parser& audioPolicyConfigParser_;
1124 #ifdef FEATURE_DTMF_TONE
1125     std::unordered_map<int32_t, std::shared_ptr<ToneInfo>> toneDescriptorMap;
1126 #endif
1127     AudioStreamCollector& streamCollector_;
1128     AudioRouterCenter& audioRouterCenter_;
1129 #ifdef ACCESSIBILITY_ENABLE
1130     std::shared_ptr<AccessibilityConfigListener> accessibilityConfigListener_;
1131 #endif
1132     std::unique_ptr<DeviceStatusListener> deviceStatusListener_;
1133     std::vector<sptr<AudioDeviceDescriptor>> connectedDevices_;
1134     std::vector<sptr<MicrophoneDescriptor>> connectedMicrophones_;
1135     std::unordered_map<int32_t, sptr<MicrophoneDescriptor>> audioCaptureMicrophoneDescriptor_;
1136     std::unordered_map<std::string, A2dpDeviceConfigInfo> connectedA2dpDeviceMap_;
1137     std::string activeBTDevice_;
1138 
1139     AudioScene audioScene_ = AUDIO_SCENE_DEFAULT;
1140     AudioScene lastAudioScene_ = AUDIO_SCENE_DEFAULT;
1141     std::unordered_map<ClassType, std::list<AudioModuleInfo>> deviceClassInfo_ = {};
1142     std::unordered_map<AdaptersType, AudioAdapterInfo> adapterInfoMap_ {};
1143 
1144     std::mutex ioHandlesMutex_;
1145     std::unordered_map<std::string, AudioIOHandle> IOHandles_ = {};
1146 
1147     std::shared_ptr<AudioSharedMemory> policyVolumeMap_ = nullptr;
1148     volatile Volume *volumeVector_ = nullptr;
1149     volatile bool *sharedAbsVolumeScene_ = nullptr;
1150 
1151     std::vector<DeviceType> outputPriorityList_ = {
1152         DEVICE_TYPE_BLUETOOTH_SCO,
1153         DEVICE_TYPE_BLUETOOTH_A2DP,
1154         DEVICE_TYPE_DP,
1155         DEVICE_TYPE_USB_HEADSET,
1156         DEVICE_TYPE_WIRED_HEADSET,
1157         DEVICE_TYPE_SPEAKER
1158     };
1159     std::vector<DeviceType> inputPriorityList_ = {
1160         DEVICE_TYPE_BLUETOOTH_SCO,
1161         DEVICE_TYPE_BLUETOOTH_A2DP,
1162         DEVICE_TYPE_USB_HEADSET,
1163         DEVICE_TYPE_WIRED_HEADSET,
1164         DEVICE_TYPE_WAKEUP,
1165         DEVICE_TYPE_MIC
1166     };
1167 
1168     std::vector<sptr<VolumeGroupInfo>> volumeGroups_;
1169     std::vector<sptr<InterruptGroupInfo>> interruptGroups_;
1170     std::unordered_map<std::string, std::string> volumeGroupData_;
1171     std::unordered_map<std::string, std::string> interruptGroupData_;
1172     GlobalConfigs globalConfigs_;
1173     AudioEffectService& audioEffectService_;
1174 
1175     bool isMicrophoneMuteTemporary_ = false;
1176 
1177     bool isMicrophoneMutePersistent_ = false;
1178 
1179     mutable std::shared_mutex deviceStatusUpdateSharedMutex_;
1180 
1181     bool hasArmUsbDevice_ = false;
1182     bool hasHifiUsbDevice_ = false; // Only the first usb device is supported now, hifi or arm.
1183     bool hasDpDevice_ = false; // Only the first dp device is supported.
1184 
1185     AudioDeviceManager &audioDeviceManager_;
1186     AudioStateManager &audioStateManager_;
1187     std::shared_ptr<AudioPolicyServerHandler> audioPolicyServerHandler_;
1188     AudioPnpServer &audioPnpServer_;
1189 
1190     std::optional<uint32_t> offloadSessionID_;
1191     PowerMgr::PowerState currentPowerState_ = PowerMgr::PowerState::AWAKE;
1192     bool currentOffloadSessionIsBackground_ = false;
1193     std::mutex offloadMutex_;
1194 
1195     AudioModuleInfo primaryMicModuleInfo_ = {};
1196     std::mutex defaultDeviceLoadMutex_;
1197     std::condition_variable loadDefaultDeviceCV_;
1198     std::atomic<bool> isPrimaryMicModuleInfoLoaded_ = false;
1199     std::atomic<bool> isAdapterInfoMap_ = false;
1200 
1201     std::mutex moveDeviceMutex_;
1202     std::condition_variable moveDeviceCV_;
1203     std::atomic<bool> moveDeviceFinished_ = false;
1204 
1205     std::unordered_map<uint32_t, SessionInfo> sessionWithNormalSourceType_;
1206 
1207     DistributedRoutingInfo distributedRoutingInfo_ = {
1208         .descriptor = nullptr,
1209         .type = CAST_TYPE_NULL
1210     };
1211 
1212     // sourceType is SOURCE_TYPE_PLAYBACK_CAPTURE, SOURCE_TYPE_WAKEUP or SOURCE_TYPE_VIRTUAL_CAPTURE
1213     std::unordered_map<uint32_t, SessionInfo> sessionWithSpecialSourceType_;
1214 
1215     static std::map<std::string, std::string> sinkPortStrToClassStrMap_;
1216     static std::map<std::string, uint32_t> formatStrToEnum;
1217     static std::map<std::string, ClassType> classStrToEnum;
1218 
1219     std::unordered_set<uint32_t> sessionIdisRemovedSet_;
1220 
1221     SourceType currentSourceType = SOURCE_TYPE_MIC;
1222     uint32_t currentRate = 0;
1223 
1224     bool updateA2dpOffloadLogFlag = false;
1225     std::mutex checkSpatializedMutex_;
1226     SafeStatus safeStatusBt_ = SAFE_UNKNOWN;
1227     SafeStatus safeStatus_ = SAFE_UNKNOWN;
1228     int64_t activeSafeTimeBt_ = 0;
1229     int64_t activeSafeTime_ = 0;
1230     std::time_t startSafeTimeBt_ = 0;
1231     std::time_t startSafeTime_ = 0;
1232     bool userSelect_ = false;
1233     std::unique_ptr<std::thread> calculateLoopSafeTime_ = nullptr;
1234     std::mutex checkMusicActiveThreadMutex_; // lock calculateLoopSafeTime_
1235     bool safeVolumeExit_ = false;
1236     bool isAbsBtFirstBoot_ = true;
1237     bool normalVoipFlag_ = false;
1238 
1239     std::mutex dialogMutex_;
1240     std::atomic<bool> isDialogSelectDestroy_ = false;
1241     std::condition_variable dialogSelectCondition_;
1242 
1243     std::unique_ptr<std::thread> safeVolumeDialogThrd_ = nullptr;
1244     std::atomic<bool> isSafeVolumeDialogShowing_ = false;
1245     std::mutex safeVolumeMutex_;
1246 
1247     DeviceType priorityOutputDevice_ = DEVICE_TYPE_INVALID;
1248     DeviceType priorityInputDevice_ = DEVICE_TYPE_INVALID;
1249     ConnectType conneceType_ = CONNECT_TYPE_LOCAL;
1250 
1251     SupportedEffectConfig supportedEffectConfig_;
1252     ConverterConfig converterConfig_;
1253 
1254     std::unique_ptr<std::thread> RecoveryDevicesThread_ = nullptr;
1255 
1256     std::mutex offloadCloseMutex_;
1257     std::mutex offloadOpenMutex_;
1258     std::atomic<bool> isOffloadOpened_ = false;
1259     std::condition_variable offloadCloseCondition_;
1260 
1261     std::mutex ringerModeMuteMutex_;
1262     std::atomic<bool> ringerModeMute_ = true;
1263     std::condition_variable ringerModeMuteCondition_;
1264     std::atomic<bool> isPolicyConfigParsered_ = false;
1265     std::shared_ptr<AudioA2dpOffloadManager> audioA2dpOffloadManager_ = nullptr;
1266 
1267     bool isBTReconnecting_ = false;
1268 };
1269 
1270 class AudioA2dpOffloadManager final : public Bluetooth::AudioA2dpPlayingStateChangedListener,
1271     public enable_shared_from_this<AudioA2dpOffloadManager> {
1272 public:
AudioA2dpOffloadManager(AudioPolicyService * audioPolicyService)1273     AudioA2dpOffloadManager(AudioPolicyService *audioPolicyService) : audioPolicyService_(audioPolicyService) {};
Init()1274     void Init() {Bluetooth::AudioA2dpManager::RegisterA2dpPlayingStateChangedListener(shared_from_this());};
GetA2dOffloadConnectionState()1275     A2dpOffloadConnectionState GetA2dOffloadConnectionState() {return currentOffloadConnectionState_;};
1276 
1277     void ConnectA2dpOffload(const std::string &deviceAddress, const vector<int32_t> &sessionIds);
1278     void OnA2dpPlayingStateChanged(const std::string &deviceAddress, int32_t playingState) override;
1279 
1280     void WaitForConnectionCompleted();
1281     bool IsA2dpOffloadConnecting(int32_t sessionId);
1282 private:
1283     A2dpOffloadConnectionState currentOffloadConnectionState_ = CONNECTION_STATUS_DISCONNECTED;
1284     std::vector<int32_t> connectionTriggerSessionIds_;
1285     std::string a2dpOffloadDeviceAddress_ = "";
1286     AudioPolicyService *audioPolicyService_ = nullptr;
1287     std::mutex connectionMutex_;
1288     std::condition_variable connectionCV_;
1289     static const int32_t CONNECTION_TIMEOUT_IN_MS = 1000; // 1000ms
1290 };
1291 } // namespace AudioStandard
1292 } // namespace OHOS
1293 
1294 #endif // ST_AUDIO_POLICY_SERVICE_H
1295