• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "a2dp_service.h"
17 
18 #include <cstring>
19 #include "adapter_config.h"
20 #include "class_creator.h"
21 #include "log.h"
22 #include "log_util.h"
23 #include "profile_config.h"
24 #include "profile_service_manager.h"
25 #include "securec.h"
26 #include "idevmgr_hdi.h"
27 
28 constexpr const char *AUDIO_BLUETOOTH_SERVICE_NAME = "audio_bluetooth_hdi_service";
29 
30 namespace OHOS {
31 namespace bluetooth {
32 std::recursive_mutex g_a2dpServiceMutex {};
ObserverProfile(uint8_t role)33 ObserverProfile::ObserverProfile(uint8_t role)
34 {
35     role_ = role;
36 }
37 
OnConnectStateChanged(const BtAddr & addr,const int state,void * context)38 void ObserverProfile::OnConnectStateChanged(const BtAddr &addr, const int state, void *context)
39 {
40     LOG_INFO("[ObserverProfile] %{public}s: state[%{public}d] role[%u]\n", __func__, state, role_);
41 
42     A2dpService *service = GetServiceInstance(role_);
43     A2dpProfile *pflA2dp = GetProfileInstance(role_);
44 
45     if (service == nullptr || pflA2dp == nullptr) {
46         LOG_INFO("[ObserverProfile] %{public}s Can't get the instance of service\n", __func__);
47         return;
48     }
49 
50     RawAddress btAddr = bluetooth::RawAddress::ConvertToString(addr.addr);
51     A2dpDeviceInfo *deviceInfo = service->GetDeviceFromList(btAddr);
52     if (deviceInfo == nullptr) {
53         if (((static_cast<CallbackParameter*>(context))->role) == A2DP_ROLE_ACP && (state == STREAM_CONNECTING)) {
54             service->ConnectManager().AddDevice(btAddr, static_cast<int>(BTConnectState::CONNECTING));
55             service->ProcessConnectFrameworkCallback(static_cast<int>(BTConnectState::CONNECTING), btAddr);
56         }
57         return;
58     }
59     int connectPolicy = service->GetConnectStrategy(btAddr);
60     int connectState = ProcessConnectStateMessage(btAddr, deviceInfo, connectPolicy, state,
61         (static_cast<CallbackParameter*>(context))->handle);
62     HILOGI("Active device(%{public}s)", GetEncryptAddr(service->GetActiveSinkDevice().GetAddress()).c_str());
63 
64     if (connectState == static_cast<int>(BTConnectState::DISCONNECTED)) {
65         if (strcmp(btAddr.GetAddress().c_str(), service->GetActiveSinkDevice().GetAddress().c_str()) == 0) {
66             LOG_INFO("[ObserverProfile] %{public}s Remove the active device\n", __func__);
67             RawAddress removeActive("");
68             service->UpdateActiveDevice(removeActive);
69         }
70         service->ConnectManager().DeleteDevice(btAddr);
71     } else if (connectState == static_cast<int>(BTConnectState::CONNECTED)) {
72         LOG_INFO("[ObserverProfile] %{public}s Add the active device\n", __func__);
73         service->UpdateActiveDevice(btAddr);
74     }
75 
76     if ((connectState == static_cast<int>(BTConnectState::CONNECTED)) ||
77         (connectState == static_cast<int>(BTConnectState::DISCONNECTED))) {
78         service->ProcessConnectFrameworkCallback(connectState, btAddr);
79         ProcessA2dpHdfLoad(connectState);
80     }
81 
82     service->CheckDisable();
83     return;
84 }
85 
ProcessA2dpHdfLoad(const int state) const86 void ObserverProfile::ProcessA2dpHdfLoad(const int state) const
87 {
88     LOG_INFO("[ObserverProfile] %{public}s state:%{public}d \n", __func__, state);
89     A2dpService *service = GetServiceInstance(role_);
90     std::vector<int> states = {static_cast<int>(BTConnectState::CONNECTED)};
91     std::vector<RawAddress> devices = service->GetDevicesByStates(states);
92 
93     if (state == static_cast<int>(BTConnectState::CONNECTED) && devices.size() == 1) {
94         auto devmgr = OHOS::HDI::DeviceManager::V1_0::IDeviceManager::Get();
95         if (devmgr != nullptr) {
96             LOG_INFO("[ObserverProfile] %{public}s, loadDevice of a2dp HDF", __func__);
97             devmgr->LoadDevice(AUDIO_BLUETOOTH_SERVICE_NAME);
98         }
99     }
100     if (state == static_cast<int>(BTConnectState::DISCONNECTED) && devices.size() == 0) {
101         auto devmgr = OHOS::HDI::DeviceManager::V1_0::IDeviceManager::Get();
102         if (devmgr != nullptr) {
103             LOG_INFO("[ObserverProfile] %{public}s, UnloadDevice of a2dp HDF", __func__);
104             devmgr->UnloadDevice(AUDIO_BLUETOOTH_SERVICE_NAME);
105         }
106     }
107 }
108 
ProcessConnectStateMessage(RawAddress btAddr,A2dpDeviceInfo * deviceInfo,const int connectPolicy,const int state,const uint16_t handle)109 int ObserverProfile::ProcessConnectStateMessage(
110     RawAddress btAddr, A2dpDeviceInfo *deviceInfo, const int connectPolicy, const int state, const uint16_t handle)
111 {
112     LOG_INFO("[ObserverProfile] %{public}s \n", __func__);
113     int connectState = RET_BAD_STATUS;
114     utility::Message msg(A2DP_MSG_PROFILE_DISCONNECTED, role_, &(btAddr));
115     switch (state) {
116         case STREAM_CONNECT:
117             if ((int)BTStrategyType::CONNECTION_FORBIDDEN == connectPolicy) {
118                 UpdateStateInformation(
119                     msg, connectState, A2DP_MSG_CONNECT_FORBIDDEN, static_cast<int>(BTConnectState::CONNECTING));
120             } else {
121                 deviceInfo->SetHandle(handle);
122                 UpdateStateInformation(
123                     msg, connectState, A2DP_MSG_PROFILE_CONNECTED, static_cast<int>(BTConnectState::CONNECTED));
124             }
125             break;
126         case STREAM_CONNECTING:
127             if ((int)BTStrategyType::CONNECTION_FORBIDDEN == connectPolicy) {
128                 UpdateStateInformation(
129                     msg, connectState, A2DP_MSG_CONNECT_FORBIDDEN, static_cast<int>(BTConnectState::CONNECTING));
130             } else {
131                 UpdateStateInformation(
132                     msg, connectState, A2DP_MSG_PROFILE_CONNECTING, static_cast<int>(BTConnectState::CONNECTING));
133             }
134             break;
135         case STREAM_DISCONNECT:
136             UpdateStateInformation(
137                 msg, connectState, A2DP_MSG_PROFILE_DISCONNECTED, static_cast<int>(BTConnectState::DISCONNECTED));
138             break;
139         case STREAM_DISCONNECTING:
140             UpdateStateInformation(
141                 msg, connectState, A2DP_MSG_PROFILE_DISCONNECTING, static_cast<int>(BTConnectState::DISCONNECTING));
142             break;
143         case STREAM_CONNECT_FAILED:
144             UpdateStateInformation(
145                 msg, connectState, A2DP_MSG_PROFILE_DISCONNECTED, static_cast<int>(BTConnectState::DISCONNECTED));
146             break;
147         default:
148             break;
149     }
150     if (connectState != RET_BAD_STATUS) {
151         deviceInfo->SetConnectState(connectState);
152         if (static_cast<int>(BTConnectState::DISCONNECTED) == connectState && deviceInfo->GetPlayingState()) {
153             deviceInfo->SetPlayingState(false);
154         }
155         deviceInfo->GetStateMachine()->ProcessMessage(msg);
156     }
157     return connectState;
158 }
159 
UpdateStateInformation(utility::Message & msg,int & state,const int msgCMD,const int stateValue)160 void ObserverProfile::UpdateStateInformation(utility::Message &msg, int &state,
161     const int msgCMD, const int stateValue)
162 {
163     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
164 
165     LOG_INFO("[ObserverProfile] %{public}s msgCMD(%{public}d) stateValue(%{public}d)\n", __func__, msgCMD, stateValue);
166     msg.what_ = msgCMD;
167     state = stateValue;
168 }
169 
OnAudioStateChanged(const BtAddr & addr,const int state,void * context)170 void ObserverProfile::OnAudioStateChanged(const BtAddr &addr, const int state, void *context)
171 {
172     LOG_INFO("[ObserverProfile] %{public}s role(%u) state(%{public}d)\n", __func__, role_, state);
173 
174     A2dpService *service = GetServiceInstance(role_);
175     RawAddress btAddr = bluetooth::RawAddress::ConvertToString(addr.addr);
176     int error = RET_NO_ERROR;
177 
178     if (service == nullptr) {
179         LOG_ERROR("[ObserverProfile] %{public}s Can't get the instance of service\n", __func__);
180         return;
181     }
182 
183     A2dpDeviceInfo *deviceInfo = service->GetDeviceFromList(btAddr);
184     utility::Message msgData(state, role_, &(btAddr));
185 
186     if (deviceInfo != nullptr) {
187         RawAddress rawAddr = bluetooth::RawAddress::ConvertToString(deviceInfo->GetDevice().addr);
188         if (state == A2DP_NOT_PLAYING) {
189             deviceInfo->SetPlayingState(false);
190         } else {
191             deviceInfo->SetPlayingState(true);
192         }
193         service->ProcessPlayingFrameworkCallback(state, error, rawAddr);
194     } else {
195         LOG_INFO("[ObserverProfile] %{public}s role[%u] Not find the device\n", __func__, role_);
196     }
197 }
198 
OnCodecStateChanged(const BtAddr & addr,const A2dpSrcCodecStatus codecInfo,void * context)199 void ObserverProfile::OnCodecStateChanged(const BtAddr &addr, const A2dpSrcCodecStatus codecInfo, void *context)
200 {
201     LOG_INFO("[ObserverProfile] %{public}s role[%u]\n", __func__, role_);
202 
203     RawAddress btAddr = bluetooth::RawAddress::ConvertToString(addr.addr);
204     A2dpService *service = GetServiceInstance(role_);
205     int error = RET_NO_ERROR;
206 
207     if (service == nullptr) {
208         LOG_ERROR("[ObserverProfile] %{public}s Can't get the instance of service\n", __func__);
209         return;
210     }
211 
212     A2dpDeviceInfo *deviceInfo = service->GetDeviceFromList(btAddr);
213     if (deviceInfo == nullptr) {
214         LOG_ERROR("[ObserverProfile] %{public}s role[%u] Not find the device\n", __func__, role_);
215         return;
216     }
217 
218     deviceInfo->SetCodecStatus(codecInfo);
219     RawAddress rawAddr = bluetooth::RawAddress::ConvertToString(deviceInfo->GetDevice().addr);
220 
221     utility::Message msg(A2DP_MSG_PROFILE_CODEC_CHANGE, role_, &(btAddr));
222     deviceInfo->GetStateMachine()->ProcessMessage(msg);
223 
224     service->ProcessCodecFrameworkCallback(codecInfo.codecInfo, error, rawAddr);
225 }
226 
A2dpService(const std::string & name,const std::string version,const uint8_t role)227 A2dpService::A2dpService(const std::string& name, const std::string version, const uint8_t role) : utility::Context(name, version)
228 {
229     LOG_INFO("[A2dpService] %{public}s role[%u]\n", __func__, role);
230 
231     name_ = name;
232     version_ = version;
233     role_ = role;
234     int value = 0;
235 
236     profileId_ = PROFILE_ID_A2DP_SRC;
237     profileObserver_ = ObserverProfile(role);
238     connectManager_ = A2dpConnectManager(role);
239     if (role == A2DP_ROLE_SOURCE) {
240         AdapterConfig::GetInstance()->GetValue(SECTION_A2DP_SRC_SERVICE, PROPERTY_MAX_CONNECTED_DEVICES, value);
241         profileId_ = PROFILE_ID_A2DP_SRC;
242     } else {
243         AdapterConfig::GetInstance()->GetValue(SECTION_A2DP_SNK_SERVICE, PROPERTY_MAX_CONNECTED_DEVICES, value);
244         profileId_ = PROFILE_ID_A2DP_SINK;
245     }
246 
247     LOG_INFO("[A2dpService] %{public}s role[%u] config max devices(%{public}d)\n", __func__, role, value);
248     if (value > 0 && value < A2DP_CONNECT_NUM_MAX) {
249         maxConnectNumSnk_ = value;
250     }
251     LOG_INFO("[A2dpService] %{public}s maxConnectDevices(%{public}d)\n", __func__, maxConnectNumSnk_);
252 }
253 
~A2dpService()254 A2dpService::~A2dpService()
255 {
256     LOG_INFO("[A2dpService] %{public}s role[%u]\n", __func__, role_);
257     for (auto it = a2dpDevices_.begin(); it != a2dpDevices_.end(); it++) {
258         if (it->second != nullptr) {
259             delete it->second;
260             it->second = nullptr;
261         }
262     }
263     a2dpDevices_.clear();
264 }
265 
GetContext()266 utility::Context *A2dpService::GetContext()
267 {
268     return this;
269 }
270 
Enable()271 void A2dpService::Enable()
272 {
273     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
274 
275     LOG_INFO("[A2dpService] %{public}s role_[%u]\n", __func__, role_);
276     A2dpProfile *pflA2dp = GetProfileInstance(role_);
277     if (pflA2dp == nullptr) {
278         LOG_WARN("[A2dpService] %{public}s Failed to get profile instance\n", __func__);
279         GetContext()->OnEnable(name_, false);
280         return;
281     }
282 
283     if (role_ == A2DP_ROLE_SOURCE) {
284         profileId_ = PROFILE_ID_A2DP_SRC;
285     } else {
286         profileId_ = PROFILE_ID_A2DP_SINK;
287     }
288 
289     pflA2dp->RegisterObserver(&profileObserver_);
290 
291     GetDispatcher()->PostTask(std::bind(&A2dpService::EnableService, this));
292 }
293 
Disable()294 void A2dpService::Disable()
295 {
296     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
297     HILOGI("[A2dpService] role_[%{public}u]", role_);
298 
299     GetDispatcher()->PostTask(std::bind(&A2dpService::DisableService, this));
300 }
301 
Connect(const RawAddress & device)302 int A2dpService::Connect(const RawAddress &device)
303 {
304     HILOGI("[address:%{public}s] role[%{public}u]", GET_ENCRYPT_ADDR(device), role_);
305 
306     int ret = RET_NO_ERROR;
307     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
308 
309     if (connectManager_.JudgeConnectExit(device, role_)) {
310         LOG_INFO("[A2dpService]The device is connected as another role");
311         ret = RET_BAD_STATUS;
312     } else if (!connectManager_.JudgeConnectedNum()) {
313         LOG_INFO("[A2dpService]The count of connected device is max");
314         ret = RET_BAD_STATUS;
315     } else if (static_cast<int>(BTConnectState::CONNECTED) == (GetDeviceState(device)) ||
316                (static_cast<int>(BTConnectState::CONNECTING) == GetDeviceState(device))) {
317         LOG_INFO("[A2dpService]Device have been connected");
318         ret = RET_BAD_STATUS;
319     } else if ((int)BTStrategyType::CONNECTION_FORBIDDEN == GetConnectStrategy(device)) {
320         ret = RET_NO_SUPPORT;
321     } else {
322         utility::Message event(A2DP_CONNECT_EVT);
323         PostEvent(event, const_cast<RawAddress &>(device));
324     }
325 
326     return ret;
327 }
328 
Disconnect(const RawAddress & device)329 int A2dpService::Disconnect(const RawAddress &device)
330 {
331     LOG_INFO("[A2dpService] %{public}s role[%u]\n", __func__, role_);
332 
333     int ret = RET_NO_ERROR;
334     A2dpDeviceInfo *info = nullptr;
335     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
336 
337     auto iter = a2dpDevices_.find(device.GetAddress().c_str());
338     if (iter == a2dpDevices_.end()) {
339         LOG_INFO("[A2dpService]Can't find the statemachine");
340         ret = RET_BAD_STATUS;
341     } else {
342         info = iter->second;
343         if ((static_cast<int>(BTConnectState::DISCONNECTED) == info->GetConnectState()) ||
344             (static_cast<int>(BTConnectState::DISCONNECTING) == info->GetConnectState())) {
345             LOG_INFO("[A2dpService]Device have been disconnected");
346             ret = BT_OPERATION_FAILED;
347         } else {
348             utility::Message event(A2DP_DISCONNECT_EVT);
349             PostEvent(event, const_cast<RawAddress &>(device));
350         }
351     }
352 
353     return ret;
354 }
355 
ProcessAvdtpCallback(const BtAddr & addr,utility::Message & message) const356 void A2dpService::ProcessAvdtpCallback(const BtAddr &addr, utility::Message &message) const
357 {
358     LOG_INFO("[A2dpService] %{public}s \n", __func__);
359 
360     uint8_t role = (static_cast<A2dpAvdtMsg*>(message.arg2_))->role;
361     message.what_ = (static_cast<A2dpAvdtMsg*>(message.arg2_))->event;
362     A2dpProfile *instance = GetProfileInstance(role);
363     if (instance == nullptr) {
364         LOG_WARN("[A2dpService] %{public}s Failed to get profile instance\n", __func__);
365         return;
366     }
367     instance->ProcessAvdtpCallback(addr, message);
368 }
369 
ProcessTimeoutCallback(uint8_t role,const BtAddr & addr) const370 void A2dpService::ProcessTimeoutCallback(uint8_t role, const BtAddr &addr) const
371 {
372     LOG_INFO("[A2dpService] %{public}s role(%u)\n", __func__, role);
373 
374     A2dpProfile *instance = GetProfileInstance(role);
375     if (instance == nullptr) {
376         LOG_WARN("[A2dpService] %{public}s Failed to get profile instance\n", __func__);
377         return;
378     }
379 
380     instance->ProcessSignalingTimeoutCallback(addr);
381 }
382 
ProcessSDPFindCallback(const BtAddr & addr,const uint8_t result,A2dpProfile * instance) const383 void A2dpService::ProcessSDPFindCallback(const BtAddr &addr, const uint8_t result, A2dpProfile *instance) const
384 {
385     LOG_INFO("[A2dpService] %{public}s \n", __func__);
386     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
387 
388     if (instance == nullptr) {
389         LOG_WARN("[A2dpService] %{public}s Failed to get profile instance\n", __func__);
390         return;
391     }
392     instance->ProcessSDPCallback(addr, result);
393 }
394 
GetConnectDevices()395 std::list<RawAddress> A2dpService::GetConnectDevices()
396 {
397     LOG_INFO("[A2dpService] %{public}s\n", __func__);
398     std::list<RawAddress> devList;
399     int connectionState = static_cast<int>(BTConnectState::DISCONNECTED);
400     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
401 
402     for (auto it = a2dpDevices_.begin(); it != a2dpDevices_.end(); it++) {
403         if (it->second == nullptr) {
404             continue;
405         }
406         connectionState = it->second->GetConnectState();
407         if (connectionState == static_cast<int>(BTConnectState::CONNECTED)) {
408             devList.push_back(RawAddress::ConvertToString(it->second->GetDevice().addr));
409         }
410     }
411     return devList;
412 }
413 
GetConnectState()414 int A2dpService::GetConnectState()
415 {
416     LOG_INFO("[A2dpService] %{public}s\n", __func__);
417 
418     int ret = PROFILE_STATE_DISCONNECTED;
419     int state = static_cast<int>(BTConnectState::DISCONNECTED);
420     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
421 
422     if (!a2dpDevices_.empty()) {
423         for (auto itr : GetDeviceList()) {
424             state = itr.second->GetConnectState();
425 
426             switch (state) {
427                 case static_cast<int>(BTConnectState::CONNECTING):
428                     ret |= PROFILE_STATE_CONNECTING;
429                     break;
430                 case static_cast<int>(BTConnectState::CONNECTED):
431                     ret |= PROFILE_STATE_CONNECTED;
432                     break;
433                 case static_cast<int>(BTConnectState::DISCONNECTING):
434                     ret |= PROFILE_STATE_DISCONNECTING;
435                     break;
436                 case static_cast<int>(BTConnectState::DISCONNECTED):
437                     ret |= PROFILE_STATE_DISCONNECTED;
438                     break;
439                 default:
440                     break;
441             }
442         }
443     }
444 
445     return ret;
446 }
447 
ProcessMessage(const utility::Message & msg) const448 void A2dpService::ProcessMessage(const utility::Message &msg) const
449 {
450     LOG_INFO("[A2dpService] %{public}s\n", __func__);
451 }
452 
EnableService()453 void A2dpService::EnableService()
454 {
455     bool ret = true;
456     A2dpProfile *instance = GetProfileInstance(role_);
457 
458     if (instance == nullptr) {
459         LOG_WARN("[A2dpService] %{public}s Failed to get profile instance\n", __func__);
460         return;
461     }
462 
463     instance->Enable();
464     GetContext()->OnEnable(name_, ret);
465 }
466 
DisableService()467 void A2dpService::DisableService()
468 {
469     bool ret = true;
470     A2dpProfile *instance = GetProfileInstance(role_);
471     if (instance == nullptr) {
472         LOG_WARN("[A2dpService] %{public}s Failed to get profile instance\n", __func__);
473         return;
474     }
475     instance->SetDisalbeTag(true);
476     isDoDisable = true;
477 
478     if (instance->HasStreaming()) {
479         auto curDevice = a2dpDevices_.find(activeDevice_.GetAddress().c_str());
480         if (curDevice != a2dpDevices_.end()) {
481             instance->Stop(curDevice->second->GetHandle(), true);
482         }
483     } else {
484         if (instance->HasOpen()) {
485             instance->CloseAll();
486         } else {
487             instance->Disable();
488         }
489     }
490 
491     if (GetConnectState() != PROFILE_STATE_DISCONNECTED) {
492         return;
493     }
494 
495     for (auto it = a2dpDevices_.begin(); it != a2dpDevices_.end(); it++) {
496         if (it->second != nullptr) {
497             delete it->second;
498             it->second = nullptr;
499         }
500     }
501 
502     a2dpDevices_.clear();
503     instance->DeregisterObserver(&profileObserver_);
504     GetContext()->OnDisable(name_, ret);
505     isDoDisable = false;
506     instance->SetDisalbeTag(false);
507 }
508 
GetDevicesByStates(std::vector<int> & states) const509 std::vector<RawAddress> A2dpService::GetDevicesByStates(std::vector<int>& states) const
510 {
511     std::vector<RawAddress> devices = {};
512     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
513 
514     for (auto it = a2dpDevices_.begin(); it != a2dpDevices_.end(); it++) {
515         int connectionState = 0;
516         connectionState = it->second->GetConnectState();
517         if (FindStateMatched(states, connectionState)) {
518             devices.push_back(RawAddress::ConvertToString(it->second->GetDevice().addr));
519         }
520     }
521 
522     return devices;
523 }
524 
FindStateMatched(std::vector<int> states,int connectState) const525 bool A2dpService::FindStateMatched(std::vector<int> states, int connectState) const
526 {
527     int length = states.size();
528     for (int i = 0; i < length; i++) {
529         int state = 0;
530         state = states[i];
531         if (connectState == state) {
532             return true;
533         }
534     }
535 
536     return false;
537 }
538 
GetDeviceState(const RawAddress & device) const539 int A2dpService::GetDeviceState(const RawAddress &device) const
540 {
541     A2dpDeviceInfo *info = nullptr;
542     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
543     auto iter = a2dpDevices_.find(device.GetAddress().c_str());
544     if (iter == a2dpDevices_.end()) {
545         LOG_ERROR("[A2dpService]Can't find the statemachine");
546         return static_cast<int>(BTConnectState::DISCONNECTED);
547     } else {
548         info = iter->second;
549     }
550 
551     return info->GetConnectState();
552 }
553 
GetPlayingState(const RawAddress & device,int & state) const554 int A2dpService::GetPlayingState(const RawAddress &device, int &state) const
555 {
556     A2dpDeviceInfo *info = nullptr;
557     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
558     auto iter = a2dpDevices_.find(device.GetAddress().c_str());
559     if (iter == a2dpDevices_.end()) {
560         LOG_ERROR("[A2dpService]Can't find the statemachine");
561         return RET_BAD_STATUS;
562     } else {
563         info = iter->second;
564     }
565     state = info->GetPlayingState() ? A2DP_IS_PLAYING : A2DP_NOT_PLAYING;
566     return RET_NO_ERROR;
567 }
568 
SetActiveSinkDevice(const RawAddress & device)569 int A2dpService::SetActiveSinkDevice(const RawAddress &device)
570 {
571     A2dpProfile *pflA2dp = GetProfileInstance(role_);
572     BtAddr btAddr = {};
573     RawAddress rawAddr(device.GetAddress());
574     rawAddr.ConvertToUint8(btAddr.addr);
575     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
576 
577     if (pflA2dp == nullptr) {
578         LOG_ERROR("[A2dpService] %{public}s Failed to get profile instance\n", __func__);
579         return RET_BAD_STATUS;
580     }
581 
582     auto iter = a2dpDevices_.find(device.GetAddress().c_str());
583     if (iter == a2dpDevices_.end()) {
584         LOG_ERROR("[A2dpService]There is no statemachine");
585         return RET_BAD_STATUS;
586     } else {
587         if (iter->second->GetConnectState() != static_cast<int>(BTConnectState::CONNECTED)) {
588             LOG_ERROR("[A2dpService]The device is not connected");
589             return RET_BAD_STATUS;
590         }
591     }
592 
593     auto curDevice = a2dpDevices_.find(activeDevice_.GetAddress().c_str());
594     if (strcmp(device.GetAddress().c_str(), activeDevice_.GetAddress().c_str()) == 0) {
595         LOG_ERROR("[A2dpService]The device is already active");
596         pflA2dp->Start(curDevice->second->GetHandle());
597     } else {
598         if (curDevice != a2dpDevices_.end() && curDevice->second != nullptr) {
599             if (pflA2dp->Stop(curDevice->second->GetHandle(), true)) {
600                 pflA2dp->Start(iter->second->GetHandle());
601             }
602         } else {
603             pflA2dp->Start(iter->second->GetHandle());
604         }
605         pflA2dp->SetActivePeer(btAddr);
606         UpdateActiveDevice(rawAddr);
607     }
608 
609     return RET_NO_ERROR;
610 }
611 
ActiveDevice()612 void A2dpService::ActiveDevice()
613 {
614     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
615     A2dpProfile *pflA2dp = GetProfileInstance(role_);
616     if (pflA2dp == nullptr) {
617         LOG_ERROR("[A2dpService] %{public}s Failed to get profile instance\n", __func__);
618         return;
619     }
620     auto curDevice = a2dpDevices_.find(activeDevice_.GetAddress().c_str());
621     if (curDevice != a2dpDevices_.end()) {
622         pflA2dp->Start(curDevice->second->GetHandle());
623     }
624 }
625 
GetActiveSinkDevice() const626 const RawAddress &A2dpService::GetActiveSinkDevice() const
627 {
628     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
629 
630     HILOGI("address(%{public}s)", GetEncryptAddr(activeDevice_.GetAddress()).c_str());
631 
632     return activeDevice_;
633 }
634 
SetConnectStrategy(const RawAddress & device,int strategy)635 int A2dpService::SetConnectStrategy(const RawAddress &device, int strategy)
636 {
637     bool returnValue = false;
638     IProfileConfig *config = ProfileConfig::GetInstance();
639     int value = 0;
640 
641     switch (BTStrategyType(strategy)) {
642         case BTStrategyType::CONNECTION_UNKNOWN:
643             return config->RemoveProperty(device.GetAddress(),
644                 SECTION_CONNECTION_POLICIES,
645                 (role_ == A2DP_ROLE_SOURCE) ? PROPERTY_A2DP_CONNECTION_POLICY : PROPERTY_A2DP_SINK_CONNECTION_POLICY);
646         case BTStrategyType::CONNECTION_ALLOWED:
647             value = (int)BTStrategyType::CONNECTION_ALLOWED;
648             break;
649         case BTStrategyType::CONNECTION_FORBIDDEN:
650             value = (int)BTStrategyType::CONNECTION_FORBIDDEN;
651             break;
652         default:
653             return RET_BAD_STATUS;
654     }
655 
656     returnValue = config->SetValue(device.GetAddress(),
657         SECTION_CONNECTION_POLICIES,
658         (role_ == A2DP_ROLE_SOURCE) ? PROPERTY_A2DP_CONNECTION_POLICY : PROPERTY_A2DP_SINK_CONNECTION_POLICY,
659         value);
660     int ret = returnValue ? RET_NO_ERROR : RET_BAD_STATUS;
661 
662     if (returnValue && ((int)BTStrategyType::CONNECTION_ALLOWED == strategy)) {
663         if (static_cast<int>(BTConnectState::DISCONNECTED) == (GetDeviceState(device))) {
664             Connect(device);
665         }
666     } else if (returnValue && ((int)BTStrategyType::CONNECTION_FORBIDDEN == strategy)) {
667         if (static_cast<int>(BTConnectState::DISCONNECTED) != (GetDeviceState(device)) &&
668             static_cast<int>(BTConnectState::DISCONNECTING) != (GetDeviceState(device))) {
669             Disconnect(device);
670         }
671     } else {
672         LOG_ERROR("[A2dpService]Strategy set failed");
673         ret = RET_BAD_STATUS;
674     }
675 
676     return ret;
677 }
678 
GetConnectStrategy(const RawAddress & device) const679 int A2dpService::GetConnectStrategy(const RawAddress &device) const
680 {
681     IProfileConfig *config = ProfileConfig::GetInstance();
682     int value = 0;
683     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
684 
685     if (!config->GetValue(device.GetAddress(),
686         SECTION_CONNECTION_POLICIES,
687         (role_ == A2DP_ROLE_SOURCE) ? PROPERTY_A2DP_CONNECTION_POLICY : PROPERTY_A2DP_SINK_CONNECTION_POLICY,
688         value)) {
689         HILOGI("%{public}s connection policy not found", GET_ENCRYPT_ADDR(device));
690         return (int)BTStrategyType::CONNECTION_UNKNOWN;
691     }
692 
693     if (value == (int)BTStrategyType::CONNECTION_ALLOWED) {
694         return (int)BTStrategyType::CONNECTION_ALLOWED;
695     } else {
696         return (int)BTStrategyType::CONNECTION_FORBIDDEN;
697     }
698 }
699 
SendDelay(const RawAddress & device,uint16_t delayValue)700 int A2dpService::SendDelay(const RawAddress &device, uint16_t delayValue)
701 {
702     LOG_INFO("[A2dpService] %{public}s\n", __func__);
703     uint16_t handle = 0;
704     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
705 
706     auto iter = a2dpDevices_.find(device.GetAddress().c_str());
707     if (iter == a2dpDevices_.end()) {
708         LOG_ERROR("[A2dpService]Can't find the statemachine");
709         return RET_BAD_STATUS;
710     } else {
711         handle = iter->second->GetHandle();
712         LOG_INFO("[A2dpService] %{public}s handle [%u]", __func__, handle);
713     }
714 
715     A2dpProfile *pflA2dp = GetProfileInstance(role_);
716     if (pflA2dp == nullptr) {
717         LOG_ERROR("[A2dpService] %{public}s Failed to get profile instance. role_(%u)\n", __func__, role_);
718         return RET_BAD_STATUS;
719     }
720 
721     int ret = pflA2dp->SendDelay(handle, delayValue);
722     return ret;
723 }
724 
GetCodecStatus(const RawAddress & device) const725 A2dpSrcCodecStatus A2dpService::GetCodecStatus(const RawAddress &device) const
726 {
727     A2dpSrcCodecStatus codecStatus;
728     A2dpDeviceInfo *info = nullptr;
729     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
730 
731     for (auto bdr : GetDeviceList()) {
732         if (bdr.first == device.GetAddress().c_str()) {
733             info = bdr.second;
734             break;
735         }
736     }
737 
738     if (info != nullptr) {
739         codecStatus = info->GetCodecStatus();
740     } else {
741         LOG_ERROR("[A2dpService] device is not found in list");
742     }
743 
744     return codecStatus;
745 }
746 
SetCodecPreference(const RawAddress & device,const A2dpSrcCodecInfo & info)747 int A2dpService::SetCodecPreference(const RawAddress &device, const A2dpSrcCodecInfo &info)
748 {
749     LOG_INFO("[A2dpService] %{public}s\n", __func__);
750     std::string addr = device.GetAddress();
751 
752     if (!strcmp(INVALID_MAC_ADDRESS.c_str(), device.GetAddress().c_str())) {
753         addr = GetActiveSinkDevice().GetAddress();
754     }
755     if (!strcmp(INVALID_MAC_ADDRESS.c_str(), addr.c_str())) {
756         LOG_INFO("[A2dpService] %{public}s : invalid device\n", __func__);
757         return RET_BAD_PARAM;
758     }
759 
760     A2dpSrcCodecStatus codecStatus = GetCodecStatus(RawAddress(addr));
761     A2dpSrcCodecInfo currentInfo = codecStatus.codecInfo;
762     if (!IsLocalCodecInfo(codecStatus, info)) {
763         LOG_ERROR("[A2dpService] %{public}s : device's local info doesn't include codecinfo \n", __func__);
764         return RET_BAD_PARAM;
765     }
766 
767     if ((IsSimilarCodecConfig(currentInfo, info))) {
768         LOG_ERROR("[A2dpService] %{public}s : current codec information doesn't change \n", __func__);
769         return RET_BAD_PARAM;
770     }
771 
772     LOG_INFO("[A2dpService] %{public}s codec information is valid\n", __func__);
773 
774     A2dpProfile *pflA2dp = GetProfileInstance(role_);
775     BtAddr btAddr = {};
776     RawAddress rawAddr(addr);
777     rawAddr.ConvertToUint8(btAddr.addr);
778 
779     int ret = RET_BAD_STATUS;
780     if (pflA2dp != nullptr) {
781         ret = pflA2dp->SetUserCodecConfigure(btAddr, info);
782     }
783     return ret;
784 }
785 
SwitchOptionalCodecs(const RawAddress & device,bool isEnable)786 void A2dpService::SwitchOptionalCodecs(const RawAddress &device, bool isEnable)
787 {
788     if ((int)A2DP_OPTIONAL_SUPPORT != GetOptionalCodecsSupportState(device)) {
789         LOG_ERROR("[A2dpService] %{public}s : optional codec is not support\n", __func__);
790         return;
791     }
792 
793     std::string addr = device.GetAddress();
794     if (!strcmp(INVALID_MAC_ADDRESS.c_str(), device.GetAddress().c_str())) {
795         addr = GetActiveSinkDevice().GetAddress();
796     }
797     if (!strcmp(INVALID_MAC_ADDRESS.c_str(), addr.c_str())) {
798         LOG_ERROR("[A2dpService] %{public}s : invalid device\n", __func__);
799         return;
800     }
801 
802     A2dpSrcCodecStatus codecStatus = GetCodecStatus(addr);
803     if (isEnable != (A2DP_CODEC_TYPE_SBC_USER == codecStatus.codecInfo.codecType)) {
804         LOG_ERROR("[A2dpService] : current optional codec is the same as user setting\n");
805         return;
806     }
807 
808     A2dpProfile *pflA2dp = GetProfileInstance(role_);
809     BtAddr btAddr = {};
810     RawAddress rawAddr(addr);
811     rawAddr.ConvertToUint8(btAddr.addr);
812 
813     if (pflA2dp == nullptr) {
814         LOG_ERROR("[A2dpService] %{public}s Failed to get profile instance. role_(%u)\n", __func__, role_);
815         return;
816     }
817     pflA2dp->EnableOptionalCodec(btAddr, isEnable);
818 }
819 
GetOptionalCodecsSupportState(const RawAddress & device) const820 int A2dpService::GetOptionalCodecsSupportState(const RawAddress &device) const
821 {
822     IProfileConfig *config = ProfileConfig::GetInstance();
823     int value = 0;
824     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
825 
826     if (!config->GetValue(
827         device.GetAddress(), SECTION_CODE_CS_SUPPORT, PROPERTY_A2DP_SUPPORTS_OPTIONAL_CODECS, value)) {
828         HILOGI("%{public}s %{public}s not found", GET_ENCRYPT_ADDR(device),
829             PROPERTY_A2DP_SUPPORTS_OPTIONAL_CODECS.c_str());
830         return (int)A2DP_OPTIONAL_SUPPORT_UNKNOWN;
831     }
832 
833     if (value) {
834         return (int)A2DP_OPTIONAL_SUPPORT;
835     } else {
836         return (int)A2DP_OPTIONAL_NOT_SUPPORT;
837     }
838 }
839 
StartPlaying(const RawAddress & device)840 int A2dpService::StartPlaying(const RawAddress &device)
841 {
842     uint16_t handle = 0;
843     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
844 
845     auto iter = a2dpDevices_.find(device.GetAddress().c_str());
846     if (iter == a2dpDevices_.end()) {
847         LOG_ERROR("[A2dpService]Can't find the statemachine");
848         return RET_BAD_STATUS;
849     } else {
850         handle = iter->second->GetHandle();
851         LOG_INFO("[A2dpService] %{public}s handle [%u]", __func__, handle);
852     }
853 
854     if (iter->second->GetPlayingState()) {
855         LOG_INFO("[A2dpService] Device is on playing");
856         return RET_NO_ERROR;
857     }
858 
859     A2dpProfile *pflA2dp = GetProfileInstance(role_);
860     if (pflA2dp == nullptr) {
861         LOG_ERROR("[A2dpService] %{public}s Failed to get profile instance. role_(%u)\n", __func__, role_);
862         return RET_BAD_STATUS;
863     }
864 
865     int ret = pflA2dp->Start(handle);
866     return ret;
867 }
868 
SuspendPlaying(const RawAddress & device)869 int A2dpService::SuspendPlaying(const RawAddress &device)
870 {
871     uint16_t handle = 0;
872     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
873 
874     auto iter = a2dpDevices_.find(device.GetAddress().c_str());
875     if (iter == a2dpDevices_.end()) {
876         LOG_ERROR("[A2dpService]Can't find the statemachine");
877         return RET_BAD_STATUS;
878     } else {
879         handle = iter->second->GetHandle();
880     }
881 
882     if (!iter->second->GetPlayingState()) {
883         LOG_ERROR("[A2dpService] Device is not on playing");
884         return RET_NO_ERROR;
885     }
886 
887     LOG_INFO("[A2dpService] %{public}s handle [%u]", __func__, handle);
888     A2dpProfile *pflA2dp = GetProfileInstance(role_);
889     if (pflA2dp == nullptr) {
890         LOG_ERROR("[A2dpService] %{public}s Failed to get profile instance. role_(%u)\n", __func__, role_);
891         return RET_BAD_STATUS;
892     }
893 
894     int ret = pflA2dp->Stop(handle, true);
895     return ret;
896 }
897 
StopPlaying(const RawAddress & device)898 int A2dpService::StopPlaying(const RawAddress &device)
899 {
900     uint16_t handle = 0;
901     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
902 
903     auto iter = a2dpDevices_.find(device.GetAddress().c_str());
904     if (iter == a2dpDevices_.end()) {
905         LOG_ERROR("[A2dpService]Can't find the statemachine");
906         return RET_BAD_STATUS;
907     } else {
908         handle = iter->second->GetHandle();
909     }
910 
911     if (!iter->second->GetPlayingState()) {
912         LOG_ERROR("[A2dpService] Device is not on playing");
913         return RET_NO_ERROR;
914     }
915 
916     LOG_INFO("[A2dpService] %{public}s handle [%u]", __func__, handle);
917     A2dpProfile *pflA2dp = GetProfileInstance(role_);
918     if (pflA2dp == nullptr) {
919         LOG_ERROR("[A2dpService] %{public}s Failed to get profile instance. role_(%u)\n", __func__, role_);
920         return RET_BAD_STATUS;
921     }
922 
923     int ret = pflA2dp->Stop(handle, false);
924     return ret;
925 }
926 
RegisterObserver(IA2dpObserver * observer)927 void A2dpService::RegisterObserver(IA2dpObserver *observer)
928 {
929     LOG_INFO("[A2dpService] %{public}s\n", __func__);
930     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
931 
932     a2dpFramworkCallback_.Register(*observer);
933 }
934 
DeregisterObserver(IA2dpObserver * observer)935 void A2dpService::DeregisterObserver(IA2dpObserver *observer)
936 {
937     LOG_INFO("[A2dpService] %{public}s\n", __func__);
938     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
939 
940     a2dpFramworkCallback_.Deregister(*observer);
941 }
942 
WriteFrame(const uint8_t * data,uint32_t size)943 int A2dpService::WriteFrame(const uint8_t *data, uint32_t size)
944 {
945     LOG_INFO("[A2dpService] %{public}s\n", __func__);
946 
947     A2dpProfile *profile = GetProfileInstance(role_);
948     if (profile != nullptr) {
949         if (profile->SetPcmData(data, size) == 0) {
950             LOG_ERROR("[A2dpService] %{public}s Failed to write frame. role_(%u)\n", __func__, role_);
951             return RET_NO_SPACE;
952         }
953     } else {
954         LOG_ERROR("[A2dpService] %{public}s Failed to get profile instance. role_(%u)\n", __func__, role_);
955         return RET_BAD_STATUS;
956     }
957     return RET_NO_ERROR;
958 }
959 
GetRenderPosition(uint16_t & delayValue,uint16_t & sendDataSize,uint32_t & timeStamp)960 void A2dpService::GetRenderPosition(uint16_t &delayValue, uint16_t &sendDataSize, uint32_t &timeStamp)
961 {
962     LOG_INFO("[A2dpService] %{public}s\n", __func__);
963 
964     A2dpProfile *profile = GetProfileInstance(role_);
965     if (profile != nullptr) {
966         profile->GetRenderPosition(delayValue, sendDataSize, timeStamp);
967     } else {
968         LOG_ERROR("[A2dpService] %{public}s Failed to get profile instance. role_(%u)\n", __func__, role_);
969     }
970 }
971 
GetMaxConnectNum()972 int A2dpService::GetMaxConnectNum()
973 {
974     LOG_INFO("[A2dpService] %{public}s\n", __func__);
975     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
976 
977     return maxConnectNumSnk_;
978 }
979 
ProcessConnectFrameworkCallback(int state,const RawAddress & device)980 void A2dpService::ProcessConnectFrameworkCallback(int state, const RawAddress &device)
981 {
982     LOG_INFO("[A2dpService] %{public}s\n", __func__);
983 
984     a2dpFramworkCallback_.ForEach(
985         [device, state](IA2dpObserver &observer) { observer.OnConnectionStateChanged(device, state); });
986 }
987 
ProcessPlayingFrameworkCallback(int playingState,int error,const RawAddress & device)988 void A2dpService::ProcessPlayingFrameworkCallback(int playingState, int error, const RawAddress &device)
989 {
990     LOG_INFO("[A2dpService] %{public}s\n", __func__);
991 
992     a2dpFramworkCallback_.ForEach([device, playingState, error](IA2dpObserver &observer) {
993         observer.OnPlayingStatusChaned(device, playingState, error);
994     });
995 }
996 
ProcessCodecFrameworkCallback(const bluetooth::A2dpSrcCodecInfo & info,int error,const RawAddress & device)997 void A2dpService::ProcessCodecFrameworkCallback(
998     const bluetooth::A2dpSrcCodecInfo &info, int error, const RawAddress &device)
999 {
1000     LOG_INFO("[A2dpService] %{public}s\n", __func__);
1001 
1002     a2dpFramworkCallback_.ForEach(
1003         [device, info, error](IA2dpObserver &observer) { observer.OnConfigurationChanged(device, info, error); });
1004 }
1005 
GetDeviceFromList(const RawAddress & device)1006 A2dpDeviceInfo *A2dpService::GetDeviceFromList(const RawAddress &device)
1007 {
1008     LOG_INFO("[A2dpService] %{public}s\n", __func__);
1009     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
1010 
1011     auto iter = a2dpDevices_.find(device.GetAddress().c_str());
1012     if (iter == a2dpDevices_.end()) {
1013         LOG_ERROR("[A2dpService]Can't find the statemachine");
1014         return nullptr;
1015     } else {
1016         return iter->second;
1017     }
1018 }
1019 
GetDeviceList() const1020 std::map<std::string, A2dpDeviceInfo *> A2dpService::GetDeviceList() const
1021 {
1022     LOG_INFO("[A2dpService] %{public}s\n", __func__);
1023     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
1024 
1025     return a2dpDevices_;
1026 }
1027 
AddDeviceToList(std::string address,A2dpDeviceInfo * deviceInfo)1028 void A2dpService::AddDeviceToList(std::string address, A2dpDeviceInfo *deviceInfo)
1029 {
1030     LOG_INFO("[A2dpService] %{public}s\n", __func__);
1031     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
1032 
1033     a2dpDevices_.insert(std::make_pair(address, deviceInfo));
1034 }
1035 
DeleteDeviceFromList(const RawAddress & device)1036 void A2dpService::DeleteDeviceFromList(const RawAddress &device)
1037 {
1038     LOG_INFO("[A2dpService] %{public}s\n", __func__);
1039 
1040     std::map<std::string, bluetooth::A2dpDeviceInfo *>::iterator it;
1041     A2dpDeviceInfo *deviceInfo = nullptr;
1042     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
1043 
1044     for (it = a2dpDevices_.begin(); it != a2dpDevices_.end(); it++) {
1045         if (strcmp(it->first.c_str(), device.GetAddress().c_str()) == RET_NO_ERROR) {
1046             deviceInfo = it->second;
1047             delete deviceInfo;
1048             a2dpDevices_.erase(it);
1049             break;
1050         }
1051         LOG_INFO("[A2dpService]%{public}s device[%{public}s]\n", __func__, it->first.c_str());
1052     }
1053 }
1054 
PostEvent(utility::Message event,RawAddress & device)1055 void A2dpService::PostEvent(utility::Message event, RawAddress &device)
1056 {
1057     GetDispatcher()->PostTask(std::bind(&A2dpService::ProcessEvent, this, event, device));
1058 }
1059 
ProcessEvent(utility::Message event,RawAddress & device)1060 void A2dpService::ProcessEvent(utility::Message event, RawAddress &device)
1061 {
1062     HILOGI("peerAddr(%{public}s)", GET_ENCRYPT_ADDR(device));
1063     BtAddr addr = {};
1064     device.ConvertToUint8(addr.addr);
1065     A2dpAvdtMsg data = {};
1066     utility::Message msg(event.what_, 0, &data);
1067 
1068     switch (event.what_) {
1069         case A2DP_CONNECT_EVT:
1070             if (connectManager_.A2dpConnect(device)) {
1071                 LOG_INFO("[A2dpService] Start connect peer\n");
1072             } else {
1073                 LOG_ERROR("[A2dpService] Start connect failed\n");
1074             }
1075             break;
1076         case A2DP_DISCONNECT_EVT:
1077             if (connectManager_.A2dpDisconnect(device)) {
1078                 LOG_INFO("[A2dpService] Start disconnect peer\n");
1079             } else {
1080                 LOG_ERROR("[A2dpService] Start disconnect failed\n");
1081             }
1082             break;
1083         case A2DP_AVDTP_EVT:
1084             if (event.arg2_ != nullptr) {
1085                 (void)memcpy_s(msg.arg2_, sizeof(data), event.arg2_, sizeof(data));
1086                 ProcessAvdtpCallback(addr, msg);
1087                 delete static_cast<A2dpAvdtMsg*>(event.arg2_);
1088                 event.arg2_ = nullptr;
1089             }
1090             break;
1091         case A2DP_SDP_EVT:
1092             if (event.arg2_ != nullptr) {
1093                 ProcessSDPFindCallback(addr, event.arg1_, static_cast<A2dpProfile*>(event.arg2_));
1094             }
1095             break;
1096         case A2DP_TIMEOUT_EVT:
1097             ProcessTimeoutCallback(event.arg1_, addr);
1098             break;
1099         default:
1100             break;
1101     }
1102 }
1103 
ConnectManager() const1104 A2dpConnectManager A2dpService::ConnectManager() const
1105 {
1106     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
1107 
1108     return connectManager_;
1109 }
1110 
UpdateOptCodecStatus(const RawAddress & device)1111 void A2dpService::UpdateOptCodecStatus(const RawAddress &device)
1112 {
1113     LOG_INFO("[A2dpService] %{public}s\n", __func__);
1114 
1115     bool supportOptCodec = false;
1116     bool mandatoryCodec = false;
1117     A2dpSrcCodecStatus codecStatus = GetCodecStatus(device);
1118     int supportState = GetOptionalCodecsSupportState(device);
1119 
1120     for (A2dpSrcCodecInfo codecInfo : codecStatus.codecInfoConfirmedCap) {
1121         if (codecInfo.codecType == A2DP_CODEC_TYPE_SBC_USER) {
1122             mandatoryCodec = true;
1123         } else {
1124             supportOptCodec = true;
1125         }
1126     }
1127 
1128     if (!mandatoryCodec) {
1129         return;
1130     }
1131 
1132     if ((supportState == A2DP_OPTIONAL_SUPPORT_UNKNOWN) ||
1133         ((supportState == A2DP_OPTIONAL_SUPPORT) && (supportOptCodec == false)) ||
1134         ((supportState == A2DP_OPTIONAL_NOT_SUPPORT) && (supportOptCodec))) {
1135         SetOptionalCodecsSupportState(device, supportOptCodec);
1136     }
1137 }
1138 
CheckDisable()1139 void A2dpService::CheckDisable()
1140 {
1141     LOG_INFO("[A2dpService] %{public}s isDoDisable(%{public}d), state(%{public}d)\n", __func__, isDoDisable, GetConnectState());
1142 
1143     A2dpProfile *instance = GetProfileInstance(role_);
1144     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
1145 
1146     if (isDoDisable && (GetConnectState() == PROFILE_STATE_DISCONNECTED)) {
1147         isDoDisable = false;
1148 
1149         for (auto it = a2dpDevices_.begin(); it != a2dpDevices_.end(); it++) {
1150             if (it->second != nullptr) {
1151                 delete it->second;
1152                 it->second = nullptr;
1153             }
1154         }
1155         a2dpDevices_.clear();
1156 
1157         instance->DeregisterObserver(&profileObserver_);
1158         GetContext()->OnDisable(name_, true);
1159         instance->SetDisalbeTag(false);
1160     }
1161 }
1162 
UpdateActiveDevice(const RawAddress & device)1163 void A2dpService::UpdateActiveDevice(const RawAddress &device)
1164 {
1165     LOG_INFO("[A2dpService] %{public}s\n", __func__);
1166     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
1167 
1168     activeDevice_ = device;
1169 }
1170 
SetOptionalCodecsSupportState(const RawAddress & device,int state)1171 void A2dpService::SetOptionalCodecsSupportState(const RawAddress &device, int state)
1172 {
1173     IProfileConfig *config = ProfileConfig::GetInstance();
1174     std::lock_guard<std::recursive_mutex> lock(g_a2dpServiceMutex);
1175 
1176     if (state == (int)A2DP_OPTIONAL_SUPPORT_UNKNOWN) {
1177         config->RemoveProperty(device.GetAddress(), SECTION_CODE_CS_SUPPORT, PROPERTY_A2DP_SUPPORTS_OPTIONAL_CODECS);
1178     } else {
1179         LOG_INFO("[A2dpService] %{public}s ProfileConfig SetValue state(%{public}d)\n", __func__, state);
1180         config->SetValue(device.GetAddress(), SECTION_CODE_CS_SUPPORT, PROPERTY_A2DP_SUPPORTS_OPTIONAL_CODECS, state);
1181     }
1182 }
1183 
IsSimilarCodecConfig(A2dpSrcCodecInfo codecInfo,A2dpSrcCodecInfo newInfo) const1184 bool A2dpService::IsSimilarCodecConfig(A2dpSrcCodecInfo codecInfo, A2dpSrcCodecInfo newInfo) const
1185 {
1186     LOG_INFO("[A2dpService] %{public}s\n", __func__);
1187 
1188     if (newInfo.codecType != codecInfo.codecType) {
1189         return false;
1190     }
1191 
1192     if ((newInfo.sampleRate == A2DP_SAMPLE_RATE_NONE_USER) || (codecInfo.sampleRate == A2DP_SAMPLE_RATE_NONE_USER)) {
1193         newInfo.sampleRate = codecInfo.sampleRate;
1194     }
1195 
1196     if ((newInfo.bitsPerSample == A2DP_SAMPLE_BITS_NONE_USER) ||
1197         (codecInfo.bitsPerSample == A2DP_SAMPLE_BITS_NONE_USER)) {
1198         newInfo.bitsPerSample = codecInfo.bitsPerSample;
1199     }
1200 
1201     if ((newInfo.channelMode == A2DP_CHANNEL_MODE_NONE_USER) ||
1202         (codecInfo.channelMode == A2DP_CHANNEL_MODE_NONE_USER)) {
1203         newInfo.channelMode = codecInfo.channelMode;
1204     }
1205 
1206     if ((newInfo.sampleRate == codecInfo.sampleRate) && (newInfo.bitsPerSample == codecInfo.bitsPerSample) &&
1207         (newInfo.channelMode == codecInfo.channelMode)) {
1208         LOG_INFO("[A2dpService] %{public}s similar config\n", __func__);
1209         return true;
1210     }
1211 
1212     return false;
1213 }
1214 
IsLocalCodecInfo(A2dpSrcCodecStatus codecStatus,A2dpSrcCodecInfo codecInformation) const1215 bool A2dpService::IsLocalCodecInfo(A2dpSrcCodecStatus codecStatus, A2dpSrcCodecInfo codecInformation) const
1216 {
1217     LOG_INFO("[A2dpService] %{public}s\n", __func__);
1218 
1219     LOG_INFO("[A2dpService] %{public}s Set codecType(%{public}u)\n", __func__, codecInformation.codecType);
1220     LOG_INFO("[A2dpService] %{public}s Set sampleRate(%{public}u)\n", __func__, codecInformation.sampleRate);
1221     LOG_INFO("[A2dpService] %{public}s Set bitsPerSample(%{public}u)\n", __func__, codecInformation.bitsPerSample);
1222     LOG_INFO("[A2dpService] %{public}s Set channelMode(%{public}u)\n", __func__, codecInformation.channelMode);
1223 
1224     for (A2dpSrcCodecInfo info : codecStatus.codecInfoLocalCap) {
1225         LOG_INFO("[A2dpService] %{public}s codecType(%{public}u)\n", __func__, info.codecType);
1226         LOG_INFO("[A2dpService] %{public}s sampleRate(%{public}u)\n", __func__, info.sampleRate);
1227         LOG_INFO("[A2dpService] %{public}s bitsPerSample(%{public}u)\n", __func__, info.bitsPerSample);
1228         LOG_INFO("[A2dpService] %{public}s channelMode(%{public}u)\n", __func__, info.channelMode);
1229         if ((info.codecType == codecInformation.codecType)
1230             && ((info.sampleRate & codecInformation.sampleRate) == codecInformation.sampleRate)
1231             && ((info.bitsPerSample & codecInformation.bitsPerSample) == codecInformation.bitsPerSample)
1232             && ((info.channelMode & codecInformation.channelMode) == codecInformation.channelMode)) {
1233             return true;
1234         }
1235     }
1236     return false;
1237 }
1238 
GetServiceInstance(uint8_t role)1239 A2dpService *GetServiceInstance(uint8_t role)
1240 {
1241     LOG_INFO("[A2dpService] %{public}s role(%u) \n", __func__, role);
1242     IProfileManager *servManager = IProfileManager::GetInstance();
1243     A2dpService *service = nullptr;
1244 
1245     if (role == A2DP_ROLE_SOURCE) {
1246         service = static_cast<A2dpService *>(servManager->GetProfileService(PROFILE_NAME_A2DP_SRC));
1247     } else {
1248         service = static_cast<A2dpService *>(servManager->GetProfileService(PROFILE_NAME_A2DP_SINK));
1249     }
1250     return service;
1251 }
1252 
GetProfileInstance(uint8_t role)1253 A2dpProfile *GetProfileInstance(uint8_t role)
1254 {
1255     LOG_INFO("[A2dpProfile] %{public}s role(%u)\n", __func__, role);
1256     A2dpProfile *profile = nullptr;
1257 
1258     if (role == AVDT_ROLE_SNK) {
1259         profile = A2dpSnkProfile::GetInstance();
1260     } else {
1261         profile = A2dpSrcProfile::GetInstance();
1262     }
1263     return profile;
1264 }
1265 }  // namespace bluetooth
1266 }  // namespace OHOS