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