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_profile.h"
17 #include <cstring>
18 #include "a2dp_avdtp.h"
19 #include "a2dp_codec_thread.h"
20 #include "a2dp_encoder_sbc.h"
21 #include "a2dp_service.h"
22 #include "a2dp_sink.h"
23 #include "a2dp_source.h"
24 #include "adapter_config.h"
25 #include "log.h"
26 #include "log_util.h"
27 #include "profile_service_manager.h"
28 #include "raw_address.h"
29 #include "securec.h"
30 
31 namespace OHOS {
32 namespace bluetooth {
33 const int CODEC_SBC_TYPE_INDEX = 2;
34 const int SAMPLE_SBC_INDEX = 3;
35 const int CODEC_LENGTH = 8;
36 const int  BIT_MOVE8 = 8;
37 uint8_t A2dpProfile::g_linkNum = 0;
38 bool A2dpProfile::g_registGap = false;
39 std::mutex g_profileMutex;
40 const std::string A2DP_IDLE_ADDRESS = "00:00:00:00:00:00";
41 
RegisterServiceSecurity(GAP_ServiceConnectDirection direction, GAP_Service serviceId, GAP_SecMultiplexingProtocol protocolId, GapSecChannel channelId, uint16_t securityMode)42 int A2dpProfile::RegisterServiceSecurity(GAP_ServiceConnectDirection direction, GAP_Service serviceId,
43     GAP_SecMultiplexingProtocol protocolId, GapSecChannel channelId, uint16_t securityMode)
44 {
45     LOG_INFO("[A2dpGap]%{public}s\n", __func__);
46 
47     GapServiceSecurityInfo securityInfo = {direction, serviceId, protocolId, channelId};
48     int ret = GAPIF_RegisterServiceSecurity(nullptr, &securityInfo, securityMode);
49 
50     return ret;
51 }
52 
DeregisterServiceSecurity(GAP_ServiceConnectDirection direction, GAP_Service serviceId)53 int A2dpProfile::DeregisterServiceSecurity(GAP_ServiceConnectDirection direction, GAP_Service serviceId)
54 {
55     LOG_INFO("[A2dpGap]%{public}s\n", __func__);
56 
57     GapServiceSecurityInfo securityInfo = {direction, serviceId, SEC_PROTOCOL_L2CAP, {AVDT_PSM}};
58     int ret = GAPIF_DeregisterServiceSecurity(nullptr, &securityInfo);
59 
60     return ret;
61 }
62 
A2dpProfile(const uint8_t role)63 A2dpProfile::A2dpProfile(const uint8_t role)
64 {
65     LOG_INFO("[A2dpProfile]%{public}s role(%u)\n", __func__, role);
66 
67     role_ = role;
68     sdpInstance_.SetProfileRole(role_);
69 
70     packetQueue_ = QueueCreate(MAX_PCM_FRAME_NUM_PER_TICK * FRAME_THREE);
71     buffer_ = new A2dpSharedBuffer();
72 }
73 
~A2dpProfile()74 A2dpProfile::~A2dpProfile()
75 {
76     LOG_INFO("[A2dpProfile]%{public}s\n", __func__);
77 
78     for (const auto &it : peers_) {
79         delete it.second;
80     }
81     if (packetQueue_ != nullptr) {
82         QueueDelete(packetQueue_, CleanPacketData);
83         packetQueue_ = nullptr;
84     }
85     if (buffer_ != nullptr) {
86         delete buffer_;
87         buffer_ = nullptr;
88     }
89     peers_.clear();
90 }
91 
GetRole() const92 uint8_t A2dpProfile::GetRole() const
93 {
94     std::lock_guard<std::mutex> lock(g_profileMutex);
95 
96     LOG_INFO("[A2dpProfile]%{public}s role(%u)\n", __func__, role_);
97 
98     return role_;
99 }
100 
GetProfileEnable() const101 bool A2dpProfile::GetProfileEnable() const
102 {
103     std::lock_guard<std::mutex> lock(g_profileMutex);
104 
105     LOG_INFO("[A2dpProfile]%{public}s enable(%{public}d)\n", __func__, enable_);
106 
107     return enable_;
108 }
109 
SetProfileEnable(bool value)110 void A2dpProfile::SetProfileEnable(bool value)
111 {
112     std::lock_guard<std::mutex> lock(g_profileMutex);
113 
114     LOG_INFO("[A2dpProfile]%{public}s enableValue(%{public}d)\n", __func__, value);
115 
116     enable_ = value;
117 }
118 
SetActivePeer(const BtAddr &peer)119 void A2dpProfile::SetActivePeer(const BtAddr &peer)
120 {
121     LOG_INFO("[A2dpProfile]%{public}s\n", __func__);
122     std::lock_guard<std::mutex> lock(g_profileMutex);
123     activePeer_ = peer;
124 }
125 
GetActivePeer() const126 const BtAddr &A2dpProfile::GetActivePeer() const
127 {
128     LOG_INFO("[A2dpProfile]%{public}s\n", __func__);
129     std::lock_guard<std::mutex> lock(g_profileMutex);
130     return activePeer_;
131 }
132 
Enable()133 void A2dpProfile::Enable()
134 {
135     AvdtRegisterParam avdtRcb = {};
136     uint8_t role = GetRole();
137     A2dpAvdtp avdtpInstance(role);
138     CodecInfo codecInfo = {};
139 
140     (void)memset_s(&codecInfo, sizeof(CodecInfo), 0, sizeof(CodecInfo));
141     avdtRcb.mtu = A2DP_MAX_AVDTP_MTU_SIZE;
142     avdtRcb.role = AVDT_ROLE_SRC;
143     avdtpInstance.RegisterAvdtp(avdtRcb);
144 
145     if (GetProfileEnable()) {
146         return;
147     }
148 
149     if (!GetGapRegisterInfo()) {
150         UpdateGapRegisterInfo(true);
151         RegisterServiceSecurity(INCOMING, GAVDP_ACP,
152             SEC_PROTOCOL_L2CAP, { .l2capPsm = AVDT_PSM },
153             GAP_SEC_IN_AUTHENTICATION | GAP_SEC_OUT_AUTHENTICATION);
154         RegisterServiceSecurity(OUTGOING, GAVDP_INT,
155             SEC_PROTOCOL_L2CAP, { .l2capPsm = AVDT_PSM },
156             GAP_SEC_IN_AUTHENTICATION | GAP_SEC_OUT_AUTHENTICATION);
157     }
158 
159     // register local stream endpoint
160     if (role == A2DP_ROLE_SOURCE) {
161         CreateSEPConfigureInfo(A2DP_ROLE_SOURCE);
162     } else {
163         CreateSEPConfigureInfo(A2DP_ROLE_SINK);
164     }
165 
166     GetSDPInstance().RegisterService();
167     SetProfileEnable(true);
168 }
169 
ProcessAvdtpCallback(const BtAddr &addr, const utility::Message &message)170 void A2dpProfile::ProcessAvdtpCallback(const BtAddr &addr, const utility::Message &message)
171 {
172     A2dpAvdtMsg *msg = static_cast<A2dpAvdtMsg*>(message.arg2_);
173     uint8_t role = GetRole();
174     uint8_t event = msg->event;
175     A2dpProfilePeer *peer = FindOrCreatePeer(addr, role);
176     if (peer == nullptr) {
177         LOG_ERROR("[A2dpService] %{public}s Failed to get peer instance\n", __func__);
178         return;
179     }
180     A2dpAvdtp avdtpInstance(role);
181     A2dpAvdtMsg *msgParsed =
182         avdtpInstance.ParseAvdtpCallbackContent(msg->handle, addr, msg->event, msg->a2dpMsg.msg, role);
183 
184     if (msgParsed != nullptr) {
185         msgParsed->role = role;
186         utility::Message data(msgParsed->event, 0, msgParsed);
187         LOG_INFO("[A2dpProfile] %{public}s cmd(%u)\n", __func__, msgParsed->event);
188         peer->GetStateMachine()->ProcessMessage(data);
189         delete msgParsed;
190         msgParsed = nullptr;
191     } else {
192         if (event == AVDT_CONNECT_IND_EVT) {
193             DeletePeer(addr);
194         }
195     }
196 }
197 
ConnectStateChangedNotify(const BtAddr &addr, const int state, void *context)198 void A2dpProfile::ConnectStateChangedNotify(const BtAddr &addr, const int state, void *context)
199 {
200     LOG_INFO("[A2dpProfile] %{public}s state(%{public}d)\n", __func__, state);
201     switch (state) {
202         case STREAM_CONNECT_FAILED:
203         case STREAM_DISCONNECT:
204             ResetDelayValue(addr);
205             DeletePeer(addr);
206             if (IsActiveDevice(addr)) {
207                 ClearActiveDevice();
208             }
209             QueueFlush(packetQueue_, CleanPacketData);
210             buffer_->Reset();
211             break;
212         case STREAM_CONNECT:
213             SetActivePeer(addr);
214             break;
215         default:
216             break;
217     }
218     if (a2dpSvcCBack_ != nullptr) {
219         a2dpSvcCBack_->OnConnectStateChanged(addr, state, context);
220     } else {
221         LOG_ERROR("[A2dpProfile] %{public}s Can't find observer objest \n", __func__);
222     }
223 }
224 
AudioStateChangedNotify(const BtAddr &addr, const int state, void *context) const225 void A2dpProfile::AudioStateChangedNotify(const BtAddr &addr, const int state, void *context) const
226 {
227     LOG_INFO("[A2dpProfile] %{public}s state(%{public}d)\n", __func__, state);
228     if (state == A2DP_IS_PLAYING) {
229         buffer_->SetValid(true);
230     } else {
231         buffer_->SetValid(false);
232     }
233     if (a2dpSvcCBack_ != nullptr) {
234         a2dpSvcCBack_->OnAudioStateChanged(addr, state, context);
235     } else {
236         LOG_ERROR("[A2dpProfile] %{public}s Can't find observer objest \n", __func__);
237     }
238 }
239 
CodecChangedNotify(const BtAddr &addr, void *context) const240 void A2dpProfile::CodecChangedNotify(const BtAddr &addr, void *context) const
241 {
242     LOG_INFO("[A2dpProfile] %{public}s", __func__);
243     A2dpProfilePeer *peer = FindPeerByAddress(addr);
244 
245     if (a2dpSvcCBack_ != nullptr && peer != nullptr) {
246         a2dpSvcCBack_->OnCodecStateChanged(addr, peer->GetCodecStatus(), context);
247     } else {
248         LOG_ERROR("[A2dpProfile] %{public}s Can't find observer objest \n", __func__);
249     }
250 }
251 
SetUserCodecConfigure(const BtAddr &addr, const A2dpSrcCodecInfo &info)252 int A2dpProfile::SetUserCodecConfigure(const BtAddr &addr, const A2dpSrcCodecInfo &info)
253 {
254     LOG_INFO("[A2dpProfile] %{public}s", __func__);
255     int ret;
256     uint8_t role = GetRole();
257     A2dpProfile *profile = GetProfileInstance(role);
258     if (profile == nullptr) {
259         LOG_ERROR("[A2dpProfile] %{public}s Can't find the instance of profile\n", __func__);
260         ret = RET_NO_SUPPORT;
261         return ret;
262     }
263 
264     A2dpProfilePeer *peer = profile->FindPeerByAddress(addr);
265     if (peer == nullptr) {
266         LOG_ERROR("[A2dpProfile] %{public}s Can't find the instance of peer\n", __func__);
267         ret = RET_BAD_PARAM;
268         return ret;
269     }
270 
271     ret = peer->SetUserCodecConfigure(info);
272 
273     return ret;
274 }
275 
IsActiveDevice(const BtAddr &addr) const276 bool A2dpProfile::IsActiveDevice(const BtAddr &addr) const
277 {
278     bool ret = false;
279     RawAddress rawAddress = RawAddress::ConvertToString(addr.addr);
280     RawAddress activeAddr = RawAddress::ConvertToString(GetActivePeer().addr);
281     std::lock_guard<std::mutex> lock(g_profileMutex);
282 
283     HILOGI("[A2dpProfile] current active address(%{public}s)", GetEncryptAddr(activeAddr.GetAddress()).c_str());
284     if (strcmp(activeAddr.GetAddress().c_str(), rawAddress.GetAddress().c_str()) == 0) {
285         HILOGI("[A2dpProfile] connect address(%{public}s)", GetEncryptAddr(rawAddress.GetAddress()).c_str());
286         ret = true;
287     }
288     return ret;
289 }
290 
ClearActiveDevice()291 void A2dpProfile::ClearActiveDevice()
292 {
293     std::lock_guard<std::mutex> lock(g_profileMutex);
294 
295     (void)memset_s(&activePeer_, sizeof(BtAddr), 0, sizeof(BtAddr));
296 }
297 
EnableOptionalCodec(const BtAddr &addr, bool value)298 bool A2dpProfile::EnableOptionalCodec(const BtAddr &addr, bool value)
299 {
300     LOG_INFO("[A2dpProfile] %{public}s\n", __func__);
301     bool ret = true;
302     A2dpProfilePeer *peer = FindPeerByAddress(addr);
303     if (peer != nullptr) {
304         ret = peer->EnableOptionalCodec(value);
305     } else {
306         LOG_ERROR("[A2dpProfile] %{public}s Can't get the device of peer\n", __func__);
307     }
308 
309     return ret;
310 }
311 
312 
NotifyEncoder(const BtAddr &addr) const313 void A2dpProfile::NotifyEncoder(const BtAddr &addr) const
314 {
315     LOG_INFO("[A2dpProfile] %{public}s\n", __func__);
316     A2dpProfilePeer *peer = FindPeerByAddress(addr);
317     if (peer != nullptr) {
318         peer->NotifyEncoder();
319     } else {
320         LOG_ERROR("[A2dpProfile] %{public}s Can't get the device of peer\n", __func__);
321     }
322 }
323 
NotifyDecoder(const BtAddr &addr) const324 void A2dpProfile::NotifyDecoder(const BtAddr &addr) const
325 {
326     LOG_INFO("[A2dpProfile] %{public}s\n", __func__);
327 
328     A2dpProfilePeer *peer = FindPeerByAddress(addr);
329     if (peer != nullptr) {
330         peer->NotifyDecoder();
331     } else {
332         LOG_ERROR("[A2dpProfile] %{public}s Can't get the device of peer\n", __func__);
333     }
334 }
335 
SetPcmData(const uint8_t *buf, uint32_t size)336 uint32_t A2dpProfile::SetPcmData(const uint8_t *buf, uint32_t size)
337 {
338     LOG_INFO("[A2dpProfile] %{public}s %{public}u\n", __func__, size);
339 
340     uint32_t actualWrittenBytes = buffer_->Write(buf, size);
341     LOG_INFO("[A2dpProfile] %{public}s expectedWrittenBytes(%{public}u) actualWrittenBytes(%{public}u)\n",
342         __func__, size, actualWrittenBytes);
343     if (actualWrittenBytes == 0) {
344         LOG_ERROR("[A2dpProfile] %{public}s failed\n", __func__);
345     }
346     return actualWrittenBytes;
347 }
348 
GetPcmData(uint8_t *buf, uint32_t size)349 uint32_t A2dpProfile::GetPcmData(uint8_t *buf, uint32_t size)
350 {
351     LOG_INFO("[A2dpProfile] %{public}s\n", __func__);
352 
353     uint32_t actualReadBytes = buffer_->Read(buf, size);
354     LOG_INFO("[A2dpProfile] %{public}s expectedReadBytes(%{public}u) actualReadBytes(%{public}u)\n",
355         __func__, size, actualReadBytes);
356     if (actualReadBytes == 0) {
357         LOG_ERROR("[A2dpProfile] %{public}s failed\n", __func__);
358         return false;
359     }
360     return actualReadBytes;
361 }
362 
GetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp)363 void A2dpProfile::GetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp)
364 {
365     LOG_INFO("[A2dpProfile] %{public}s\n", __func__);
366 
367     A2dpCodecThread *codecThread = A2dpCodecThread::GetInstance();
368     delayValue = delayValue_;
369     codecThread->GetRenderPosition(sendDataSize, timeStamp);
370 }
371 
DequeuePacket()372 void A2dpProfile::DequeuePacket()
373 {
374     LOG_INFO("[A2dpProfile] %{public}s \n", __func__);
375     A2dpProfilePeer *peer = FindOrCreatePeer(activePeer_, A2DP_ROLE_SOURCE);
376     if (peer != nullptr) {
377         int32_t count = QueueGetSize(packetQueue_);
378         LOG_INFO("[A2dpProfile] %{public}s QueueTryDequeue starts, count %{public}d \n", __func__, count);
379         PacketData *packetData = (PacketData *)QueueTryDequeue(packetQueue_);
380         if (packetData == nullptr) {
381             LOG_ERROR("[A2dpProfile] %{public}s no data\n", __func__);
382             return;
383         }
384         count = QueueGetSize(packetQueue_);
385         LOG_INFO("[A2dpProfile] %{public}s  packetData is not null, QueueTryDequeue ends, count %{public}d\n",
386             __func__, count);
387         peer->SendPacket(packetData->packet, packetData->frames, packetData->bytes, packetData->pktTimeStamp);
388         PacketFree(packetData->packet);
389         free(packetData);
390         packetData = nullptr;
391     } else {
392         LOG_ERROR("[A2dpProfile] %{public}s no peer\n", __func__);
393     }
394 }
395 
EnqueuePacket(const Packet *packet, size_t frames, uint32_t bytes, uint32_t pktTimeStamp)396 void A2dpProfile::EnqueuePacket(const Packet *packet, size_t frames, uint32_t bytes, uint32_t pktTimeStamp)
397 {
398     Packet *refpkt = nullptr;
399     PacketData *packetData = nullptr;
400     int32_t count = QueueGetSize(packetQueue_);
401     LOG_INFO("[A2dpProfile] %{public}s, frame %{public}u, count %{public}d \n", __func__, bytes, count);
402     if (count >= MAX_PCM_FRAME_NUM_PER_TICK * FRAME_THREE) {
403         QueueFlush(packetQueue_, CleanPacketData);
404     }
405     count = QueueGetSize(packetQueue_);
406     LOG_INFO("[A2dpProfile] %{public}s, after flush count %{public}d \n", __func__, count);
407     refpkt = PacketRefMalloc((Packet *)packet);
408     packetData = (PacketData *)malloc(sizeof(PacketData));
409     if (packetData == nullptr) {
410         LOG_ERROR("[A2dpProfile] %{public}s, packetData is NULL\n", __func__);
411         return;
412     }
413     packetData->packet = refpkt;
414     packetData->frames = frames;
415     packetData->bytes = bytes;
416     packetData->pktTimeStamp = pktTimeStamp;
417 
418     QueueEnqueue(packetQueue_, (void *)packetData);
419     count = QueueGetSize(packetQueue_);
420     LOG_INFO("[A2dpProfile] %{public}s ends count %{public}d \n", __func__, count);
421 }
422 
CreateSEPConfigureInfo(uint8_t role)423 void A2dpProfile::CreateSEPConfigureInfo(uint8_t role)
424 {
425     AvdtStreamConfig cfg[AVDT_NUM_SEPS] = {};
426     A2dpAvdtp avdtp(role);
427     uint8_t number = 0;
428 
429     for (int i = A2DP_SOURCE_CODEC_INDEX_SBC; i < A2DP_CODEC_INDEX_MAX; i++) {
430         int value = 0x01;
431         LOG_INFO("[A2dpProfile]%{public}s index (%{public}d)\n", __func__, i);
432         if (i < A2DP_SINK_CODEC_INDEX_MIN) {
433             cfg[number].sepType = AVDT_ROLE_SRC;
434             cfg[number].cfg.mediaType = A2DP_MEDIA_TYPE_AUDIO;
435             if (A2DP_SOURCE_CODEC_INDEX_SBC == i) {
436                 AdapterConfig::GetInstance()->GetValue(SECTION_A2DP_SRC_SERVICE, PROPERTY_CODEC_SBC_SUPPORT, value);
437                 LOG_INFO("[A2dpProfile] %{public}s SRC SBC value[%{public}d] \n", __func__, value);
438                 if (!value) {
439                     continue;
440                 }
441                 BuildCodecInfo(A2DP_SOURCE_CODEC_INDEX_SBC, cfg[number].cfg.codecInfo);
442                 cfg[number].cfg.numCodec = A2DP_CODEC_SBC_INFO_LEN;
443             } else if (A2DP_SOURCE_CODEC_INDEX_AAC == i) {
444                 AdapterConfig::GetInstance()->GetValue(SECTION_A2DP_SRC_SERVICE, PROPERTY_CODEC_AAC_SUPPORT, value);
445                 LOG_INFO("[A2dpProfile] %{public}s SRC AAC value[%{public}d] \n", __func__, value);
446                 if (!value) {
447                     continue;
448                 }
449                 BuildCodecInfo(A2DP_SOURCE_CODEC_INDEX_AAC, cfg[number].cfg.codecInfo);
450                 cfg[number].cfg.numCodec = A2DP_CODEC_AAC_INFO_LEN;
451             }
452             cfg[number].codecIndex = i;
453             cfg[number].sinkDataCback = ProcessSinkStream;
454             cfg[number].cfg.pscMask = (AVDT_PSC_MSK_TRANS | AVDT_PSC_MSK_DELAY_RPT | AVDT_PSC_MSK_CODEC);
455         } else {
456             cfg[number].sepType = AVDT_ROLE_SNK;
457             cfg[number].cfg.mediaType = A2DP_MEDIA_TYPE_AUDIO;
458             if (A2DP_SINK_CODEC_INDEX_SBC == i) {
459                 AdapterConfig::GetInstance()->GetValue(SECTION_A2DP_SNK_SERVICE, PROPERTY_CODEC_SBC_SUPPORT, value);
460                 LOG_INFO("[A2dpProfile] %{public}s SNK SBC value[%{public}d] \n", __func__, value);
461                 if (!value) {
462                     continue;
463                 }
464                 BuildCodecInfo(A2DP_SINK_CODEC_INDEX_SBC, cfg[number].cfg.codecInfo);
465                 cfg[number].cfg.numCodec = A2DP_CODEC_SBC_INFO_LEN;
466             } else if (A2DP_SINK_CODEC_INDEX_AAC == i) {
467                 AdapterConfig::GetInstance()->GetValue(SECTION_A2DP_SNK_SERVICE, PROPERTY_CODEC_AAC_SUPPORT, value);
468                 LOG_INFO("[A2dpProfile] %{public}s SNK AAC value[%{public}d] \n", __func__, value);
469                 if (!value) {
470                     continue;
471                 }
472                 BuildCodecInfo(A2DP_SINK_CODEC_INDEX_AAC, cfg[number].cfg.codecInfo);
473                 cfg[number].cfg.numCodec = A2DP_CODEC_AAC_INFO_LEN;
474             }
475             cfg[number].codecIndex = i;
476             cfg[number].sinkDataCback = ProcessSinkStream;
477             cfg[number].cfg.pscMask = (AVDT_PSC_MSK_TRANS | AVDT_PSC_MSK_DELAY_RPT | AVDT_PSC_MSK_CODEC);
478         }
479         number++;
480     }
481     avdtp.RegisterLocalSEP(cfg, number);
482 }
483 
BuildCodecInfo(A2dpCodecIndex index, uint8_t *data)484 void A2dpProfile::BuildCodecInfo(A2dpCodecIndex index, uint8_t *data)
485 {
486     LOG_INFO("[A2dpProfile]%{public}s index(%u)\n", __func__, index);
487     switch (index) {
488         case A2DP_SINK_CODEC_INDEX_SBC:
489             *data++ = A2DP_CODEC_SBC_INFO_LEN;
490             *data++ = A2DP_MEDIA_TYPE_AUDIO;
491             *data++ = A2DP_CODEC_TYPE_SBC;
492             *data++ = A2DP_SBC_SINK_CAPS.sampleFreq | A2DP_SBC_SINK_CAPS.channelMode;
493             *data++ = A2DP_SBC_SINK_CAPS.blockLen | A2DP_SBC_SINK_CAPS.numSubbands |
494                 A2DP_SBC_SINK_CAPS.allocatedMethod;
495             *data++ = A2DP_SBC_SINK_CAPS.minBitpool;
496             *data = A2DP_SBC_SINK_CAPS.maxBitpool;
497             break;
498         case A2DP_SOURCE_CODEC_INDEX_SBC:
499             *data++ = A2DP_CODEC_SBC_INFO_LEN;
500             *data++ = A2DP_MEDIA_TYPE_AUDIO;
501             *data++ = A2DP_CODEC_TYPE_SBC;
502             *data++ = A2DP_SBC_SOURCE_CAPS.sampleFreq | A2DP_SBC_SOURCE_CAPS.channelMode;
503             *data++ = A2DP_SBC_SOURCE_CAPS.blockLen | A2DP_SBC_SOURCE_CAPS.numSubbands |
504                 A2DP_SBC_SOURCE_CAPS.allocatedMethod;
505             *data++ = A2DP_SBC_SOURCE_CAPS.minBitpool;
506             *data = A2DP_SBC_SOURCE_CAPS.maxBitpool;
507             break;
508         case A2DP_SINK_CODEC_INDEX_AAC:
509         case A2DP_SOURCE_CODEC_INDEX_AAC:
510             *data++ = A2DP_CODEC_AAC_INFO_LEN;
511             *data++ = A2DP_MEDIA_TYPE_AUDIO;
512             *data++ = A2DP_CODEC_TYPE_AAC;
513             *data++ = A2DP_AAC_MPEG2_OBJECT_TYPE;         // object type
514             *data++ = A2DP_AAC_SAMPLE_RATE_OCTET1_44100;  // octet1
515             *data++ = (A2DP_AAC_SAMPLE_RATE_OCTET2_48000 >> BIT_MOVE8) | A2DP_AAC_CHANNEL_MODE_OCTET2_DOUBLE |
516                       A2DP_AAC_CHANNEL_MODE_OCTET2_SINGLE;
517             // octet2: b4~7:sampleFrequency b2: dual channels b3: single channel
518             *data++ = A2DP_AAC_VARIABLE_BIT_RATE_DISABLED;  // octect3 b7: vbr   b6 ~b0: bitrate22 ~ 16
519             *data++ = 0x00;                                 // octet 4 bit rate 8 ~ 15
520             *data = A2DP_SAMPLE_BITS_16; // octet 5 bitrate 0 ~7
521             break;
522         default:
523             break;
524     }
525 }
526 
Disable()527 void A2dpProfile::Disable()
528 {
529     LOG_INFO("[A2dpProfile]%{public}s enable(%{public}d) role(%u)\n", __func__, GetProfileEnable(), GetRole());
530 
531     A2dpAvdtMsg data = {};
532     utility::Message msg(EVT_DISCONNECT_REQ, 0, &data);
533     A2dpProfilePeer *peer = nullptr;
534     uint8_t role = GetRole();
535 
536     if (!GetProfileEnable()) {
537         return;
538     }
539     SetProfileEnable(false);
540 
541     for (const auto &it : peers_) {
542         peer = it.second;
543         HILOGI("[A2dpProfile] matched peers_addr(%{public}s) [role%u]\n", GetEncryptAddr(it.first).c_str(), role);
544         if (peer != nullptr && it.first.c_str() != nullptr) {
545             data.a2dpMsg.connectInfo.addr = peer->GetPeerAddress();
546             data.role = role;
547             msg.arg2_ = &data;
548             peer->GetStateMachine()->ProcessMessage(msg);
549             peer->SetCurrentCmd(EVT_DISCONNECT_REQ);
550             break;
551         }
552     }
553     if (GetGapRegisterInfo()) {
554         UpdateGapRegisterInfo(false);
555         DeregisterServiceSecurity(INCOMING, GAVDP_ACP);
556         DeregisterServiceSecurity(OUTGOING, GAVDP_INT);
557     }
558 
559     GetSDPInstance().UnregisterService();
560     ClearNumberPeerDevice();
561 
562     QueueFlush(packetQueue_, CleanPacketData);
563     buffer_->Reset();
564 }
565 
GetSDPInstance(void) const566 A2dpSdpManager A2dpProfile::GetSDPInstance(void) const
567 {
568     std::lock_guard<std::mutex> lock(g_profileMutex);
569 
570     return sdpInstance_;
571 }
GetConfigure() const572 const ConfigureStream &A2dpProfile::GetConfigure() const
573 {
574     LOG_INFO("[A2dpProfile]%{public}s\n", __func__);
575     std::lock_guard<std::mutex> lock(g_profileMutex);
576     return configureStream_;
577 }
578 
SetConfigure(const BtAddr &addr)579 void A2dpProfile::SetConfigure(const BtAddr &addr)
580 {
581     std::lock_guard<std::mutex> lock(g_profileMutex);
582 
583     A2dpProfilePeer *peer = FindPeerByAddress(addr);
584     if (peer != nullptr) {
585         (void)memset_s(&configureStream_, sizeof(ConfigureStream), 0, sizeof(ConfigureStream));
586         configureStream_.cfg = peer->GetPeerCapabilityInfo();
587         configureStream_.intSeid = peer->GetIntSeid();
588         configureStream_.acpSeid = peer->GetAcpSeid();
589         configureStream_.addr = addr;
590     }
591 
592     LOG_INFO("[A2dpProfile]%{public}s AcpSeid(%u) intseid(%u)\n",
593         __func__, configureStream_.acpSeid, configureStream_.intSeid);
594 }
595 
Connect(const BtAddr &device)596 int A2dpProfile::Connect(const BtAddr &device)
597 {
598     LOG_INFO("[A2dpProfile]%{public}s\n", __func__);
599 
600     A2dpProfile *a2dpInstance = nullptr;
601     uint8_t role = GetRole();
602     if (role == A2DP_ROLE_SOURCE) {
603         a2dpInstance = A2dpSrcProfile::GetInstance();
604     } else {
605         a2dpInstance = A2dpSnkProfile::GetInstance();
606     }
607     FindOrCreatePeer(device, role);
608     if (GetSDPInstance().FindSnkService(device, a2dpInstance, A2dpProfilePeer::SDPServiceCallback) != BT_SUCCESS) {
609         LOG_WARN("[A2dpProfile]%{public}s SDP_ServiceSearch Error\n", __func__);
610     }
611     return A2DP_SUCCESS;
612 }
613 
ProcessSDPCallback(const BtAddr &addr, uint8_t result)614 void A2dpProfile::ProcessSDPCallback(const BtAddr &addr, uint8_t result)
615 {
616     if (result != A2DP_SUCCESS) {
617         CallbackParameter param = {A2DP_ROLE_INT, true, 0};
618         ConnectStateChangedNotify(addr, STREAM_DISCONNECT, (void *)&param);
619         LOG_INFO("[A2dpProfile]%{public}s Failed to get SDPresult(%hhu)\n", __func__, result);
620         return;
621     }
622 
623     /// Check sdp information
624     uint8_t role = GetRole();
625     A2dpAvdtMsg data = {};
626     A2dpProfilePeer *peer = FindOrCreatePeer(addr, role);
627     utility::Message msg(EVT_CONNECT_REQ, 0, &data);
628 
629     data.a2dpMsg.connectInfo.addr = addr;
630     data.role = role;
631     msg.arg2_ = &data;
632     if (peer == nullptr) {
633         LOG_ERROR("[A2dpProfile]%{public}s Not resources", __func__);
634     } else {
635         if (!peer->GetSDPServiceCapability()) {
636             msg.arg1_ = EVT_SDP_CFM;
637             LOG_ERROR("[A2dpProfile]%{public}s Can't find peer service matched. role(%u)", __func__, data.role);
638         }
639         peer->GetStateMachine()->ProcessMessage(msg);
640         peer->SetCurrentCmd(EVT_CONNECT_REQ);
641         peer->SetInitSide(true);
642     }
643 }
644 
Disconnect(const BtAddr &device)645 int A2dpProfile::Disconnect(const BtAddr &device)
646 {
647     int ret = 0;
648     A2dpProfilePeer *peer = nullptr;
649     A2dpAvdtMsg data = {};
650     utility::Message msg(EVT_DISCONNECT_REQ, 0, &data);
651 
652     data.a2dpMsg.connectInfo.addr = device;
653     data.role = GetRole();
654     msg.arg2_ = &data;
655     peer = FindPeerByAddress(device);
656     if (peer == nullptr) {
657         ret = AVDT_NO_RESOURCES;
658         LOG_ERROR("[A2dpProfile]%{public}s Not resources", __func__);
659     } else {
660         if (peer->GetCurrentCmd() != EVT_SDP_DISC && peer->GetCurrentCmd() != EVT_CONNECT_REQ) {
661             ret = peer->GetStateMachine()->ProcessMessage(msg);
662             peer->SetCurrentCmd(EVT_DISCONNECT_REQ);
663         } else {
664             peer->SetDisconnectIndication(true);
665         }
666     }
667 
668     return ret;
669 }
670 
Stop(const uint16_t handle, const bool suspend)671 int A2dpProfile::Stop(const uint16_t handle, const bool suspend)
672 {
673     LOG_INFO("[A2dpProfile]%{public}s handle(%u) suspend(%{public}d)\n", __func__, handle, suspend);
674     int ret = BT_SUCCESS;
675     A2dpProfilePeer *peer = nullptr;
676     A2dpAvdtMsg data = {};
677     utility::Message msg(EVT_SUSPEND_REQ, 0, &data);
678 
679     data.a2dpMsg.stream.handle = handle;
680     data.role = GetRole();
681     msg.arg2_ = &data;
682 
683     peer = FindPeerByHandle(handle);
684     if (peer == nullptr) {
685         ret = AVDT_BAD_PARAMS;
686         LOG_ERROR("[A2dpProfile]%{public}s invalid handle(%u) suspend(%{public}d)\n", __func__, handle, suspend);
687         return ret;
688     }
689 
690     if ((strcmp(A2DP_PROFILE_OPEN.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) ||
691         (strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0)) {
692         LOG_INFO("[A2dpProfile]%{public}s streaming exited now\n", __func__);
693         peer->GetStateMachine()->ProcessMessage(msg);
694     } else {
695         LOG_ERROR("[A2dpProfile]%{public}s Not streaming status now\n", __func__);
696         ret = AVDT_ERR_UNSUPPORTED_COMMAND;
697     }
698 
699     QueueFlush(packetQueue_, CleanPacketData);
700     buffer_->Reset();
701     return ret;
702 }
703 
Start(const uint16_t handle)704 int A2dpProfile::Start(const uint16_t handle)
705 {
706     LOG_INFO("[A2dpProfile]%{public}s handle(%hu)\n", __func__, handle);
707 
708     int ret = BT_SUCCESS;
709     uint8_t role = GetRole();
710     A2dpProfilePeer *peer = nullptr;
711     A2dpAvdtMsg data = {};
712     utility::Message msg(EVT_START_REQ, 0, &data);
713 
714     data.a2dpMsg.stream.handle = handle;
715     data.role = role;
716     msg.arg2_ = &data;
717     peer = FindPeerByHandle(handle);
718     if (peer == nullptr) {
719         ret = AVDT_BAD_PARAMS;
720         return ret;
721     }
722     if (strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
723         LOG_INFO("[A2dpProfile]%{public}s The state of stream is streaming now\n", __func__);
724         if (role == A2DP_ROLE_SOURCE) {
725             peer->NotifyEncoder();
726         } else if (role == A2DP_ROLE_SINK) {
727             peer->NotifyDecoder();
728         } else {
729             LOG_ERROR("[A2dpProfile]%{public}s Audio data is not ready\n", __func__);
730         }
731         peer->GetStateMachine()->ProcessMessage(msg);
732         return BT_SUCCESS;
733     }
734     if (!JudgeAllowedStreaming()) {
735         return AVDT_NO_RESOURCES;
736     }
737     peer->GetStateMachine()->ProcessMessage(msg);
738 
739     return ret;
740 }
741 
JudgeAllowedStreaming() const742 bool A2dpProfile::JudgeAllowedStreaming() const
743 {
744     bool ret = true;
745     A2dpProfilePeer *peerProfile = nullptr;
746 
747     for (const auto &it : peers_) {
748         peerProfile = it.second;
749         if (peerProfile != nullptr) {
750             LOG_INFO("[A2dpProfile]%{public}s state(%{public}s)\n",
751                 __func__, peerProfile->GetStateMachine()->GetStateName().c_str());
752             if (strcmp(A2DP_PROFILE_STREAMING.c_str(), peerProfile->GetStateMachine()->GetStateName().c_str()) == 0) {
753                 LOG_ERROR("[A2dpProfile]%{public}s there is one streaming exited now\n", __func__);
754                 ret = false;
755                 break;
756             }
757         }
758     }
759     return ret;
760 }
761 
Close(const uint16_t handle) const762 int A2dpProfile::Close(const uint16_t handle) const
763 {
764     int ret = BT_SUCCESS;
765     A2dpProfilePeer *peer = nullptr;
766     A2dpAvdtMsg data = {};
767     utility::Message msg(EVT_CLOSE_REQ, 0, &data);
768 
769     data.a2dpMsg.stream.handle = handle;
770     data.role = GetRole();
771     msg.arg2_ = &data;
772     peer = FindPeerByHandle(handle);
773     if (peer == nullptr) {
774         ret = AVDT_BAD_PARAMS;
775         return ret;
776     }
777 
778     if (strcmp(A2DP_PROFILE_OPEN.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0 ||
779         strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
780         LOG_INFO("[A2dpProfile]%{public}s open/streaming exited now\n", __func__);
781         peer->GetStateMachine()->ProcessMessage(msg);
782     } else {
783         LOG_ERROR("[A2dpProfile]%{public}s Not open/streaming status now\n", __func__);
784         ret = AVDT_ERR_UNSUPPORTED_COMMAND;
785     }
786     return ret;
787 }
788 
789 
HasStreaming()790 bool A2dpProfile::HasStreaming()
791 {
792     A2dpProfilePeer *peer = nullptr;
793     for (const auto &it : peers_) {
794         LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, it.second->GetStreamHandle());
795         peer = it.second;
796         if (peer != nullptr) {
797             if (strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
798                 LOG_INFO("[A2dpProfile]%{public}s streaming exited now\n", __func__);
799                 return true;
800             }
801         }
802     }
803     return false;
804 }
805 
HasOpen()806 bool A2dpProfile::HasOpen()
807 {
808     A2dpProfilePeer *peer = nullptr;
809     for (const auto &it : peers_) {
810         LOG_INFO("[A2dpProfile]%{public}s \n", __func__);
811         peer = it.second;
812         if (peer != nullptr) {
813             if (strcmp(A2DP_PROFILE_OPEN.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
814                 LOG_INFO("[A2dpProfile]%{public}s open exited now\n", __func__);
815                 return true;
816             }
817         }
818     }
819     return false;
820 }
821 
SetDisalbeTag(bool tag)822 void A2dpProfile::SetDisalbeTag(bool tag)
823 {
824     LOG_INFO("[A2dpProfile]%{public}s isDoDisable(%u)\n", __func__, tag);
825     isDoDisable_ = tag;
826 }
827 
GetDisalbeTag()828 bool A2dpProfile::GetDisalbeTag()
829 {
830     LOG_INFO("[A2dpProfile]%{public}s isDoDisable(%u)\n", __func__, isDoDisable_);
831     return isDoDisable_;
832 }
833 
CloseAll()834 void A2dpProfile::CloseAll()
835 {
836     for (const auto &it : peers_) {
837         LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, it.second->GetStreamHandle());
838         if (it.second != nullptr) {
839             Close(it.second->GetStreamHandle());
840         }
841     }
842 }
843 
SendDelay(const uint16_t handle, const uint16_t delayValue)844 int A2dpProfile::SendDelay(const uint16_t handle, const uint16_t delayValue)
845 {
846     LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, handle);
847     A2dpAvdtp avdtp(A2DP_ROLE_SINK);
848     uint8_t label = 0;
849 
850     int ret = avdtp.DelayReq(handle, label, delayValue);
851     return ret;
852 }
853 
CloseRsp(const uint16_t handle, const uint8_t errorCode) const854 int A2dpProfile::CloseRsp(const uint16_t handle, const uint8_t errorCode) const
855 {
856     LOG_INFO("[A2dpProfile]%{public}s handle(%u) role(%u)\n", __func__, handle, GetRole());
857     A2dpAvdtp avdtp(GetRole());
858     uint8_t label = 0;
859 
860     int ret = avdtp.CloseRsp(handle, label, errorCode);
861     return ret;
862 }
863 
WriteStream(const uint16_t handle, const uint8_t config, const uint8_t bitpool)864 int A2dpProfile::WriteStream(const uint16_t handle, const uint8_t config, const uint8_t bitpool)
865 {
866     LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, handle);
867 
868     A2dpAvdtp avdtp(A2DP_ROLE_SOURCE);
869     uint32_t timeStamp = 0x8FF;
870     Packet *pkt = PacketMalloc(0, 0, 0);
871     uint8_t pktType = 0;
872     uint16_t marker = 0x0B;
873     uint8_t codecInfo[CODEC_LENGTH] = {0x01, 0x9c, 0x00, 0x35, 0x00, 0x88, 0x88, 0x88};
874 
875     codecInfo[CODEC_SBC_TYPE_INDEX] = config;
876     codecInfo[SAMPLE_SBC_INDEX] = bitpool;
877     Buffer *encBuf = BufferMalloc(CODEC_LENGTH);
878     (void)memcpy_s(BufferPtr(encBuf), CODEC_LENGTH, codecInfo, CODEC_LENGTH);
879     PacketPayloadAddLast(pkt, encBuf);
880 
881     int ret = avdtp.WriteStream(handle, pkt, timeStamp, pktType, marker);
882     return ret;
883 }
884 
Reconfigure(const uint16_t handle, uint8_t *codecInfo) const885 int A2dpProfile::Reconfigure(const uint16_t handle, uint8_t *codecInfo) const
886 {
887     LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, handle);
888 
889     int ret = BT_SUCCESS;
890     A2dpProfilePeer *peer = nullptr;
891     A2dpAvdtMsg data = {};
892     utility::Message msg(EVT_RECONFIG_REQ, 0, &data);
893 
894     peer = FindPeerByHandle(handle);
895     if (peer == nullptr) {
896         ret = AVDT_BAD_PARAMS;
897         LOG_ERROR("[A2dpProfile]%{public}s invalid handle(%u) \n", __func__, handle);
898         return ret;
899     }
900 
901     (void)memcpy_s(data.a2dpMsg.configStream.cfg.codecInfo, A2DP_CODEC_SIZE, codecInfo,
902         sizeof(data.a2dpMsg.configStream.cfg.codecInfo));
903     data.a2dpMsg.configStream.cfg.mediaType = A2DP_MEDIA_TYPE_AUDIO;
904     data.a2dpMsg.configStream.cfg.numCodec = A2DP_CODEC_SBC_INFO_LEN;
905     data.a2dpMsg.configStream.cfg.pscMask = AVDT_PSC_MSK_CODEC;
906     data.a2dpMsg.configStream.intSeid = handle;
907     data.role = GetRole();
908     msg.arg2_ = &data;
909 
910     if (strcmp(A2DP_PROFILE_OPEN.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
911         LOG_INFO("[A2dpProfile]%{public}s streaming exited now\n", __func__);
912         peer->GetStateMachine()->ProcessMessage(msg);
913     } else {
914         LOG_ERROR("[A2dpProfile]%{public}s Not open status now\n", __func__);
915         ret = AVDT_ERR_UNSUPPORTED_COMMAND;
916     }
917 
918     return ret;
919 }
920 
DelayReportNotify(const BtAddr &device, const uint16_t delayValue)921 void A2dpProfile::DelayReportNotify(const BtAddr &device, const uint16_t delayValue)
922 {
923     LOG_INFO("[A2dpProfile]%{public}s delayValue(%{public}u)\n", __func__, delayValue);
924 
925     A2dpProfilePeer *peer = nullptr;
926     peer = FindPeerByAddress(device);
927     if (peer == nullptr) {
928         LOG_ERROR("[A2dpProfile]%{public}s Not resources", __func__);
929         return;
930     }
931 
932     delayValue_ = delayValue;
933 }
934 
ResetDelayValue(const BtAddr &device)935 void A2dpProfile::ResetDelayValue(const BtAddr &device)
936 {
937     LOG_INFO("[A2dpProfile]%{public}s", __func__);
938 
939     A2dpProfilePeer *peer = nullptr;
940     peer = FindPeerByAddress(device);
941     if (peer == nullptr) {
942         LOG_ERROR("[A2dpProfile]%{public}s Not resources", __func__);
943         return;
944     }
945     delayValue_ = 0;
946 }
947 
RegisterObserver(A2dpProfileObserver *observer)948 void A2dpProfile::RegisterObserver(A2dpProfileObserver *observer)
949 {
950     LOG_INFO("[A2dpProfile]%{public}s\n", __func__);
951 
952     a2dpSvcCBack_ = observer;
953     return;
954 }
955 
DeregisterObserver(A2dpProfileObserver *observer)956 void A2dpProfile::DeregisterObserver(A2dpProfileObserver *observer)
957 {
958     LOG_INFO("[A2dpProfile]%{public}s\n", __func__);
959     return;
960 }
961 
FindPeerByAddress(const BtAddr &peerAddress) const962 A2dpProfilePeer *A2dpProfile::FindPeerByAddress(const BtAddr &peerAddress) const
963 {
964     HILOGI("[A2dpProfile] addr(%{public}s)",
965         GetEncryptAddr(RawAddress::ConvertToString(peerAddress.addr).GetAddress()).c_str());
966     A2dpProfilePeer *peer = nullptr;
967 
968     for (const auto &it : peers_) {
969         if (strcmp(it.first.c_str(), RawAddress::ConvertToString(peerAddress.addr).GetAddress().c_str()) == 0) {
970             peer = it.second;
971             HILOGI("[A2dpProfile] matched peers_addr(%{public}s)\n", GetEncryptAddr(it.first).c_str());
972             return peer;
973         }
974         HILOGI("[A2dpProfile] peers_addr(%{public}s)\n", GetEncryptAddr(it.first).c_str());
975     }
976     return peer;
977 }
978 
FindPeerByHandle(uint16_t handle) const979 A2dpProfilePeer *A2dpProfile::FindPeerByHandle(uint16_t handle) const
980 {
981     LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, handle);
982     A2dpProfilePeer *peer = nullptr;
983 
984     for (const auto &it : peers_) {
985         LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, it.second->GetStreamHandle());
986         if (handle == it.second->GetStreamHandle()) {
987             peer = it.second;
988             break;
989         }
990     }
991     return peer;
992 }
993 
FindOrCreatePeer(const BtAddr &peerAddress, uint8_t localRole)994 A2dpProfilePeer *A2dpProfile::FindOrCreatePeer(const BtAddr &peerAddress, uint8_t localRole)
995 {
996     A2dpProfilePeer *peer = nullptr;
997     std::string addr = RawAddress::ConvertToString(peerAddress.addr).GetAddress();
998     peer = FindPeerByAddress(peerAddress);
999     if (peer != nullptr) {
1000         LOG_DEBUG("[A2dpProfile]%{public}s Peer is exited", __func__);
1001         return peer;
1002     }
1003     if (UpdateNumberPeerDevice(true)) {
1004         auto peerInstance = std::make_unique<A2dpProfilePeer>(peerAddress, localRole);
1005         peer = peerInstance.release();
1006         peers_.insert(std::make_pair(addr, peer));
1007         HILOGI("addr: %{public}s", GetEncryptAddr(addr).c_str());
1008     } else {
1009         HILOGE("Connected device is max: %{public}u", GetConnectedPeerDevice());
1010     }
1011     return peer;
1012 }
1013 
DeletePeer(const BtAddr &peerAddress)1014 bool A2dpProfile::DeletePeer(const BtAddr &peerAddress)
1015 {
1016     bool ret = false;
1017     std::map<std::string, A2dpProfilePeer *>::iterator it;
1018 
1019     if (IsActiveDevice(peerAddress)) {
1020         A2dpCodecThread *codecThread = A2dpCodecThread::GetInstance();
1021         if (codecThread != nullptr) {
1022             codecThread->StopA2dpCodecThread();
1023             delete codecThread;
1024         }
1025     }
1026 
1027     for (it = peers_.begin(); it != peers_.end(); it++) {
1028         if (strcmp(it->first.c_str(), RawAddress::ConvertToString(peerAddress.addr).GetAddress().c_str()) == 0) {
1029             delete it->second;
1030             peers_.erase(it);
1031             UpdateNumberPeerDevice(false);
1032             ret = true;
1033             HILOGI("[A2dpProfile] matched peers_addr(%{public}s)",
1034                 GetEncryptAddr(RawAddress::ConvertToString(peerAddress.addr).GetAddress()).c_str());
1035             break;
1036         }
1037         HILOGI("[A2dpProfile] peers_addr(%{public}s)\n", GetEncryptAddr(it->first).c_str());
1038     }
1039 
1040     return ret;
1041 }
1042 
UpdateNumberPeerDevice(bool plus)1043 bool A2dpProfile::UpdateNumberPeerDevice(bool plus)
1044 {
1045     std::lock_guard<std::mutex> lock(g_profileMutex);
1046     LOG_INFO("[A2dpProfile]%{public}s plus(%{public}d)\n", __func__, plus);
1047 
1048     if (plus) {
1049         g_linkNum++;
1050     } else {
1051         if (g_linkNum > 0) {
1052             g_linkNum--;
1053         }
1054     }
1055     if (g_linkNum > A2DP_CONNECT_NUM_MAX) {
1056         LOG_ERROR("[A2dpProfile]%{public}s linkNum(%u)\n", __func__, g_linkNum);
1057         g_linkNum = A2DP_CONNECT_NUM_MAX;
1058         return false;
1059     }
1060     LOG_INFO("[A2dpProfile]%{public}s linkNum(%u)\n", __func__, g_linkNum);
1061     return true;
1062 }
1063 
GetConnectedPeerDevice()1064 uint8_t A2dpProfile::GetConnectedPeerDevice()
1065 {
1066     std::lock_guard<std::mutex> lock(g_profileMutex);
1067     LOG_INFO("[A2dpProfile]%{public}s \n", __func__);
1068 
1069     return g_linkNum;
1070 }
1071 
ClearNumberPeerDevice()1072 void A2dpProfile::ClearNumberPeerDevice()
1073 {
1074     std::lock_guard<std::mutex> lock(g_profileMutex);
1075     LOG_INFO("[A2dpProfile]%{public}s \n", __func__);
1076 
1077     g_linkNum = 0;
1078 }
1079 
UpdateGapRegisterInfo(bool value)1080 void A2dpProfile::UpdateGapRegisterInfo(bool value)
1081 {
1082     std::lock_guard<std::mutex> lock(g_profileMutex);
1083     LOG_INFO("[A2dpProfile]%{public}s register(%{public}d) \n", __func__, value);
1084 
1085     g_registGap = value;
1086 }
1087 
GetGapRegisterInfo()1088 bool A2dpProfile::GetGapRegisterInfo()
1089 {
1090     std::lock_guard<std::mutex> lock(g_profileMutex);
1091     LOG_INFO("[A2dpProfile]%{public}s register(%{public}d) \n", __func__, g_registGap);
1092 
1093     return g_registGap;
1094 }
1095 
ProcessSignalingTimeoutCallback(const BtAddr &addr) const1096 void A2dpProfile::ProcessSignalingTimeoutCallback(const BtAddr &addr) const
1097 {
1098     LOG_INFO("[A2dpProfile]%{public}s  \n", __func__);
1099 
1100     A2dpProfilePeer *peer = FindPeerByAddress(addr);
1101     if (peer != nullptr) {
1102         peer->ProcessSignalingTimeoutCallback();
1103     }
1104 }
1105 
ProcessSinkStream(uint16_t handle, Packet *pkt, uint32_t timeStamp, uint8_t pt, uint16_t streamHandle)1106 void ProcessSinkStream(uint16_t handle, Packet *pkt, uint32_t timeStamp, uint8_t pt, uint16_t streamHandle)
1107 {
1108     LOG_INFO("[A2dpProfile]%{public}s  \n", __func__);
1109 
1110     A2dpProfile *profile = GetProfileInstance(A2DP_ROLE_SINK);
1111     if (profile == nullptr) {
1112         LOG_ERROR("[A2dpProfile]%{public}s Can't find the instance of profile \n", __func__);
1113         return;
1114     }
1115     A2dpProfilePeer *peer = profile->FindPeerByHandle(handle);
1116     if (peer == nullptr) {
1117         LOG_ERROR("[A2dpProfile]%{public}s Can't find the instance of peer device \n", __func__);
1118         return;
1119     }
1120     if (strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) != 0) {
1121         LOG_ERROR("[A2dpProfile]%{public}s Peer statemachine is not Streaming \n", __func__);
1122         return;
1123     }
1124 
1125     A2dpCodecThread *codecThread = A2dpCodecThread::GetInstance();
1126     if (codecThread == nullptr) {
1127         LOG_ERROR("[A2dpProfile]%{public}s Can't find the instance of codec \n", __func__);
1128         return;
1129     }
1130 
1131     uint16_t packetSize = PacketSize(pkt);
1132     if (packetSize == 0) {
1133         return;
1134     }
1135     auto frameData = (uint8_t *)malloc(packetSize);
1136     if (frameData != nullptr) {
1137         (void)memset_s(frameData, packetSize, 0, packetSize);
1138         PacketRead(pkt, frameData, 0, packetSize);
1139         A2dpEncoderInitPeerParams peerParams = {};
1140         utility::Message msg(A2DP_FRAME_READY, packetSize, frameData);
1141         codecThread->PostMessage(msg, peerParams, nullptr, nullptr);
1142     }
1143 }
1144 
CleanPacketData(void *data)1145 void CleanPacketData(void *data)
1146 {
1147     PacketData *packetData = (PacketData *)data;
1148     PacketFree(packetData->packet);
1149     free(packetData);
1150 }
1151 }  // namespace bluetooth
1152 }  // namespace OHOS
1153