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