1 /*
2  * Copyright (c) 2021-2023 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 "AudioBluetoothManager"
17 #endif
18 
19 #include "audio_bluetooth_manager.h"
20 #include "bluetooth_def.h"
21 #include "audio_errors.h"
22 #include "audio_common_log.h"
23 #include "audio_utils.h"
24 #include "bluetooth_audio_manager.h"
25 #include "bluetooth_device_manager.h"
26 #include "bluetooth_device_utils.h"
27 
28 namespace OHOS {
29 namespace Bluetooth {
30 using namespace AudioStandard;
31 
32 A2dpSource *AudioA2dpManager::a2dpInstance_ = nullptr;
33 std::shared_ptr<AudioA2dpListener> AudioA2dpManager::a2dpListener_ = std::make_shared<AudioA2dpListener>();
34 int AudioA2dpManager::connectionState_ = static_cast<int>(BTConnectState::DISCONNECTED);
35 BluetoothRemoteDevice AudioA2dpManager::activeA2dpDevice_;
36 std::mutex g_a2dpInstanceLock;
37 HandsFreeAudioGateway *AudioHfpManager::hfpInstance_ = nullptr;
38 std::shared_ptr<AudioHfpListener> AudioHfpManager::hfpListener_ = std::make_shared<AudioHfpListener>();
39 AudioScene AudioHfpManager::scene_ = AUDIO_SCENE_DEFAULT;
40 AudioScene AudioHfpManager::sceneFromPolicy_ = AUDIO_SCENE_DEFAULT;
41 OHOS::Bluetooth::ScoCategory AudioHfpManager::scoCategory = OHOS::Bluetooth::ScoCategory::SCO_DEFAULT;
42 OHOS::Bluetooth::RecognitionStatus AudioHfpManager::recognitionStatus =
43     OHOS::Bluetooth::RecognitionStatus::RECOGNITION_DISCONNECTED;
44 BluetoothRemoteDevice AudioHfpManager::activeHfpDevice_;
45 std::vector<std::shared_ptr<AudioA2dpPlayingStateChangedListener>> AudioA2dpManager::a2dpPlayingStateChangedListeners_;
46 std::mutex g_activehfpDeviceLock;
47 std::mutex g_audioSceneLock;
48 std::mutex g_hfpInstanceLock;
49 std::mutex g_a2dpPlayingStateChangedLock;
50 static const int32_t BT_SET_ACTIVE_DEVICE_TIMEOUT = 8; //BtService SetActiveDevice 8s timeout
51 
GetAudioStreamInfo(A2dpCodecInfo codecInfo, AudioStreamInfo &audioStreamInfo)52 static bool GetAudioStreamInfo(A2dpCodecInfo codecInfo, AudioStreamInfo &audioStreamInfo)
53 {
54     AUDIO_DEBUG_LOG("codec info rate[%{public}d]  format[%{public}d]  channel[%{public}d]",
55         codecInfo.sampleRate, codecInfo.bitsPerSample, codecInfo.channelMode);
56     switch (codecInfo.sampleRate) {
57         case A2DP_SBC_SAMPLE_RATE_48000_USER:
58         case A2DP_L2HCV2_SAMPLE_RATE_48000_USER:
59             audioStreamInfo.samplingRate = SAMPLE_RATE_48000;
60             break;
61         case A2DP_SBC_SAMPLE_RATE_44100_USER:
62             audioStreamInfo.samplingRate = SAMPLE_RATE_44100;
63             break;
64         case A2DP_SBC_SAMPLE_RATE_32000_USER:
65             audioStreamInfo.samplingRate = SAMPLE_RATE_32000;
66             break;
67         case A2DP_SBC_SAMPLE_RATE_16000_USER:
68             audioStreamInfo.samplingRate = SAMPLE_RATE_16000;
69             break;
70         case A2DP_L2HCV2_SAMPLE_RATE_96000_USER:
71             audioStreamInfo.samplingRate = SAMPLE_RATE_96000;
72             break;
73         default:
74             return false;
75     }
76     switch (codecInfo.bitsPerSample) {
77         case A2DP_SAMPLE_BITS_16_USER:
78             audioStreamInfo.format = SAMPLE_S16LE;
79             break;
80         case A2DP_SAMPLE_BITS_24_USER:
81             audioStreamInfo.format = SAMPLE_S24LE;
82             break;
83         case A2DP_SAMPLE_BITS_32_USER:
84             audioStreamInfo.format = SAMPLE_S32LE;
85             break;
86         default:
87             return false;
88     }
89     switch (codecInfo.channelMode) {
90         case A2DP_SBC_CHANNEL_MODE_STEREO_USER:
91             audioStreamInfo.channels = STEREO;
92             break;
93         case A2DP_SBC_CHANNEL_MODE_MONO_USER:
94             audioStreamInfo.channels = MONO;
95             break;
96         default:
97             return false;
98     }
99     audioStreamInfo.encoding = ENCODING_PCM;
100     return true;
101 }
102 
103 // LCOV_EXCL_START
RegisterBluetoothA2dpListener()104 void AudioA2dpManager::RegisterBluetoothA2dpListener()
105 {
106     AUDIO_INFO_LOG("AudioA2dpManager::RegisterBluetoothA2dpListener");
107     std::lock_guard<std::mutex> a2dpLock(g_a2dpInstanceLock);
108     a2dpInstance_ = A2dpSource::GetProfile();
109     CHECK_AND_RETURN_LOG(a2dpInstance_ != nullptr, "Failed to obtain A2DP profile instance");
110     a2dpInstance_->RegisterObserver(a2dpListener_);
111 }
112 
UnregisterBluetoothA2dpListener()113 void AudioA2dpManager::UnregisterBluetoothA2dpListener()
114 {
115     AUDIO_INFO_LOG("AudioA2dpManager::UnregisterBluetoothA2dpListener");
116     std::lock_guard<std::mutex> a2dpLock(g_a2dpInstanceLock);
117     CHECK_AND_RETURN_LOG(a2dpInstance_ != nullptr, "A2DP profile instance unavailable");
118     a2dpInstance_->DeregisterObserver(a2dpListener_);
119     a2dpInstance_ = nullptr;
120 }
121 
DisconnectBluetoothA2dpSink()122 void AudioA2dpManager::DisconnectBluetoothA2dpSink()
123 {
124     int connectionState = static_cast<int>(BTConnectState::DISCONNECTED);
125     auto a2dpList = MediaBluetoothDeviceManager::GetAllA2dpBluetoothDevice();
126     for (const auto &device : a2dpList) {
127         a2dpListener_->OnConnectionStateChanged(device, connectionState,
128             static_cast<uint32_t>(ConnChangeCause::CONNECT_CHANGE_COMMON_CAUSE));
129     }
130 
131     auto virtualDevices = MediaBluetoothDeviceManager::GetA2dpVirtualDeviceList();
132     for (const auto &virtualDevice : virtualDevices) {
133         a2dpListener_->OnVirtualDeviceChanged(static_cast<int32_t>(Bluetooth::BT_VIRTUAL_DEVICE_REMOVE),
134             virtualDevice.GetDeviceAddr());
135     }
136 
137     MediaBluetoothDeviceManager::ClearAllA2dpBluetoothDevice();
138 }
139 
SetActiveA2dpDevice(const std::string& macAddress)140 int32_t AudioA2dpManager::SetActiveA2dpDevice(const std::string& macAddress)
141 {
142     std::lock_guard<std::mutex> a2dpLock(g_a2dpInstanceLock);
143     AUDIO_INFO_LOG("incoming device:%{public}s, current device:%{public}s",
144         GetEncryptAddr(macAddress).c_str(), GetEncryptAddr(activeA2dpDevice_.GetDeviceAddr()).c_str());
145     a2dpInstance_ = A2dpSource::GetProfile();
146     CHECK_AND_RETURN_RET_LOG(a2dpInstance_ != nullptr, ERROR, "Failed to obtain A2DP profile instance");
147     BluetoothRemoteDevice device;
148     if (macAddress != "") {
149         int32_t tmp = MediaBluetoothDeviceManager::GetConnectedA2dpBluetoothDevice(macAddress, device);
150         CHECK_AND_RETURN_RET_LOG(tmp == SUCCESS, ERROR, "the configuring A2DP device doesn't exist.");
151     } else {
152         AUDIO_INFO_LOG("Deactive A2DP device");
153     }
154     int32_t ret = a2dpInstance_->SetActiveSinkDevice(device);
155     CHECK_AND_RETURN_RET_LOG(ret == 0, ERROR, "SetActiveA2dpDevice failed. result: %{public}d", ret);
156     activeA2dpDevice_ = device;
157     return SUCCESS;
158 }
159 
GetActiveA2dpDevice()160 std::string AudioA2dpManager::GetActiveA2dpDevice()
161 {
162     std::lock_guard<std::mutex> a2dpLock(g_a2dpInstanceLock);
163     a2dpInstance_ = A2dpSource::GetProfile();
164     CHECK_AND_RETURN_RET_LOG(a2dpInstance_ != nullptr, "", "Failed to obtain A2DP profile instance");
165     BluetoothRemoteDevice device = a2dpInstance_->GetActiveSinkDevice();
166     return device.GetDeviceAddr();
167 }
168 
SetDeviceAbsVolume(const std::string& macAddress, int32_t volume)169 int32_t AudioA2dpManager::SetDeviceAbsVolume(const std::string& macAddress, int32_t volume)
170 {
171     BluetoothRemoteDevice device;
172     int32_t ret = MediaBluetoothDeviceManager::GetConnectedA2dpBluetoothDevice(macAddress, device);
173     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "SetDeviceAbsVolume: the configuring A2DP device doesn't exist.");
174     return AvrcpTarget::GetProfile()->SetDeviceAbsoluteVolume(device, volume);
175 }
176 
GetA2dpDeviceStreamInfo(const std::string& macAddress, AudioStreamInfo &streamInfo)177 int32_t AudioA2dpManager::GetA2dpDeviceStreamInfo(const std::string& macAddress,
178     AudioStreamInfo &streamInfo)
179 {
180     std::lock_guard<std::mutex> a2dpLock(g_a2dpInstanceLock);
181     a2dpInstance_ = A2dpSource::GetProfile();
182     CHECK_AND_RETURN_RET_LOG(a2dpInstance_ != nullptr, ERROR, "Failed to obtain A2DP profile instance");
183     BluetoothRemoteDevice device;
184     int32_t ret = MediaBluetoothDeviceManager::GetConnectedA2dpBluetoothDevice(macAddress, device);
185     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR,
186         "GetA2dpDeviceStreamInfo: the configuring A2DP device doesn't exist.");
187     A2dpCodecStatus codecStatus = a2dpInstance_->GetCodecStatus(device);
188     bool result = GetAudioStreamInfo(codecStatus.codecInfo, streamInfo);
189     CHECK_AND_RETURN_RET_LOG(result, ERROR, "GetA2dpDeviceStreamInfo: Unsupported a2dp codec info");
190     return SUCCESS;
191 }
192 
HasA2dpDeviceConnected()193 bool AudioA2dpManager::HasA2dpDeviceConnected()
194 {
195     a2dpInstance_ = A2dpSource::GetProfile();
196     CHECK_AND_RETURN_RET(a2dpInstance_, false);
197     std::vector<int32_t> states {static_cast<int32_t>(BTConnectState::CONNECTED)};
198     std::vector<BluetoothRemoteDevice> devices;
199     a2dpInstance_->GetDevicesByStates(states, devices);
200 
201     return !devices.empty();
202 }
203 
A2dpOffloadSessionRequest(const std::vector<A2dpStreamInfo> &info)204 int32_t AudioA2dpManager::A2dpOffloadSessionRequest(const std::vector<A2dpStreamInfo> &info)
205 {
206     CHECK_AND_RETURN_RET_LOG(activeA2dpDevice_.GetDeviceAddr() != "00:00:00:00:00:00", A2DP_NOT_OFFLOAD,
207         "Invalid mac address, not request, return A2DP_NOT_OFFLOAD.");
208     int32_t ret = a2dpInstance_->A2dpOffloadSessionRequest(activeA2dpDevice_, info);
209     AUDIO_DEBUG_LOG("Request %{public}zu stream and return a2dp offload state %{public}d", info.size(), ret);
210     return ret;
211 }
212 
OffloadStartPlaying(const std::vector<int32_t> &sessionsID)213 int32_t AudioA2dpManager::OffloadStartPlaying(const std::vector<int32_t> &sessionsID)
214 {
215     CHECK_AND_RETURN_RET_LOG(activeA2dpDevice_.GetDeviceAddr() != "00:00:00:00:00:00", ERROR,
216         "Invalid mac address, not start, return error.");
217     AUDIO_DEBUG_LOG("Start playing %{public}zu stream", sessionsID.size());
218     return a2dpInstance_->OffloadStartPlaying(activeA2dpDevice_, sessionsID);
219 }
220 
OffloadStopPlaying(const std::vector<int32_t> &sessionsID)221 int32_t AudioA2dpManager::OffloadStopPlaying(const std::vector<int32_t> &sessionsID)
222 {
223     if (activeA2dpDevice_.GetDeviceAddr() == "00:00:00:00:00:00") {
224         AUDIO_DEBUG_LOG("Invalid mac address, not stop, return error.");
225         return ERROR;
226     }
227     AUDIO_DEBUG_LOG("Stop playing %{public}zu stream", sessionsID.size());
228     return a2dpInstance_->OffloadStopPlaying(activeA2dpDevice_, sessionsID);
229 }
230 
GetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp)231 int32_t AudioA2dpManager::GetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp)
232 {
233     if (activeA2dpDevice_.GetDeviceAddr() == "00:00:00:00:00:00") {
234         AUDIO_DEBUG_LOG("Invalid mac address, return error.");
235         return ERROR;
236     }
237     return a2dpInstance_->GetRenderPosition(activeA2dpDevice_, delayValue, sendDataSize, timeStamp);
238 }
239 
RegisterA2dpPlayingStateChangedListener( std::shared_ptr<AudioA2dpPlayingStateChangedListener> listener)240 int32_t AudioA2dpManager::RegisterA2dpPlayingStateChangedListener(
241     std::shared_ptr<AudioA2dpPlayingStateChangedListener> listener)
242 {
243     std::lock_guard<std::mutex> lock(g_a2dpPlayingStateChangedLock);
244     a2dpPlayingStateChangedListeners_.push_back(listener);
245     return SUCCESS;
246 }
247 
OnA2dpPlayingStateChanged(const std::string &deviceAddress, int32_t playingState)248 void AudioA2dpManager::OnA2dpPlayingStateChanged(const std::string &deviceAddress, int32_t playingState)
249 {
250     std::lock_guard<std::mutex> lock(g_a2dpPlayingStateChangedLock);
251     for (auto listener : a2dpPlayingStateChangedListeners_) {
252         listener->OnA2dpPlayingStateChanged(deviceAddress, playingState);
253     }
254 }
255 
CheckA2dpDeviceReconnect()256 void AudioA2dpManager::CheckA2dpDeviceReconnect()
257 {
258     if (a2dpInstance_ == nullptr) {
259         a2dpInstance_ = A2dpSource::GetProfile();
260     }
261     CHECK_AND_RETURN_LOG(a2dpInstance_ != nullptr, "A2DP profile instance unavailable");
262     std::vector<int32_t> states {static_cast<int32_t>(BTConnectState::CONNECTED)};
263     std::vector<BluetoothRemoteDevice> devices;
264     a2dpInstance_->GetDevicesByStates(states, devices);
265 
266     for (auto &device : devices) {
267         a2dpListener_->OnConnectionStateChanged(device, static_cast<int32_t>(BTConnectState::CONNECTED),
268             static_cast<uint32_t>(ConnChangeCause::CONNECT_CHANGE_COMMON_CAUSE));
269 
270         int32_t wearState = 0; // 0 unwear state
271         if (IsBTWearDetectionEnable(device)) {
272             wearState = BluetoothAudioManager::GetInstance().IsDeviceWearing(device);
273             if (wearState == 1) MediaBluetoothDeviceManager::SetMediaStack(device, WEAR_ACTION); // 1 wear state
274         }
275         AUDIO_INFO_LOG("reconnect a2dp device:%{public}s, wear state:%{public}d",
276             GetEncryptAddr(device.GetDeviceAddr()).c_str(), wearState);
277     }
278 
279     std::vector<std::string> virtualDevices;
280     a2dpInstance_->GetVirtualDeviceList(virtualDevices);
281     for (auto &macAddress : virtualDevices) {
282         AUDIO_PRERELEASE_LOGI("reconnect virtual a2dp device:%{public}s", GetEncryptAddr(macAddress).c_str());
283         a2dpListener_->OnVirtualDeviceChanged(static_cast<int32_t>(Bluetooth::BT_VIRTUAL_DEVICE_ADD), macAddress);
284     }
285 }
286 
Connect(const std::string &macAddress)287 int32_t AudioA2dpManager::Connect(const std::string &macAddress)
288 {
289     CHECK_AND_RETURN_RET_LOG(a2dpInstance_ != nullptr, ERROR, "A2DP profile instance unavailable");
290     BluetoothRemoteDevice virtualDevice = BluetoothRemoteDevice(macAddress);
291     if (MediaBluetoothDeviceManager::IsA2dpBluetoothDeviceConnecting(macAddress)) {
292         AUDIO_PRERELEASE_LOGI("A2dp device %{public}s is connecting, ignore connect request", macAddress.c_str());
293         virtualDevice.SetVirtualAutoConnectType(CONN_REASON_MANUAL_VIRTUAL_CONNECT_PREEMPT_FLAG, 0);
294         return SUCCESS;
295     }
296     std::vector<std::string> virtualDevices;
297     a2dpInstance_->GetVirtualDeviceList(virtualDevices);
298     if (std::find(virtualDevices.begin(), virtualDevices.end(), macAddress) == virtualDevices.end()) {
299         AUDIO_PRERELEASE_LOGI("A2dp device %{public}s is not virtual device, ignore connect request",
300             macAddress.c_str());
301         return SUCCESS;
302     }
303     int32_t ret = a2dpInstance_->Connect(virtualDevice);
304     CHECK_AND_RETURN_RET_LOG(ret == 0, ERROR, "A2dp Connect Failed");
305     virtualDevice.SetVirtualAutoConnectType(CONN_REASON_MANUAL_VIRTUAL_CONNECT_PREEMPT_FLAG, 0);
306     return SUCCESS;
307 }
308 
OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state, int cause)309 void AudioA2dpListener::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state, int cause)
310 {
311     AUDIO_INFO_LOG("AudioA2dpListener OnConnectionStateChanged: state: %{public}d", state);
312     // Record connection state and device for hdi start time to check
313     AudioA2dpManager::SetConnectionState(state);
314     if (state == static_cast<int>(BTConnectState::CONNECTING)) {
315         MediaBluetoothDeviceManager::SetMediaStack(device, BluetoothDeviceAction::CONNECTING_ACTION);
316     }
317     if (state == static_cast<int>(BTConnectState::CONNECTED)) {
318         MediaBluetoothDeviceManager::SetMediaStack(device, BluetoothDeviceAction::CONNECT_ACTION);
319     }
320     if (state == static_cast<int>(BTConnectState::DISCONNECTED)) {
321         MediaBluetoothDeviceManager::SetMediaStack(device, BluetoothDeviceAction::DISCONNECT_ACTION);
322     }
323 }
324 
OnConfigurationChanged(const BluetoothRemoteDevice &device, const A2dpCodecInfo &codecInfo, int error)325 void AudioA2dpListener::OnConfigurationChanged(const BluetoothRemoteDevice &device, const A2dpCodecInfo &codecInfo,
326     int error)
327 {
328     AUDIO_INFO_LOG("OnConfigurationChanged: sampleRate: %{public}d, channels: %{public}d, format: %{public}d",
329         codecInfo.sampleRate, codecInfo.channelMode, codecInfo.bitsPerSample);
330     AudioStreamInfo streamInfo = {};
331     bool result = GetAudioStreamInfo(codecInfo, streamInfo);
332     CHECK_AND_RETURN_LOG(result, "OnConfigurationChanged: Unsupported a2dp codec info");
333     MediaBluetoothDeviceManager::UpdateA2dpDeviceConfiguration(device, streamInfo);
334 }
335 
OnPlayingStatusChanged(const BluetoothRemoteDevice &device, int playingState, int error)336 void AudioA2dpListener::OnPlayingStatusChanged(const BluetoothRemoteDevice &device, int playingState, int error)
337 {
338     AUDIO_INFO_LOG("OnPlayingStatusChanged, state: %{public}d, error: %{public}d", playingState, error);
339     if (error == SUCCESS) {
340         AudioA2dpManager::OnA2dpPlayingStateChanged(device.GetDeviceAddr(), playingState);
341     }
342 }
343 
OnMediaStackChanged(const BluetoothRemoteDevice &device, int action)344 void AudioA2dpListener::OnMediaStackChanged(const BluetoothRemoteDevice &device, int action)
345 {
346     AUDIO_INFO_LOG("OnMediaStackChanged, action: %{public}d", action);
347     MediaBluetoothDeviceManager::SetMediaStack(device, action);
348 }
349 
OnVirtualDeviceChanged(int32_t action, std::string macAddress)350 void AudioA2dpListener::OnVirtualDeviceChanged(int32_t action, std::string macAddress)
351 {
352     AUDIO_INFO_LOG("AudioA2dpListener: action: %{public}d", action);
353     if (action == static_cast<int32_t>(Bluetooth::BT_VIRTUAL_DEVICE_ADD)) {
354         MediaBluetoothDeviceManager::SetMediaStack(BluetoothRemoteDevice(macAddress),
355             BluetoothDeviceAction::VIRTUAL_DEVICE_ADD_ACTION);
356     }
357     if (action == static_cast<int32_t>(Bluetooth::BT_VIRTUAL_DEVICE_REMOVE)) {
358         MediaBluetoothDeviceManager::SetMediaStack(BluetoothRemoteDevice(macAddress),
359             BluetoothDeviceAction::VIRTUAL_DEVICE_REMOVE_ACTION);
360     }
361 }
362 
RegisterBluetoothScoListener()363 void AudioHfpManager::RegisterBluetoothScoListener()
364 {
365     AUDIO_INFO_LOG("AudioHfpManager::RegisterBluetoothScoListener");
366     std::lock_guard<std::mutex> hfpLock(g_hfpInstanceLock);
367     hfpInstance_ = HandsFreeAudioGateway::GetProfile();
368     CHECK_AND_RETURN_LOG(hfpInstance_ != nullptr, "Failed to obtain HFP AG profile instance");
369 
370     hfpInstance_->RegisterObserver(hfpListener_);
371 }
372 
UnregisterBluetoothScoListener()373 void AudioHfpManager::UnregisterBluetoothScoListener()
374 {
375     AUDIO_INFO_LOG("AudioHfpManager::UnregisterBluetoothScoListene");
376     std::lock_guard<std::mutex> hfpLock(g_hfpInstanceLock);
377     CHECK_AND_RETURN_LOG(hfpInstance_ != nullptr, "HFP AG profile instance unavailable");
378 
379     hfpInstance_->DeregisterObserver(hfpListener_);
380     hfpInstance_ = nullptr;
381 }
382 
CheckHfpDeviceReconnect()383 void AudioHfpManager::CheckHfpDeviceReconnect()
384 {
385     if (hfpInstance_ == nullptr) {
386         hfpInstance_ = HandsFreeAudioGateway::GetProfile();
387     }
388     CHECK_AND_RETURN_LOG(hfpInstance_ != nullptr, "HFP profile instance unavailable");
389     std::vector<int32_t> states {static_cast<int32_t>(BTConnectState::CONNECTED)};
390     std::vector<BluetoothRemoteDevice> devices = hfpInstance_->GetDevicesByStates(states);
391     for (auto &device : devices) {
392         hfpListener_->OnConnectionStateChanged(device, static_cast<int32_t>(BTConnectState::CONNECTED),
393             static_cast<uint32_t>(ConnChangeCause::CONNECT_CHANGE_COMMON_CAUSE));
394 
395         int32_t wearState = 0; // 0 unwear state
396         if (IsBTWearDetectionEnable(device)) {
397             wearState = BluetoothAudioManager::GetInstance().IsDeviceWearing(device);
398             if (wearState == 1) HfpBluetoothDeviceManager::SetHfpStack(device, WEAR_ACTION); // 1 wear state
399         }
400         AUDIO_INFO_LOG("reconnect hfp device:%{public}s, wear state:%{public}d",
401             GetEncryptAddr(device.GetDeviceAddr()).c_str(), wearState);
402     }
403 
404     std::vector<std::string> virtualDevices;
405     hfpInstance_->GetVirtualDeviceList(virtualDevices);
406     for (auto &macAddress : virtualDevices) {
407         AUDIO_PRERELEASE_LOGI("reconnect virtual hfp device:%{public}s", GetEncryptAddr(macAddress).c_str());
408         hfpListener_->OnVirtualDeviceChanged(static_cast<int32_t>(Bluetooth::BT_VIRTUAL_DEVICE_ADD), macAddress);
409     }
410 }
411 
HandleScoWithRecongnition(bool handleFlag, BluetoothRemoteDevice &device)412 int32_t AudioHfpManager::HandleScoWithRecongnition(bool handleFlag, BluetoothRemoteDevice &device)
413 {
414     CHECK_AND_RETURN_RET_LOG(hfpInstance_ != nullptr, ERROR, "HFP AG profile instance unavailable");
415     bool ret = true;
416     if (handleFlag) {
417         int8_t scoCategory = GetScoCategoryFromScene(scene_);
418         if (scoCategory == ScoCategory::SCO_DEFAULT &&
419             AudioHfpManager::scoCategory != ScoCategory::SCO_RECOGNITION) {
420             AUDIO_INFO_LOG("Recongnition sco connect");
421             AudioHfpManager::recognitionStatus = RecognitionStatus::RECOGNITION_CONNECTING;
422             ret = hfpInstance_->OpenVoiceRecognition(device);
423             if (ret) {
424                 AudioHfpManager::scoCategory = ScoCategory::SCO_RECOGNITION;
425                 AudioHfpManager::recognitionStatus = RecognitionStatus::RECOGNITION_CONNECTED;
426             }
427         } else {
428             AUDIO_INFO_LOG("Sco Connected OR Connecting, No Need to Create");
429         }
430     } else {
431         if (AudioHfpManager::scoCategory == ScoCategory::SCO_RECOGNITION) {
432             AUDIO_INFO_LOG("Recongnition sco close");
433             AudioHfpManager::recognitionStatus = RecognitionStatus::RECOGNITION_DISCONNECTING;
434             ret = hfpInstance_->CloseVoiceRecognition(device);
435             if (ret) {
436                 AudioHfpManager::scoCategory = ScoCategory::SCO_DEFAULT;
437                 AudioHfpManager::recognitionStatus = RecognitionStatus::RECOGNITION_DISCONNECTED;
438             }
439         }
440     }
441     CHECK_AND_RETURN_RET_LOG(ret == true, ERROR, "HandleScoWithRecongnition failed, result: %{public}d", ret);
442     return SUCCESS;
443 }
444 
ClearRecongnitionStatus()445 void AudioHfpManager::ClearRecongnitionStatus()
446 {
447     if (AudioHfpManager::scoCategory == ScoCategory::SCO_RECOGNITION) {
448         AudioHfpManager::scoCategory = ScoCategory::SCO_DEFAULT;
449         AudioHfpManager::recognitionStatus = RecognitionStatus::RECOGNITION_DISCONNECTED;
450     }
451 }
452 
GetScoCategory()453 ScoCategory AudioHfpManager::GetScoCategory()
454 {
455     return scoCategory;
456 }
457 
GetRecognitionStatus()458 RecognitionStatus AudioHfpManager::GetRecognitionStatus()
459 {
460     return recognitionStatus;
461 }
462 
SetActiveHfpDevice(const std::string &macAddress)463 int32_t AudioHfpManager::SetActiveHfpDevice(const std::string &macAddress)
464 {
465     AudioXCollie audioXCollie("AudioHfpManager::SetActiveHfpDevice", BT_SET_ACTIVE_DEVICE_TIMEOUT,
466         nullptr, nullptr, AUDIO_XCOLLIE_FLAG_LOG | AUDIO_XCOLLIE_FLAG_RECOVERY);
467     BluetoothRemoteDevice device;
468     if (HfpBluetoothDeviceManager::GetConnectedHfpBluetoothDevice(macAddress, device) != SUCCESS) {
469         AUDIO_ERR_LOG("SetActiveHfpDevice failed for the HFP device %{public}s does not exist.",
470             GetEncryptAddr(macAddress).c_str());
471         return ERROR;
472     }
473     std::lock_guard<std::mutex> hfpDeviceLock(g_activehfpDeviceLock);
474     AUDIO_INFO_LOG("incoming device:%{public}s, current device:%{public}s",
475         GetEncryptAddr(macAddress).c_str(), GetEncryptAddr(activeHfpDevice_.GetDeviceAddr()).c_str());
476     if (macAddress != activeHfpDevice_.GetDeviceAddr()) {
477         AUDIO_INFO_LOG("Active hfp device is changed, need to DisconnectSco for current activeHfpDevice.");
478         int32_t ret = DisconnectSco();
479         CHECK_AND_RETURN_RET_LOG(ret == 0, ERROR, "DisconnectSco failed, result: %{public}d", ret);
480     }
481     std::lock_guard<std::mutex> hfpLock(g_hfpInstanceLock);
482     CHECK_AND_RETURN_RET_LOG(hfpInstance_ != nullptr, ERROR, "HFP AG profile instance unavailable");
483     bool res = hfpInstance_->SetActiveDevice(device);
484     CHECK_AND_RETURN_RET_LOG(res == true, ERROR, "SetActiveHfpDevice failed, result: %{public}d", res);
485     activeHfpDevice_ = device;
486     return SUCCESS;
487 }
488 
GetActiveHfpDevice()489 std::string AudioHfpManager::GetActiveHfpDevice()
490 {
491     std::lock_guard<std::mutex> hfpLock(g_hfpInstanceLock);
492     CHECK_AND_RETURN_RET_LOG(hfpInstance_ != nullptr, "", "HFP AG profile instance unavailable");
493     BluetoothRemoteDevice device = hfpInstance_->GetActiveDevice();
494     return device.GetDeviceAddr();
495 }
496 
ConnectScoWithAudioScene(AudioScene scene)497 int32_t AudioHfpManager::ConnectScoWithAudioScene(AudioScene scene)
498 {
499     if (scoCategory == ScoCategory::SCO_RECOGNITION) {
500         AUDIO_INFO_LOG("Recognition Sco Connected");
501         return SUCCESS;
502     }
503 
504     std::lock_guard<std::mutex> sceneLock(g_audioSceneLock);
505     int8_t lastScoCategory = GetScoCategoryFromScene(scene_);
506     int8_t newScoCategory = GetScoCategoryFromScene(scene);
507     AUDIO_INFO_LOG("new sco category is %{public}d, last sco category is %{public}d", newScoCategory, lastScoCategory);
508 
509     if (lastScoCategory == newScoCategory) {
510         return SUCCESS;
511     }
512     std::lock_guard<std::mutex> hfpLock(g_hfpInstanceLock);
513     CHECK_AND_RETURN_RET_LOG(hfpInstance_ != nullptr, ERROR, "HFP AG profile instance unavailable");
514     bool isInbardingEnabled = false;
515     hfpInstance_->IsInbandRingingEnabled(isInbardingEnabled);
516     if ((scene == AUDIO_SCENE_RINGING || scene == AUDIO_SCENE_VOICE_RINGING) && !isInbardingEnabled) {
517         AUDIO_INFO_LOG("The inbarding switch is off, ignore the ring scene.");
518         return SUCCESS;
519     }
520     int32_t ret;
521     if (lastScoCategory != ScoCategory::SCO_DEFAULT) {
522         AUDIO_INFO_LOG("Entered to disConnectSco for last audioScene category.");
523         ret = hfpInstance_->DisconnectSco(static_cast<uint8_t>(lastScoCategory));
524         CHECK_AND_RETURN_RET_LOG(ret == 0, ERROR,
525             "ConnectScoWithAudioScene failed as the last SCO failed to be disconnected, result: %{public}d", ret);
526     }
527     if (newScoCategory != ScoCategory::SCO_DEFAULT) {
528         AUDIO_INFO_LOG("Entered to connectSco for new audioScene category.");
529         ret = hfpInstance_->ConnectSco(static_cast<uint8_t>(newScoCategory));
530         CHECK_AND_RETURN_RET_LOG(ret == 0, ERROR, "ConnectScoWithAudioScene failed, result: %{public}d", ret);
531     }
532     scene_ = scene;
533     return SUCCESS;
534 }
535 
DisconnectSco()536 int32_t AudioHfpManager::DisconnectSco()
537 {
538     std::lock_guard<std::mutex> sceneLock(g_audioSceneLock);
539     int8_t currentScoCategory = GetScoCategoryFromScene(scene_);
540     if (currentScoCategory == ScoCategory::SCO_DEFAULT) {
541         AUDIO_INFO_LOG("Current sco category is DEFAULT, not need to disconnect sco.");
542         return SUCCESS;
543     }
544     AUDIO_INFO_LOG("current sco category %{public}d", currentScoCategory);
545 
546     std::lock_guard<std::mutex> hfpLock(g_hfpInstanceLock);
547     CHECK_AND_RETURN_RET_LOG(hfpInstance_ != nullptr, ERROR, "HFP AG profile instance unavailable");
548     int32_t ret = hfpInstance_->DisconnectSco(static_cast<uint8_t>(currentScoCategory));
549     CHECK_AND_RETURN_RET_LOG(ret == 0, ERROR, "DisconnectSco failed, result: %{public}d", ret);
550     scene_ = AUDIO_SCENE_DEFAULT;
551     return SUCCESS;
552 }
553 
GetScoCategoryFromScene(AudioScene scene)554 int8_t AudioHfpManager::GetScoCategoryFromScene(AudioScene scene)
555 {
556     switch (scene) {
557         case AUDIO_SCENE_VOICE_RINGING:
558         case AUDIO_SCENE_PHONE_CALL:
559             return ScoCategory::SCO_CALLULAR;
560         case AUDIO_SCENE_RINGING:
561         case AUDIO_SCENE_PHONE_CHAT:
562             return ScoCategory::SCO_VIRTUAL;
563         default:
564             return ScoCategory::SCO_DEFAULT;
565     }
566 }
567 
DisconnectBluetoothHfpSink()568 void AudioHfpManager::DisconnectBluetoothHfpSink()
569 {
570     int connectionState = static_cast<int>(BTConnectState::DISCONNECTED);
571     auto hfpList = HfpBluetoothDeviceManager::GetAllHfpBluetoothDevice();
572     for (const auto &device : hfpList) {
573         hfpListener_->OnConnectionStateChanged(device, connectionState,
574             static_cast<uint32_t>(ConnChangeCause::CONNECT_CHANGE_COMMON_CAUSE));
575     }
576 
577     auto virtualDevices = HfpBluetoothDeviceManager::GetHfpVirtualDeviceList();
578     for (const auto &virtualDevice : virtualDevices) {
579         hfpListener_->OnVirtualDeviceChanged(static_cast<int32_t>(Bluetooth::BT_VIRTUAL_DEVICE_REMOVE),
580             virtualDevice.GetDeviceAddr());
581     }
582     HfpBluetoothDeviceManager::ClearAllHfpBluetoothDevice();
583 }
584 
UpdateCurrentActiveHfpDevice(const BluetoothRemoteDevice &device)585 void AudioHfpManager::UpdateCurrentActiveHfpDevice(const BluetoothRemoteDevice &device)
586 {
587     std::lock_guard<std::mutex> hfpDeviceLock(g_activehfpDeviceLock);
588     activeHfpDevice_ = device;
589 }
590 
GetCurrentActiveHfpDevice()591 std::string AudioHfpManager::GetCurrentActiveHfpDevice()
592 {
593     std::lock_guard<std::mutex> hfpDeviceLock(g_activehfpDeviceLock);
594     return activeHfpDevice_.GetDeviceAddr();
595 }
596 
UpdateAudioScene(AudioScene scene)597 void AudioHfpManager::UpdateAudioScene(AudioScene scene)
598 {
599     std::lock_guard<std::mutex> sceneLock(g_audioSceneLock);
600     scene_ = scene;
601 }
602 
GetCurrentAudioScene()603 AudioStandard::AudioScene AudioHfpManager::GetCurrentAudioScene()
604 {
605     std::lock_guard<std::mutex> sceneLock(g_audioSceneLock);
606     return scene_;
607 }
608 
SetAudioSceneFromPolicy(AudioScene scene)609 void AudioHfpManager::SetAudioSceneFromPolicy(AudioScene scene)
610 {
611     sceneFromPolicy_ = scene;
612 }
613 
GetPolicyAudioScene()614 AudioStandard::AudioScene AudioHfpManager::GetPolicyAudioScene()
615 {
616     return sceneFromPolicy_;
617 }
618 
Connect(const std::string &macAddress)619 int32_t AudioHfpManager::Connect(const std::string &macAddress)
620 {
621     CHECK_AND_RETURN_RET_LOG(hfpInstance_ != nullptr, ERROR, "HFP AG profile instance unavailable");
622     BluetoothRemoteDevice virtualDevice = BluetoothRemoteDevice(macAddress);
623     if (HfpBluetoothDeviceManager::IsHfpBluetoothDeviceConnecting(macAddress)) {
624         AUDIO_PRERELEASE_LOGI("Hfp device %{public}s is connecting, ignore connect request", macAddress.c_str());
625         virtualDevice.SetVirtualAutoConnectType(CONN_REASON_MANUAL_VIRTUAL_CONNECT_PREEMPT_FLAG, 0);
626         return SUCCESS;
627     }
628     std::vector<std::string> virtualDevices;
629     hfpInstance_->GetVirtualDeviceList(virtualDevices);
630     if (std::find(virtualDevices.begin(), virtualDevices.end(), macAddress) == virtualDevices.end()) {
631         AUDIO_PRERELEASE_LOGI("Hfp device %{public}s is not virtual device, ignore connect request",
632             macAddress.c_str());
633         return SUCCESS;
634     }
635     int32_t ret = hfpInstance_->Connect(virtualDevice);
636     CHECK_AND_RETURN_RET_LOG(ret == 0, ERROR, "Hfp Connect Failed");
637     virtualDevice.SetVirtualAutoConnectType(CONN_REASON_MANUAL_VIRTUAL_CONNECT_PREEMPT_FLAG, 0);
638     return SUCCESS;
639 }
640 
OnScoStateChanged(const BluetoothRemoteDevice &device, int state, int reason)641 void AudioHfpListener::OnScoStateChanged(const BluetoothRemoteDevice &device, int state, int reason)
642 {
643     AUDIO_INFO_LOG("AudioHfpListener::OnScoStateChanged: state:[%{public}d] reason:[%{public}d] device:[%{public}s]",
644         state, reason, GetEncryptAddr(device.GetDeviceAddr()).c_str());
645     // SCO_DISCONNECTED = 3, SCO_CONNECTING = 4, SCO_DISCONNECTING = 5, SCO_CONNECTED = 6
646     HfpScoConnectState scoState = static_cast<HfpScoConnectState>(state);
647     if (scoState == HfpScoConnectState::SCO_CONNECTED || scoState == HfpScoConnectState::SCO_DISCONNECTED) {
648         if (device.GetDeviceAddr() == AudioHfpManager::GetCurrentActiveHfpDevice() &&
649             scoState == HfpScoConnectState::SCO_DISCONNECTED) {
650             BluetoothRemoteDevice defaultDevice;
651             AudioHfpManager::UpdateCurrentActiveHfpDevice(defaultDevice);
652             AUDIO_INFO_LOG("Sco disconnect, need set audio scene as default.");
653             AudioHfpManager::UpdateAudioScene(AUDIO_SCENE_DEFAULT);
654         } else if (scoState == HfpScoConnectState::SCO_CONNECTED) {
655             AudioScene audioScene = AudioHfpManager::GetPolicyAudioScene();
656             if (audioScene != AudioHfpManager::GetCurrentAudioScene()) {
657                 AUDIO_INFO_LOG("Sco connect by peripheral device, update scene_ %{public}d", audioScene);
658                 AudioHfpManager::UpdateAudioScene(audioScene);
659             }
660             AudioHfpManager::UpdateCurrentActiveHfpDevice(device);
661         }
662         bool isConnected = (scoState == HfpScoConnectState::SCO_CONNECTED) ? true : false;
663         HfpBluetoothDeviceManager::OnScoStateChanged(device, isConnected, reason);
664     }
665 }
666 
OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state, int cause)667 void AudioHfpListener::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state, int cause)
668 {
669     AUDIO_INFO_LOG("AudioHfpListener::OnConnectionStateChanged: state: %{public}d", state);
670     if (state == static_cast<int>(BTConnectState::CONNECTING)) {
671         HfpBluetoothDeviceManager::SetHfpStack(device, BluetoothDeviceAction::CONNECTING_ACTION);
672     }
673     if (state == static_cast<int>(BTConnectState::CONNECTED)) {
674         HfpBluetoothDeviceManager::SetHfpStack(device, BluetoothDeviceAction::CONNECT_ACTION);
675     }
676     if (state == static_cast<int>(BTConnectState::DISCONNECTED)) {
677         if (device.GetDeviceAddr() == AudioHfpManager::GetCurrentActiveHfpDevice()) {
678             BluetoothRemoteDevice defaultDevice;
679             AudioHfpManager::UpdateCurrentActiveHfpDevice(defaultDevice);
680             AUDIO_INFO_LOG("Current active hfp device diconnect, need set audio scene as default.");
681             AudioHfpManager::UpdateAudioScene(AUDIO_SCENE_DEFAULT);
682         }
683         HfpBluetoothDeviceManager::SetHfpStack(device, BluetoothDeviceAction::DISCONNECT_ACTION);
684     }
685 }
686 
OnHfpStackChanged(const BluetoothRemoteDevice &device, int action)687 void AudioHfpListener::OnHfpStackChanged(const BluetoothRemoteDevice &device, int action)
688 {
689     AUDIO_INFO_LOG("OnHfpStackChanged, action: %{public}d device: %{public}s",
690         action, GetEncryptAddr(device.GetDeviceAddr()).c_str());
691     HfpBluetoothDeviceManager::SetHfpStack(device, action);
692 }
693 
OnVirtualDeviceChanged(int32_t action, std::string macAddress)694 void AudioHfpListener::OnVirtualDeviceChanged(int32_t action, std::string macAddress)
695 {
696     AUDIO_INFO_LOG("AudioHfpListener: action: %{public}d", action);
697     if (action == static_cast<int32_t>(Bluetooth::BT_VIRTUAL_DEVICE_ADD)) {
698         HfpBluetoothDeviceManager::SetHfpStack(BluetoothRemoteDevice(macAddress),
699             BluetoothDeviceAction::VIRTUAL_DEVICE_ADD_ACTION);
700     }
701     if (action == static_cast<int32_t>(Bluetooth::BT_VIRTUAL_DEVICE_REMOVE)) {
702         HfpBluetoothDeviceManager::SetHfpStack(BluetoothRemoteDevice(macAddress),
703             BluetoothDeviceAction::VIRTUAL_DEVICE_REMOVE_ACTION);
704     }
705 }
706 // LCOV_EXCL_STOP
707 } // namespace Bluetooth
708 } // namespace OHOS
709