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