1 /*
2 * Copyright (c) 2024-2025 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 #ifndef LOG_TAG
16 #define LOG_TAG "AudioDeviceLock"
17 #endif
18
19 #include "audio_device_lock.h"
20 #include <ability_manager_client.h>
21 #include "iservice_registry.h"
22 #include "parameter.h"
23 #include "parameters.h"
24 #include "audio_policy_log.h"
25 #include "media_monitor_manager.h"
26 #include "audio_state_manager.h"
27
28 #include "audio_policy_utils.h"
29 #include "audio_server_proxy.h"
30
31 namespace OHOS {
32 namespace AudioStandard {
33 const int32_t DATA_LINK_CONNECTED = 11;
34 static constexpr int64_t WAIT_LOAD_DEFAULT_DEVICE_TIME_MS = 200; // 200ms
35 static constexpr int32_t RETRY_TIMES = 25;
36
GetEncryptAddr(const std::string & addr)37 static std::string GetEncryptAddr(const std::string &addr)
38 {
39 const int32_t START_POS = 6;
40 const int32_t END_POS = 13;
41 const int32_t ADDRESS_STR_LEN = 17;
42 if (addr.empty() || addr.length() != ADDRESS_STR_LEN) {
43 return std::string("");
44 }
45 std::string tmp = "**:**:**:**:**:**";
46 std::string out = addr;
47 for (int i = START_POS; i <= END_POS; i++) {
48 out[i] = tmp[i];
49 }
50 return out;
51 }
52
Init(std::shared_ptr<AudioA2dpOffloadManager> audioA2dpOffloadManager)53 void AudioDeviceLock::Init(std::shared_ptr<AudioA2dpOffloadManager> audioA2dpOffloadManager)
54 {
55 audioA2dpOffloadManager_ = audioA2dpOffloadManager;
56 }
57
DeInit()58 void AudioDeviceLock::DeInit()
59 {
60 audioA2dpOffloadManager_ = nullptr;
61 }
62
SetAudioScene(AudioScene audioScene,const int32_t uid,const int32_t pid)63 int32_t AudioDeviceLock::SetAudioScene(AudioScene audioScene, const int32_t uid, const int32_t pid)
64 {
65 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
66
67 AUDIO_INFO_LOG("Set audio scene start: %{public}d, lastScene: %{public}d, uid: %{public}d, pid: %{public}d",
68 audioScene, audioSceneManager_.GetLastAudioScene(), uid, pid);
69 audioSceneManager_.SetAudioScenePre(audioScene);
70 audioStateManager_.SetAudioSceneOwnerUid(audioScene == 0 ? 0 : uid);
71 bool isSameScene = audioSceneManager_.IsSameAudioScene();
72
73 // fetch input&output device
74 audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::SET_AUDIO_SCENE);
75 audioDeviceCommon_.FetchDevice(false);
76
77 if (!isSameScene) {
78 int32_t result = audioSceneManager_.SetAudioSceneAfter(audioScene, audioA2dpOffloadFlag_.GetA2dpOffloadFlag());
79 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "failed [%{public}d]", result);
80 }
81 audioDeviceCommon_.OnAudioSceneChange(audioScene);
82
83 if (audioScene == AUDIO_SCENE_PHONE_CALL) {
84 // Make sure the STREAM_VOICE_CALL volume is set before the calling starts.
85 audioVolumeManager_.SetVoiceCallVolume(audioVolumeManager_.GetSystemVolumeLevel(STREAM_VOICE_CALL));
86 } else {
87 audioVolumeManager_.SetVoiceRingtoneMute(false);
88 }
89 audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
90 audioActiveDevice_.GetCurrentOutputDevice(), "SetAudioScene");
91 return SUCCESS;
92 }
93
IsArmUsbDevice(const AudioDeviceDescriptor & desc)94 bool AudioDeviceLock::IsArmUsbDevice(const AudioDeviceDescriptor &desc)
95 {
96 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
97 return audioDeviceManager_.IsArmUsbDevice(desc);
98 }
99
GetDevices(DeviceFlag deviceFlag)100 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioDeviceLock::GetDevices(DeviceFlag deviceFlag)
101 {
102 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
103 return audioConnectedDevice_.GetDevicesInner(deviceFlag);
104 }
105
SetDeviceActive(InternalDeviceType deviceType,bool active,const int32_t uid)106 int32_t AudioDeviceLock::SetDeviceActive(InternalDeviceType deviceType, bool active, const int32_t uid)
107 {
108 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
109
110 int32_t ret = audioActiveDevice_.SetDeviceActive(deviceType, active, uid);
111 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetDeviceActive failed");
112
113 audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
114 audioDeviceCommon_.FetchDevice(false);
115 audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
116 audioActiveDevice_.GetCurrentOutputDevice(), "SetDevcieActive");
117 return SUCCESS;
118 }
119
GetPreferredOutputDeviceDescriptors(AudioRendererInfo & rendererInfo,std::string networkId)120 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioDeviceLock::GetPreferredOutputDeviceDescriptors(
121 AudioRendererInfo &rendererInfo, std::string networkId)
122 {
123 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
124 return audioDeviceCommon_.GetPreferredOutputDeviceDescInner(rendererInfo, networkId);
125 }
126
GetPreferredInputDeviceDescriptors(AudioCapturerInfo & captureInfo,std::string networkId)127 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioDeviceLock::GetPreferredInputDeviceDescriptors(
128 AudioCapturerInfo &captureInfo, std::string networkId)
129 {
130 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
131 return audioDeviceCommon_.GetPreferredInputDeviceDescInner(captureInfo, networkId);
132 }
133
GetActiveBluetoothDevice()134 std::shared_ptr<AudioDeviceDescriptor> AudioDeviceLock::GetActiveBluetoothDevice()
135 {
136 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
137
138 std::shared_ptr<AudioDeviceDescriptor> preferredDesc = audioStateManager_.GetPreferredCallRenderDevice();
139 if (preferredDesc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
140 return preferredDesc;
141 }
142
143 std::vector<shared_ptr<AudioDeviceDescriptor>> audioPrivacyDeviceDescriptors =
144 audioDeviceManager_.GetCommRenderPrivacyDevices();
145 std::vector<shared_ptr<AudioDeviceDescriptor>> activeDeviceDescriptors;
146
147 for (const auto &desc : audioPrivacyDeviceDescriptors) {
148 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && desc->isEnable_) {
149 activeDeviceDescriptors.push_back(make_shared<AudioDeviceDescriptor>(*desc));
150 }
151 }
152
153 uint32_t btDeviceSize = activeDeviceDescriptors.size();
154 if (btDeviceSize == 0) {
155 activeDeviceDescriptors = audioDeviceManager_.GetCommRenderBTCarDevices();
156 }
157 btDeviceSize = activeDeviceDescriptors.size();
158 if (btDeviceSize == 0) {
159 return make_shared<AudioDeviceDescriptor>();
160 } else if (btDeviceSize == 1) {
161 shared_ptr<AudioDeviceDescriptor> res = std::move(activeDeviceDescriptors[0]);
162 return res;
163 }
164
165 uint32_t index = 0;
166 for (uint32_t i = 1; i < btDeviceSize; ++i) {
167 if (activeDeviceDescriptors[i]->connectTimeStamp_ >
168 activeDeviceDescriptors[index]->connectTimeStamp_) {
169 index = i;
170 }
171 }
172 shared_ptr<AudioDeviceDescriptor> res = std::move(activeDeviceDescriptors[index]);
173 return res;
174 }
175
UpdateAppVolume(int32_t appUid,int32_t volume)176 void AudioDeviceLock::UpdateAppVolume(int32_t appUid, int32_t volume)
177 {
178 AUDIO_INFO_LOG("appUid = %{public}d, volume = %{public}d", appUid, volume);
179 streamCollector_.UpdateAppVolume(appUid, volume);
180 }
181
OnDeviceInfoUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand command)182 void AudioDeviceLock::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command)
183 {
184 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
185 audioDeviceStatus_.OnDeviceInfoUpdated(desc, command);
186 }
187
SetCallDeviceActive(InternalDeviceType deviceType,bool active,std::string address,const int32_t uid)188 int32_t AudioDeviceLock::SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address,
189 const int32_t uid)
190 {
191 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
192
193 CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
194
195 int32_t ret = audioActiveDevice_.SetCallDeviceActive(deviceType, active, address, uid);
196 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetCallDeviceActive failed");
197 audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
198 audioDeviceCommon_.FetchDevice(false);
199 return SUCCESS;
200 }
201
GetAvailableDevices(AudioDeviceUsage usage)202 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioDeviceLock::GetAvailableDevices(AudioDeviceUsage usage)
203 {
204 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
205 return AudioPolicyUtils::GetInstance().GetAvailableDevicesInner(usage);
206 }
207
FetchOutputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo,const AudioStreamDeviceChangeReasonExt reason)208 void AudioDeviceLock::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo,
209 const AudioStreamDeviceChangeReasonExt reason)
210 {
211 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
212 AUDIO_INFO_LOG("fetch device for track, sessionid:%{public}d start",
213 streamChangeInfo.audioRendererChangeInfo.sessionId);
214
215 AudioMode mode = AudioMode::AUDIO_MODE_PLAYBACK;
216 // Set prerunningState true to refetch devices when device info change before update tracker to running
217 streamChangeInfo.audioRendererChangeInfo.prerunningState = true;
218 if (streamCollector_.UpdateTrackerInternal(mode, streamChangeInfo) != SUCCESS) {
219 return;
220 }
221
222 vector<shared_ptr<AudioRendererChangeInfo>> rendererChangeInfo;
223 rendererChangeInfo.push_back(
224 make_shared<AudioRendererChangeInfo>(streamChangeInfo.audioRendererChangeInfo));
225 streamCollector_.GetRendererStreamInfo(streamChangeInfo, *rendererChangeInfo[0]);
226
227 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStarting(streamChangeInfo.audioRendererChangeInfo.sessionId);
228
229 audioDeviceCommon_.FetchOutputDevice(rendererChangeInfo, reason);
230 }
231
FetchInputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo)232 void AudioDeviceLock::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo)
233 {
234 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
235 AUDIO_INFO_LOG("fetch device for track, sessionid:%{public}d start",
236 streamChangeInfo.audioCapturerChangeInfo.sessionId);
237
238 vector<shared_ptr<AudioCapturerChangeInfo>> capturerChangeInfo;
239 capturerChangeInfo.push_back(
240 make_shared<AudioCapturerChangeInfo>(streamChangeInfo.audioCapturerChangeInfo));
241 streamCollector_.GetCapturerStreamInfo(streamChangeInfo, *capturerChangeInfo[0]);
242
243 audioDeviceCommon_.FetchInputDevice(capturerChangeInfo);
244 }
245
246
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object,const int32_t apiVersion)247 int32_t AudioDeviceLock::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
248 const sptr<IRemoteObject> &object, const int32_t apiVersion)
249 {
250 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
251
252 if (mode == AUDIO_MODE_RECORD) {
253 audioMicrophoneDescriptor_.AddAudioCapturerMicrophoneDescriptor(
254 streamChangeInfo.audioCapturerChangeInfo.sessionId, DEVICE_TYPE_NONE);
255 if (apiVersion > 0 && apiVersion < API_11) {
256 audioDeviceCommon_.UpdateDeviceInfo(streamChangeInfo.audioCapturerChangeInfo.inputDeviceInfo,
257 std::make_shared<AudioDeviceDescriptor>(audioActiveDevice_.GetCurrentInputDevice()), false, false);
258 }
259 } else if (apiVersion > 0 && apiVersion < API_11) {
260 audioDeviceCommon_.UpdateDeviceInfo(streamChangeInfo.audioRendererChangeInfo.outputDeviceInfo,
261 std::make_shared<AudioDeviceDescriptor>(audioActiveDevice_.GetCurrentOutputDevice()), false, false);
262 }
263 return streamCollector_.RegisterTracker(mode, streamChangeInfo, object);
264 }
265
UpdateSessionConnectionState(const int32_t & sessionID,const int32_t & state)266 void AudioDeviceLock::UpdateSessionConnectionState(const int32_t &sessionID, const int32_t &state)
267 {
268 AudioServerProxy::GetInstance().UpdateSessionConnectionStateProxy(sessionID, state);
269 }
270
SendA2dpConnectedWhileRunning(const RendererState & rendererState,const uint32_t & sessionId)271 void AudioDeviceLock::SendA2dpConnectedWhileRunning(const RendererState &rendererState, const uint32_t &sessionId)
272 {
273 if ((rendererState == RENDERER_RUNNING) && (audioA2dpOffloadManager_ != nullptr) &&
274 !audioA2dpOffloadManager_->IsA2dpOffloadConnecting(sessionId)) {
275 AUDIO_INFO_LOG("Notify client not to block.");
276 std::thread sendConnectedToClient(&AudioDeviceLock::UpdateSessionConnectionState, this, sessionId,
277 DATA_LINK_CONNECTED);
278 sendConnectedToClient.detach();
279 }
280 }
281
HandleAudioCaptureState(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)282 void AudioDeviceLock::HandleAudioCaptureState(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
283 {
284 if (mode == AUDIO_MODE_RECORD &&
285 (streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_RELEASED ||
286 streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_STOPPED)) {
287 if (Util::IsScoSupportSource(streamChangeInfo.audioCapturerChangeInfo.capturerInfo.sourceType)) {
288 audioDeviceCommon_.BluetoothScoDisconectForRecongnition();
289 Bluetooth::AudioHfpManager::ClearRecongnitionStatus();
290 } else if (audioDeviceManager_.GetScoState() &&
291 audioSceneManager_.GetAudioScene() == AUDIO_SCENE_DEFAULT) {
292 AUDIO_INFO_LOG("close capture app, disconnect sco");
293 Bluetooth::AudioHfpManager::DisconnectSco();
294 }
295 audioMicrophoneDescriptor_.RemoveAudioCapturerMicrophoneDescriptorBySessionID(
296 streamChangeInfo.audioCapturerChangeInfo.sessionId);
297 }
298 }
299
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)300 int32_t AudioDeviceLock::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
301 {
302 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
303
304 HandleAudioCaptureState(mode, streamChangeInfo);
305
306 int32_t ret = streamCollector_.UpdateTracker(mode, streamChangeInfo);
307
308 const auto &rendererState = streamChangeInfo.audioRendererChangeInfo.rendererState;
309 if (rendererState == RENDERER_PREPARED || rendererState == RENDERER_NEW || rendererState == RENDERER_INVALID) {
310 return ret; // only update tracker in new and prepared
311 }
312
313 audioDeviceCommon_.UpdateTracker(mode, streamChangeInfo, rendererState);
314
315 if (audioA2dpOffloadManager_) {
316 audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream(audioActiveDevice_.GetCurrentOutputDeviceType());
317 }
318 SendA2dpConnectedWhileRunning(rendererState, streamChangeInfo.audioRendererChangeInfo.sessionId);
319 return ret;
320 }
321
UpdateDefaultOutputDeviceWhenStopping(int32_t uid)322 void AudioDeviceLock::UpdateDefaultOutputDeviceWhenStopping(int32_t uid)
323 {
324 std::vector<uint32_t> sessionIDSet = streamCollector_.GetAllRendererSessionIDForUID(uid);
325 for (const auto &sessionID : sessionIDSet) {
326 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(sessionID);
327 audioDeviceManager_.RemoveSelectedDefaultOutputDevice(sessionID);
328 }
329 audioDeviceCommon_.FetchDevice(true);
330 }
331
RegisteredTrackerClientDied(pid_t uid)332 void AudioDeviceLock::RegisteredTrackerClientDied(pid_t uid)
333 {
334 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
335
336 UpdateDefaultOutputDeviceWhenStopping(static_cast<int32_t>(uid));
337
338 audioMicrophoneDescriptor_.RemoveAudioCapturerMicrophoneDescriptor(static_cast<int32_t>(uid));
339 streamCollector_.RegisteredTrackerClientDied(static_cast<int32_t>(uid));
340
341 audioDeviceCommon_.ClientDiedDisconnectScoNormal();
342 audioDeviceCommon_.ClientDiedDisconnectScoRecognition();
343
344 if (!streamCollector_.ExistStreamForPipe(PIPE_TYPE_OFFLOAD)) {
345 audioOffloadStream_.DynamicUnloadOffloadModule();
346 }
347
348 if (!streamCollector_.ExistStreamForPipe(PIPE_TYPE_MULTICHANNEL)) {
349 audioOffloadStream_.UnloadMchModule();
350 }
351 }
352
OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo,DeviceRole role,bool hasPair)353 void AudioDeviceLock::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress,
354 const std::string& deviceName, const AudioStreamInfo& streamInfo, DeviceRole role, bool hasPair)
355 {
356 // Pnp device status update
357 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
358 audioDeviceStatus_.OnDeviceStatusUpdated(devType, isConnected, macAddress, deviceName, streamInfo, role, hasPair);
359 }
360
OnDeviceStatusUpdated(AudioDeviceDescriptor & updatedDesc,bool isConnected)361 void AudioDeviceLock::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, bool isConnected)
362 {
363 // Bluetooth device status updated
364 DeviceType devType = updatedDesc.deviceType_;
365 string macAddress = updatedDesc.macAddress_;
366 string deviceName = updatedDesc.deviceName_;
367 bool isActualConnection = (updatedDesc.connectState_ != VIRTUAL_CONNECTED);
368 AUDIO_INFO_LOG("Device connection is actual connection: %{public}d", isActualConnection);
369
370 AudioStreamInfo streamInfo = {};
371 #ifdef BLUETOOTH_ENABLE
372 if (devType == DEVICE_TYPE_BLUETOOTH_A2DP && isActualConnection && isConnected) {
373 int32_t ret = Bluetooth::AudioA2dpManager::GetA2dpDeviceStreamInfo(macAddress, streamInfo);
374 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Get a2dp device stream info failed!");
375 }
376 if (devType == DEVICE_TYPE_BLUETOOTH_A2DP_IN && isActualConnection && isConnected) {
377 int32_t ret = Bluetooth::AudioA2dpManager::GetA2dpInDeviceStreamInfo(macAddress, streamInfo);
378 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Get a2dp input device stream info failed!");
379 }
380 if (isConnected && isActualConnection
381 && devType == DEVICE_TYPE_BLUETOOTH_SCO
382 && updatedDesc.deviceCategory_ != BT_UNWEAR_HEADPHONE
383 && !audioDeviceManager_.GetScoState()) {
384 Bluetooth::AudioHfpManager::SetActiveHfpDevice(macAddress);
385 }
386 #endif
387 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
388 audioDeviceStatus_.OnDeviceStatusUpdated(updatedDesc, devType,
389 macAddress, deviceName, isActualConnection, streamInfo, isConnected);
390 }
391
OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)392 void AudioDeviceLock::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress,
393 const std::string &deviceName, const AudioStreamInfo &streamInfo)
394 {
395 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
396 audioDeviceStatus_.OnDeviceConfigurationChanged(deviceType, macAddress, deviceName, streamInfo);
397 }
398
UpdateRendererInfoWhenNoPermission(const shared_ptr<AudioRendererChangeInfo> & audioRendererChangeInfos,bool hasSystemPermission)399 static void UpdateRendererInfoWhenNoPermission(const shared_ptr<AudioRendererChangeInfo> &audioRendererChangeInfos,
400 bool hasSystemPermission)
401 {
402 if (!hasSystemPermission) {
403 audioRendererChangeInfos->clientUID = 0;
404 audioRendererChangeInfos->rendererState = RENDERER_INVALID;
405 }
406 }
407
GetCurrentRendererChangeInfos(vector<shared_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos,bool hasBTPermission,bool hasSystemPermission)408 int32_t AudioDeviceLock::GetCurrentRendererChangeInfos(vector<shared_ptr<AudioRendererChangeInfo>>
409 &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission)
410 {
411 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
412
413 int32_t status = streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
414 CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status,
415 "AudioPolicyServer:: Get renderer change info failed");
416
417 std::vector<std::shared_ptr<AudioDeviceDescriptor>> outputDevices =
418 audioConnectedDevice_.GetDevicesInner(OUTPUT_DEVICES_FLAG);
419 DeviceType activeDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
420 DeviceRole activeDeviceRole = OUTPUT_DEVICE;
421 std::string activeDeviceMac = audioActiveDevice_.GetCurrentOutputDeviceMacAddr();
422
423 const auto& itr = std::find_if(outputDevices.begin(), outputDevices.end(),
424 [&activeDeviceType, &activeDeviceRole, &activeDeviceMac](const std::shared_ptr<AudioDeviceDescriptor> &desc) {
425 if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
426 // This A2DP device is not the active A2DP device. Skip it.
427 return activeDeviceType != DEVICE_TYPE_BLUETOOTH_A2DP || desc->macAddress_ == activeDeviceMac;
428 }
429 return false;
430 });
431
432 if (itr != outputDevices.end()) {
433 size_t rendererInfosSize = audioRendererChangeInfos.size();
434 for (size_t i = 0; i < rendererInfosSize; i++) {
435 UpdateRendererInfoWhenNoPermission(audioRendererChangeInfos[i], hasSystemPermission);
436 audioDeviceCommon_.UpdateDeviceInfo(audioRendererChangeInfos[i]->outputDeviceInfo, *itr,
437 hasBTPermission, hasSystemPermission);
438 }
439 }
440
441 return status;
442 }
443
GetAvailableMicrophones()444 std::vector<sptr<MicrophoneDescriptor>> AudioDeviceLock::GetAvailableMicrophones()
445 {
446 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
447 return audioMicrophoneDescriptor_.GetAvailableMicrophones();
448 }
449
GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)450 std::vector<sptr<MicrophoneDescriptor>> AudioDeviceLock::GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)
451 {
452 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
453 return audioMicrophoneDescriptor_.GetAudioCapturerMicrophoneDescriptors(sessionId);
454 }
455
OnReceiveBluetoothEvent(const std::string macAddress,const std::string deviceName)456 void AudioDeviceLock::OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName)
457 {
458 std::lock_guard<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_);
459 audioDeviceManager_.OnReceiveBluetoothEvent(macAddress, deviceName);
460 audioConnectedDevice_.SetDisplayName(macAddress, deviceName);
461 }
462
OnDeviceStatusUpdated(DStatusInfo statusInfo,bool isStop)463 void AudioDeviceLock::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop)
464 {
465 // Distributed devices status update
466 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
467 audioDeviceStatus_.OnDeviceStatusUpdated(statusInfo, isStop);
468 }
469
OnForcedDeviceSelected(DeviceType devType,const std::string & macAddress)470 void AudioDeviceLock::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress)
471 {
472 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
473 audioDeviceStatus_.OnForcedDeviceSelected(devType, macAddress);
474 }
475
SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)476 int32_t AudioDeviceLock::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
477 std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)
478 {
479 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
480 return audioRecoveryDevice_.SelectOutputDevice(audioRendererFilter, selectedDesc);
481 }
482
SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)483 int32_t AudioDeviceLock::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
484 std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)
485 {
486 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
487 return audioRecoveryDevice_.SelectInputDevice(audioCapturerFilter, selectedDesc);
488 }
489
ExcludeOutputDevices(AudioDeviceUsage audioDevUsage,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & audioDeviceDescriptors)490 int32_t AudioDeviceLock::ExcludeOutputDevices(AudioDeviceUsage audioDevUsage,
491 std::vector<std::shared_ptr<AudioDeviceDescriptor>> &audioDeviceDescriptors)
492 {
493 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
494 return audioRecoveryDevice_.ExcludeOutputDevices(audioDevUsage, audioDeviceDescriptors);
495 }
496
UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & audioDeviceDescriptors)497 int32_t AudioDeviceLock::UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage,
498 std::vector<std::shared_ptr<AudioDeviceDescriptor>> &audioDeviceDescriptors)
499 {
500 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
501 return audioRecoveryDevice_.UnexcludeOutputDevices(audioDevUsage, audioDeviceDescriptors);
502 }
503
GetExcludedDevices(AudioDeviceUsage audioDevUsage)504 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioDeviceLock::GetExcludedDevices(
505 AudioDeviceUsage audioDevUsage)
506 {
507 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
508 return audioStateManager_.GetExcludedDevices(audioDevUsage);
509 }
510
UpdateTrackerDeviceChange(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc)511 void AudioDeviceLock::UpdateTrackerDeviceChange(const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc)
512 {
513 AUDIO_INFO_LOG("Start");
514
515 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
516 for (std::shared_ptr<AudioDeviceDescriptor> deviceDesc : desc) {
517 if (deviceDesc->deviceRole_ == OUTPUT_DEVICE) {
518 DeviceType type = curOutputDeviceType;
519 std::string macAddress = audioActiveDevice_.GetCurrentOutputDeviceMacAddr();
520 auto itr = audioConnectedDevice_.CheckExistOutputDevice(type, macAddress);
521 if (itr != nullptr) {
522 AudioDeviceDescriptor outputDevice(AudioDeviceDescriptor::DEVICE_INFO);
523 audioDeviceCommon_.UpdateDeviceInfo(outputDevice, itr, true, true);
524 streamCollector_.UpdateTracker(AUDIO_MODE_PLAYBACK, outputDevice);
525 }
526 }
527
528 if (deviceDesc->deviceRole_ == INPUT_DEVICE) {
529 DeviceType type = audioActiveDevice_.GetCurrentInputDeviceType();
530 auto itr = audioConnectedDevice_.CheckExistInputDevice(type);
531 if (itr != nullptr) {
532 AudioDeviceDescriptor inputDevice(AudioDeviceDescriptor::DEVICE_INFO);
533 audioDeviceCommon_.UpdateDeviceInfo(inputDevice, itr, true, true);
534 audioMicrophoneDescriptor_.UpdateAudioCapturerMicrophoneDescriptor(itr->deviceType_);
535 streamCollector_.UpdateTracker(AUDIO_MODE_RECORD, inputDevice);
536 }
537 }
538 }
539 }
540
NotifyRemoteRenderState(std::string networkId,std::string condition,std::string value)541 void AudioDeviceLock::NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value)
542 {
543 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
544
545 AUDIO_INFO_LOG("device<%{public}s> condition:%{public}s value:%{public}s",
546 GetEncryptStr(networkId).c_str(), condition.c_str(), value.c_str());
547
548 std::vector<SinkInput> sinkInputs;
549 audioPolicyManager_.GetAllSinkInputs(sinkInputs);
550 std::vector<shared_ptr<AudioRendererChangeInfo>> rendererChangeInfos;
551 streamCollector_.GetCurrentRendererChangeInfos(rendererChangeInfos);
552 std::vector<SinkInput> targetSinkInputs = {};
553 for (auto &changeInfo : rendererChangeInfos) {
554 if (changeInfo->outputDeviceInfo.networkId_ != networkId) {
555 continue;
556 }
557 for (auto &sinkInput : sinkInputs) {
558 if (changeInfo->sessionId == sinkInput.streamId) {
559 targetSinkInputs.push_back(sinkInput);
560 }
561 }
562 }
563 AUDIO_DEBUG_LOG("move [%{public}zu] of all [%{public}zu]sink-inputs to local.",
564 targetSinkInputs.size(), sinkInputs.size());
565 std::shared_ptr<AudioDeviceDescriptor> localDevice = std::make_shared<AudioDeviceDescriptor>();
566 CHECK_AND_RETURN_LOG(localDevice != nullptr, "Device error: null device.");
567 localDevice->networkId_ = LOCAL_NETWORK_ID;
568 localDevice->deviceRole_ = DeviceRole::OUTPUT_DEVICE;
569 localDevice->deviceType_ = DeviceType::DEVICE_TYPE_SPEAKER;
570
571 int32_t ret;
572 AudioDeviceDescriptor curOutputDeviceDesc = audioActiveDevice_.GetCurrentOutputDevice();
573 if (localDevice->deviceType_ != curOutputDeviceDesc.deviceType_) {
574 AUDIO_WARNING_LOG("device[%{public}d] not active, use device[%{public}d] instead.",
575 static_cast<int32_t>(localDevice->deviceType_), static_cast<int32_t>(curOutputDeviceDesc.deviceType_));
576 ret = audioDeviceCommon_.MoveToLocalOutputDevice(targetSinkInputs,
577 std::make_shared<AudioDeviceDescriptor>(curOutputDeviceDesc));
578 } else {
579 ret = audioDeviceCommon_.MoveToLocalOutputDevice(targetSinkInputs, localDevice);
580 }
581 CHECK_AND_RETURN_LOG((ret == SUCCESS), "MoveToLocalOutputDevice failed!");
582
583 // Suspend device, notify audio stream manager that device has been changed.
584 ret = audioPolicyManager_.SuspendAudioDevice(networkId, true);
585 CHECK_AND_RETURN_LOG((ret == SUCCESS), "SuspendAudioDevice failed!");
586
587 std::vector<std::shared_ptr<AudioDeviceDescriptor>> desc = {};
588 desc.push_back(localDevice);
589 UpdateTrackerDeviceChange(desc);
590 audioDeviceCommon_.OnPreferredOutputDeviceUpdated(curOutputDeviceDesc);
591 AUDIO_DEBUG_LOG("Success");
592 }
593
OnCapturerSessionAdded(uint64_t sessionID,SessionInfo sessionInfo,AudioStreamInfo streamInfo)594 int32_t AudioDeviceLock::OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo,
595 AudioStreamInfo streamInfo)
596 {
597 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
598 return audioCapturerSession_.OnCapturerSessionAdded(sessionID, sessionInfo, streamInfo);
599 }
600
OnCapturerSessionRemoved(uint64_t sessionID)601 void AudioDeviceLock::OnCapturerSessionRemoved(uint64_t sessionID)
602 {
603 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
604 audioCapturerSession_.OnCapturerSessionRemoved(sessionID);
605 }
606
OnServiceConnected(AudioServiceIndex serviceIndex)607 int32_t AudioDeviceLock::OnServiceConnected(AudioServiceIndex serviceIndex)
608 {
609 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
610 return audioDeviceStatus_.OnServiceConnected(serviceIndex);
611 }
612
613 // new lock
OnPnpDeviceStatusUpdated(AudioDeviceDescriptor & desc,bool isConnected)614 void AudioDeviceLock::OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected)
615 {
616 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
617 audioDeviceStatus_.OnPnpDeviceStatusUpdated(desc, isConnected);
618 }
619
OnBlockedStatusUpdated(DeviceType devType,DeviceBlockStatus status)620 void AudioDeviceLock::OnBlockedStatusUpdated(DeviceType devType, DeviceBlockStatus status)
621 {
622 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
623 audioDeviceStatus_.OnBlockedStatusUpdated(devType, status);
624 }
625
OnMicrophoneBlockedUpdate(DeviceType devType,DeviceBlockStatus status)626 void AudioDeviceLock::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status)
627 {
628 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
629 audioDeviceStatus_.OnMicrophoneBlockedUpdate(devType, status);
630 }
631
OnServiceDisconnected(AudioServiceIndex serviceIndex)632 void AudioDeviceLock::OnServiceDisconnected(AudioServiceIndex serviceIndex)
633 {
634 AUDIO_WARNING_LOG("Start for [%{public}d]", serviceIndex);
635 }
636
SetDisplayName(const std::string & deviceName,bool isLocalDevice)637 void AudioDeviceLock::SetDisplayName(const std::string &deviceName, bool isLocalDevice)
638 {
639 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
640 audioConnectedDevice_.SetDisplayName(deviceName, isLocalDevice);
641 }
642
UpdateSpatializationSupported(const std::string macAddress,const bool support)643 void AudioDeviceLock::UpdateSpatializationSupported(const std::string macAddress, const bool support)
644 {
645 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
646 audioConnectedDevice_.UpdateSpatializationSupported(macAddress, support);
647 }
648
SetDmDeviceType(const uint16_t dmDeviceType)649 void AudioDeviceLock::SetDmDeviceType(const uint16_t dmDeviceType)
650 {
651 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
652 audioConnectedDevice_.SetDmDeviceType(dmDeviceType);
653 }
654
TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)655 int32_t AudioDeviceLock::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)
656 {
657 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_);
658 audioDeviceCommon_.FetchDevice(true, reason);
659 audioDeviceCommon_.FetchDevice(false, reason);
660
661 // update a2dp offload
662 audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
663 return SUCCESS;
664 }
665
GetVolumeGroupInfos()666 std::vector<sptr<VolumeGroupInfo>> AudioDeviceLock::GetVolumeGroupInfos()
667 {
668 std::vector<sptr<VolumeGroupInfo>> infos = {};
669 for (int32_t i = 0; i < RETRY_TIMES; i++) {
670 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_);
671 if (audioVolumeManager_.GetVolumeGroupInfosNotWait(infos)) {
672 return infos;
673 } else {
674 deviceLock.unlock();
675 std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_LOAD_DEFAULT_DEVICE_TIME_MS));
676 }
677 }
678 AUDIO_ERR_LOG("timeout");
679 return infos;
680 }
681
682 }
683 }
684