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