• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     if (GetSDPInstance().FindSnkService(device, a2dpInstance, A2dpProfilePeer::SDPServiceCallback) != BT_SUCCESS) {
608         LOG_WARN("[A2dpProfile]%{public}s SDP_ServiceSearch Error\n", __func__);
609     }
610     return A2DP_SUCCESS;
611 }
612 
ProcessSDPCallback(const BtAddr & addr,uint8_t result)613 void A2dpProfile::ProcessSDPCallback(const BtAddr &addr, uint8_t result)
614 {
615     if (result != A2DP_SUCCESS) {
616         CallbackParameter param = {A2DP_ROLE_INT, true, 0};
617         ConnectStateChangedNotify(addr, STREAM_DISCONNECT, (void *)&param);
618         LOG_INFO("[A2dpProfile]%{public}s Failed to get SDPresult(%hhu)\n", __func__, result);
619         return;
620     }
621 
622     /// Check sdp information
623     uint8_t role = GetRole();
624     A2dpAvdtMsg data = {};
625     A2dpProfilePeer *peer = FindOrCreatePeer(addr, role);
626     utility::Message msg(EVT_CONNECT_REQ, 0, &data);
627 
628     data.a2dpMsg.connectInfo.addr = addr;
629     data.role = role;
630     msg.arg2_ = &data;
631     if (peer == nullptr) {
632         LOG_ERROR("[A2dpProfile]%{public}s Not resources", __func__);
633     } else {
634         if (!peer->GetSDPServiceCapability()) {
635             msg.arg1_ = EVT_SDP_CFM;
636             LOG_ERROR("[A2dpProfile]%{public}s Can't find peer service matched. role(%u)", __func__, data.role);
637         }
638         peer->GetStateMachine()->ProcessMessage(msg);
639         peer->SetCurrentCmd(EVT_CONNECT_REQ);
640         peer->SetInitSide(true);
641     }
642 }
643 
Disconnect(const BtAddr & device)644 int A2dpProfile::Disconnect(const BtAddr &device)
645 {
646     int ret = 0;
647     A2dpProfilePeer *peer = nullptr;
648     A2dpAvdtMsg data = {};
649     utility::Message msg(EVT_DISCONNECT_REQ, 0, &data);
650 
651     data.a2dpMsg.connectInfo.addr = device;
652     data.role = GetRole();
653     msg.arg2_ = &data;
654     peer = FindPeerByAddress(device);
655     if (peer == nullptr) {
656         ret = AVDT_NO_RESOURCES;
657         LOG_ERROR("[A2dpProfile]%{public}s Not resources", __func__);
658     } else {
659         if (peer->GetCurrentCmd() != EVT_SDP_DISC && peer->GetCurrentCmd() != EVT_CONNECT_REQ) {
660             ret = peer->GetStateMachine()->ProcessMessage(msg);
661             peer->SetCurrentCmd(EVT_DISCONNECT_REQ);
662         } else {
663             peer->SetDisconnectIndication(true);
664         }
665     }
666 
667     return ret;
668 }
669 
Stop(const uint16_t handle,const bool suspend)670 int A2dpProfile::Stop(const uint16_t handle, const bool suspend)
671 {
672     LOG_INFO("[A2dpProfile]%{public}s handle(%u) suspend(%{public}d)\n", __func__, handle, suspend);
673     int ret = BT_SUCCESS;
674     A2dpProfilePeer *peer = nullptr;
675     A2dpAvdtMsg data = {};
676     utility::Message msg(EVT_SUSPEND_REQ, 0, &data);
677 
678     data.a2dpMsg.stream.handle = handle;
679     data.role = GetRole();
680     msg.arg2_ = &data;
681 
682     peer = FindPeerByHandle(handle);
683     if (peer == nullptr) {
684         ret = AVDT_BAD_PARAMS;
685         LOG_ERROR("[A2dpProfile]%{public}s invalid handle(%u) suspend(%{public}d)\n", __func__, handle, suspend);
686         return ret;
687     }
688 
689     if ((strcmp(A2DP_PROFILE_OPEN.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) ||
690         (strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0)) {
691         LOG_INFO("[A2dpProfile]%{public}s streaming exited now\n", __func__);
692         peer->GetStateMachine()->ProcessMessage(msg);
693     } else {
694         LOG_ERROR("[A2dpProfile]%{public}s Not streaming status now\n", __func__);
695         ret = AVDT_ERR_UNSUPPORTED_COMMAND;
696     }
697 
698     QueueFlush(packetQueue_, CleanPacketData);
699     buffer_->Reset();
700     return ret;
701 }
702 
Start(const uint16_t handle)703 int A2dpProfile::Start(const uint16_t handle)
704 {
705     LOG_INFO("[A2dpProfile]%{public}s handle(%hu)\n", __func__, handle);
706 
707     int ret = BT_SUCCESS;
708     uint8_t role = GetRole();
709     A2dpProfilePeer *peer = nullptr;
710     A2dpAvdtMsg data = {};
711     utility::Message msg(EVT_START_REQ, 0, &data);
712 
713     data.a2dpMsg.stream.handle = handle;
714     data.role = role;
715     msg.arg2_ = &data;
716     peer = FindPeerByHandle(handle);
717     if (peer == nullptr) {
718         ret = AVDT_BAD_PARAMS;
719         return ret;
720     }
721     if (strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
722         LOG_INFO("[A2dpProfile]%{public}s The state of stream is streaming now\n", __func__);
723         if (role == A2DP_ROLE_SOURCE) {
724             peer->NotifyEncoder();
725         } else if (role == A2DP_ROLE_SINK) {
726             peer->NotifyDecoder();
727         } else {
728             LOG_ERROR("[A2dpProfile]%{public}s Audio data is not ready\n", __func__);
729         }
730         peer->GetStateMachine()->ProcessMessage(msg);
731         return BT_SUCCESS;
732     }
733     if (!JudgeAllowedStreaming()) {
734         return AVDT_NO_RESOURCES;
735     }
736     peer->GetStateMachine()->ProcessMessage(msg);
737 
738     return ret;
739 }
740 
JudgeAllowedStreaming() const741 bool A2dpProfile::JudgeAllowedStreaming() const
742 {
743     bool ret = true;
744     A2dpProfilePeer *peerProfile = nullptr;
745 
746     for (const auto &it : peers_) {
747         peerProfile = it.second;
748         if (peerProfile != nullptr) {
749             LOG_INFO("[A2dpProfile]%{public}s state(%{public}s)\n",
750                 __func__, peerProfile->GetStateMachine()->GetStateName().c_str());
751             if (strcmp(A2DP_PROFILE_STREAMING.c_str(), peerProfile->GetStateMachine()->GetStateName().c_str()) == 0) {
752                 LOG_ERROR("[A2dpProfile]%{public}s there is one streaming exited now\n", __func__);
753                 ret = false;
754                 break;
755             }
756         }
757     }
758     return ret;
759 }
760 
Close(const uint16_t handle) const761 int A2dpProfile::Close(const uint16_t handle) const
762 {
763     int ret = BT_SUCCESS;
764     A2dpProfilePeer *peer = nullptr;
765     A2dpAvdtMsg data = {};
766     utility::Message msg(EVT_CLOSE_REQ, 0, &data);
767 
768     data.a2dpMsg.stream.handle = handle;
769     data.role = GetRole();
770     msg.arg2_ = &data;
771     peer = FindPeerByHandle(handle);
772     if (peer == nullptr) {
773         ret = AVDT_BAD_PARAMS;
774         return ret;
775     }
776 
777     if (strcmp(A2DP_PROFILE_OPEN.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0 ||
778         strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
779         LOG_INFO("[A2dpProfile]%{public}s open/streaming exited now\n", __func__);
780         peer->GetStateMachine()->ProcessMessage(msg);
781     } else {
782         LOG_ERROR("[A2dpProfile]%{public}s Not open/streaming status now\n", __func__);
783         ret = AVDT_ERR_UNSUPPORTED_COMMAND;
784     }
785     return ret;
786 }
787 
788 
HasStreaming()789 bool A2dpProfile::HasStreaming()
790 {
791     A2dpProfilePeer *peer = nullptr;
792     for (const auto &it : peers_) {
793         LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, it.second->GetStreamHandle());
794         peer = it.second;
795         if (peer != nullptr) {
796             if (strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
797                 LOG_INFO("[A2dpProfile]%{public}s streaming exited now\n", __func__);
798                 return true;
799             }
800         }
801     }
802     return false;
803 }
804 
HasOpen()805 bool A2dpProfile::HasOpen()
806 {
807     A2dpProfilePeer *peer = nullptr;
808     for (const auto &it : peers_) {
809         LOG_INFO("[A2dpProfile]%{public}s \n", __func__);
810         peer = it.second;
811         if (peer != nullptr) {
812             if (strcmp(A2DP_PROFILE_OPEN.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
813                 LOG_INFO("[A2dpProfile]%{public}s open exited now\n", __func__);
814                 return true;
815             }
816         }
817     }
818     return false;
819 }
820 
SetDisalbeTag(bool tag)821 void A2dpProfile::SetDisalbeTag(bool tag)
822 {
823     LOG_INFO("[A2dpProfile]%{public}s isDoDisable(%u)\n", __func__, tag);
824     isDoDisable_ = tag;
825 }
826 
GetDisalbeTag()827 bool A2dpProfile::GetDisalbeTag()
828 {
829     LOG_INFO("[A2dpProfile]%{public}s isDoDisable(%u)\n", __func__, isDoDisable_);
830     return isDoDisable_;
831 }
832 
CloseAll()833 void A2dpProfile::CloseAll()
834 {
835     for (const auto &it : peers_) {
836         LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, it.second->GetStreamHandle());
837         if (it.second != nullptr) {
838             Close(it.second->GetStreamHandle());
839         }
840     }
841 }
842 
SendDelay(const uint16_t handle,const uint16_t delayValue)843 int A2dpProfile::SendDelay(const uint16_t handle, const uint16_t delayValue)
844 {
845     LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, handle);
846     A2dpAvdtp avdtp(A2DP_ROLE_SINK);
847     uint8_t label = 0;
848 
849     int ret = avdtp.DelayReq(handle, label, delayValue);
850     return ret;
851 }
852 
CloseRsp(const uint16_t handle,const uint8_t errorCode) const853 int A2dpProfile::CloseRsp(const uint16_t handle, const uint8_t errorCode) const
854 {
855     LOG_INFO("[A2dpProfile]%{public}s handle(%u) role(%u)\n", __func__, handle, GetRole());
856     A2dpAvdtp avdtp(GetRole());
857     uint8_t label = 0;
858 
859     int ret = avdtp.CloseRsp(handle, label, errorCode);
860     return ret;
861 }
862 
WriteStream(const uint16_t handle,const uint8_t config,const uint8_t bitpool)863 int A2dpProfile::WriteStream(const uint16_t handle, const uint8_t config, const uint8_t bitpool)
864 {
865     LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, handle);
866 
867     A2dpAvdtp avdtp(A2DP_ROLE_SOURCE);
868     uint32_t timeStamp = 0x8FF;
869     Packet *pkt = PacketMalloc(0, 0, 0);
870     uint8_t pktType = 0;
871     uint16_t marker = 0x0B;
872     uint8_t codecInfo[CODEC_LENGTH] = {0x01, 0x9c, 0x00, 0x35, 0x00, 0x88, 0x88, 0x88};
873 
874     codecInfo[CODEC_SBC_TYPE_INDEX] = config;
875     codecInfo[SAMPLE_SBC_INDEX] = bitpool;
876     Buffer *encBuf = BufferMalloc(CODEC_LENGTH);
877     (void)memcpy_s(BufferPtr(encBuf), CODEC_LENGTH, codecInfo, CODEC_LENGTH);
878     PacketPayloadAddLast(pkt, encBuf);
879 
880     int ret = avdtp.WriteStream(handle, pkt, timeStamp, pktType, marker);
881     return ret;
882 }
883 
Reconfigure(const uint16_t handle,uint8_t * codecInfo) const884 int A2dpProfile::Reconfigure(const uint16_t handle, uint8_t *codecInfo) const
885 {
886     LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, handle);
887 
888     int ret = BT_SUCCESS;
889     A2dpProfilePeer *peer = nullptr;
890     A2dpAvdtMsg data = {};
891     utility::Message msg(EVT_RECONFIG_REQ, 0, &data);
892 
893     peer = FindPeerByHandle(handle);
894     if (peer == nullptr) {
895         ret = AVDT_BAD_PARAMS;
896         LOG_ERROR("[A2dpProfile]%{public}s invalid handle(%u) \n", __func__, handle);
897         return ret;
898     }
899 
900     (void)memcpy_s(data.a2dpMsg.configStream.cfg.codecInfo, A2DP_CODEC_SIZE, codecInfo,
901         sizeof(data.a2dpMsg.configStream.cfg.codecInfo));
902     data.a2dpMsg.configStream.cfg.mediaType = A2DP_MEDIA_TYPE_AUDIO;
903     data.a2dpMsg.configStream.cfg.numCodec = A2DP_CODEC_SBC_INFO_LEN;
904     data.a2dpMsg.configStream.cfg.pscMask = AVDT_PSC_MSK_CODEC;
905     data.a2dpMsg.configStream.intSeid = handle;
906     data.role = GetRole();
907     msg.arg2_ = &data;
908 
909     if (strcmp(A2DP_PROFILE_OPEN.c_str(), peer->GetStateMachine()->GetStateName().c_str()) == 0) {
910         LOG_INFO("[A2dpProfile]%{public}s streaming exited now\n", __func__);
911         peer->GetStateMachine()->ProcessMessage(msg);
912     } else {
913         LOG_ERROR("[A2dpProfile]%{public}s Not open status now\n", __func__);
914         ret = AVDT_ERR_UNSUPPORTED_COMMAND;
915     }
916 
917     return ret;
918 }
919 
DelayReportNotify(const BtAddr & device,const uint16_t delayValue)920 void A2dpProfile::DelayReportNotify(const BtAddr &device, const uint16_t delayValue)
921 {
922     LOG_INFO("[A2dpProfile]%{public}s delayValue(%{public}u)\n", __func__, delayValue);
923 
924     A2dpProfilePeer *peer = nullptr;
925     peer = FindPeerByAddress(device);
926     if (peer == nullptr) {
927         LOG_ERROR("[A2dpProfile]%{public}s Not resources", __func__);
928         return;
929     }
930 
931     delayValue_ = delayValue;
932 }
933 
ResetDelayValue(const BtAddr & device)934 void A2dpProfile::ResetDelayValue(const BtAddr &device)
935 {
936     LOG_INFO("[A2dpProfile]%{public}s", __func__);
937 
938     A2dpProfilePeer *peer = nullptr;
939     peer = FindPeerByAddress(device);
940     if (peer == nullptr) {
941         LOG_ERROR("[A2dpProfile]%{public}s Not resources", __func__);
942         return;
943     }
944     delayValue_ = 0;
945 }
946 
RegisterObserver(A2dpProfileObserver * observer)947 void A2dpProfile::RegisterObserver(A2dpProfileObserver *observer)
948 {
949     LOG_INFO("[A2dpProfile]%{public}s\n", __func__);
950 
951     a2dpSvcCBack_ = observer;
952     return;
953 }
954 
DeregisterObserver(A2dpProfileObserver * observer)955 void A2dpProfile::DeregisterObserver(A2dpProfileObserver *observer)
956 {
957     LOG_INFO("[A2dpProfile]%{public}s\n", __func__);
958     return;
959 }
960 
FindPeerByAddress(const BtAddr & peerAddress) const961 A2dpProfilePeer *A2dpProfile::FindPeerByAddress(const BtAddr &peerAddress) const
962 {
963     HILOGI("[A2dpProfile] addr(%{public}s)",
964         GetEncryptAddr(RawAddress::ConvertToString(peerAddress.addr).GetAddress()).c_str());
965     A2dpProfilePeer *peer = nullptr;
966 
967     for (const auto &it : peers_) {
968         if (strcmp(it.first.c_str(), RawAddress::ConvertToString(peerAddress.addr).GetAddress().c_str()) == 0) {
969             peer = it.second;
970             HILOGI("[A2dpProfile] matched peers_addr(%{public}s)\n", GetEncryptAddr(it.first).c_str());
971             return peer;
972         }
973         HILOGI("[A2dpProfile] peers_addr(%{public}s)\n", GetEncryptAddr(it.first).c_str());
974     }
975     return peer;
976 }
977 
FindPeerByHandle(uint16_t handle) const978 A2dpProfilePeer *A2dpProfile::FindPeerByHandle(uint16_t handle) const
979 {
980     LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, handle);
981     A2dpProfilePeer *peer = nullptr;
982 
983     for (const auto &it : peers_) {
984         LOG_INFO("[A2dpProfile]%{public}s handle(%u)\n", __func__, it.second->GetStreamHandle());
985         if (handle == it.second->GetStreamHandle()) {
986             peer = it.second;
987             break;
988         }
989     }
990     return peer;
991 }
992 
FindOrCreatePeer(const BtAddr & peerAddress,uint8_t localRole)993 A2dpProfilePeer *A2dpProfile::FindOrCreatePeer(const BtAddr &peerAddress, uint8_t localRole)
994 {
995     A2dpProfilePeer *peer = nullptr;
996     std::string addr = RawAddress::ConvertToString(peerAddress.addr).GetAddress();
997     peer = FindPeerByAddress(peerAddress);
998     if (peer != nullptr) {
999         LOG_DEBUG("[A2dpProfile]%{public}s Peer is exited", __func__);
1000         return peer;
1001     }
1002     if (UpdateNumberPeerDevice(true)) {
1003         auto peerInstance = std::make_unique<A2dpProfilePeer>(peerAddress, localRole);
1004         peer = peerInstance.release();
1005         peers_.insert(std::make_pair(addr, peer));
1006         HILOGI("addr: %{public}s", GetEncryptAddr(addr).c_str());
1007     } else {
1008         HILOGE("Connected device is max: %{public}u", GetConnectedPeerDevice());
1009     }
1010     return peer;
1011 }
1012 
DeletePeer(const BtAddr & peerAddress)1013 bool A2dpProfile::DeletePeer(const BtAddr &peerAddress)
1014 {
1015     bool ret = false;
1016     std::map<std::string, A2dpProfilePeer *>::iterator it;
1017 
1018     if (IsActiveDevice(peerAddress)) {
1019         A2dpCodecThread *codecThread = A2dpCodecThread::GetInstance();
1020         if (codecThread != nullptr) {
1021             codecThread->StopA2dpCodecThread();
1022             delete codecThread;
1023         }
1024     }
1025 
1026     for (it = peers_.begin(); it != peers_.end(); it++) {
1027         if (strcmp(it->first.c_str(), RawAddress::ConvertToString(peerAddress.addr).GetAddress().c_str()) == 0) {
1028             delete it->second;
1029             peers_.erase(it);
1030             UpdateNumberPeerDevice(false);
1031             ret = true;
1032             HILOGI("[A2dpProfile] matched peers_addr(%{public}s)",
1033                 GetEncryptAddr(RawAddress::ConvertToString(peerAddress.addr).GetAddress()).c_str());
1034             break;
1035         }
1036         HILOGI("[A2dpProfile] peers_addr(%{public}s)\n", GetEncryptAddr(it->first).c_str());
1037     }
1038 
1039     return ret;
1040 }
1041 
UpdateNumberPeerDevice(bool plus)1042 bool A2dpProfile::UpdateNumberPeerDevice(bool plus)
1043 {
1044     std::lock_guard<std::mutex> lock(g_profileMutex);
1045     LOG_INFO("[A2dpProfile]%{public}s plus(%{public}d)\n", __func__, plus);
1046 
1047     if (plus) {
1048         g_linkNum++;
1049     } else {
1050         if (g_linkNum > 0) {
1051             g_linkNum--;
1052         }
1053     }
1054     if (g_linkNum > A2DP_CONNECT_NUM_MAX) {
1055         LOG_ERROR("[A2dpProfile]%{public}s linkNum(%u)\n", __func__, g_linkNum);
1056         g_linkNum = A2DP_CONNECT_NUM_MAX;
1057         return false;
1058     }
1059     LOG_INFO("[A2dpProfile]%{public}s linkNum(%u)\n", __func__, g_linkNum);
1060     return true;
1061 }
1062 
GetConnectedPeerDevice()1063 uint8_t A2dpProfile::GetConnectedPeerDevice()
1064 {
1065     std::lock_guard<std::mutex> lock(g_profileMutex);
1066     LOG_INFO("[A2dpProfile]%{public}s \n", __func__);
1067 
1068     return g_linkNum;
1069 }
1070 
ClearNumberPeerDevice()1071 void A2dpProfile::ClearNumberPeerDevice()
1072 {
1073     std::lock_guard<std::mutex> lock(g_profileMutex);
1074     LOG_INFO("[A2dpProfile]%{public}s \n", __func__);
1075 
1076     g_linkNum = 0;
1077 }
1078 
UpdateGapRegisterInfo(bool value)1079 void A2dpProfile::UpdateGapRegisterInfo(bool value)
1080 {
1081     std::lock_guard<std::mutex> lock(g_profileMutex);
1082     LOG_INFO("[A2dpProfile]%{public}s register(%{public}d) \n", __func__, value);
1083 
1084     g_registGap = value;
1085 }
1086 
GetGapRegisterInfo()1087 bool A2dpProfile::GetGapRegisterInfo()
1088 {
1089     std::lock_guard<std::mutex> lock(g_profileMutex);
1090     LOG_INFO("[A2dpProfile]%{public}s register(%{public}d) \n", __func__, g_registGap);
1091 
1092     return g_registGap;
1093 }
1094 
ProcessSignalingTimeoutCallback(const BtAddr & addr) const1095 void A2dpProfile::ProcessSignalingTimeoutCallback(const BtAddr &addr) const
1096 {
1097     LOG_INFO("[A2dpProfile]%{public}s  \n", __func__);
1098 
1099     A2dpProfilePeer *peer = FindPeerByAddress(addr);
1100     if (peer != nullptr) {
1101         peer->ProcessSignalingTimeoutCallback();
1102     }
1103 }
1104 
ProcessSinkStream(uint16_t handle,Packet * pkt,uint32_t timeStamp,uint8_t pt,uint16_t streamHandle)1105 void ProcessSinkStream(uint16_t handle, Packet *pkt, uint32_t timeStamp, uint8_t pt, uint16_t streamHandle)
1106 {
1107     LOG_INFO("[A2dpProfile]%{public}s  \n", __func__);
1108 
1109     A2dpProfile *profile = GetProfileInstance(A2DP_ROLE_SINK);
1110     if (profile == nullptr) {
1111         LOG_ERROR("[A2dpProfile]%{public}s Can't find the instance of profile \n", __func__);
1112         return;
1113     }
1114     A2dpProfilePeer *peer = profile->FindPeerByHandle(handle);
1115     if (peer == nullptr) {
1116         LOG_ERROR("[A2dpProfile]%{public}s Can't find the instance of peer device \n", __func__);
1117         return;
1118     }
1119     if (strcmp(A2DP_PROFILE_STREAMING.c_str(), peer->GetStateMachine()->GetStateName().c_str()) != 0) {
1120         LOG_ERROR("[A2dpProfile]%{public}s Peer statemachine is not Streaming \n", __func__);
1121         return;
1122     }
1123 
1124     A2dpCodecThread *codecThread = A2dpCodecThread::GetInstance();
1125     if (codecThread == nullptr) {
1126         LOG_ERROR("[A2dpProfile]%{public}s Can't find the instance of codec \n", __func__);
1127         return;
1128     }
1129 
1130     uint16_t packetSize = PacketSize(pkt);
1131     if (packetSize == 0) {
1132         return;
1133     }
1134     auto frameData = (uint8_t *)malloc(packetSize);
1135     if (frameData != nullptr) {
1136         (void)memset_s(frameData, packetSize, 0, packetSize);
1137         PacketRead(pkt, frameData, 0, packetSize);
1138         A2dpEncoderInitPeerParams peerParams = {};
1139         utility::Message msg(A2DP_FRAME_READY, packetSize, frameData);
1140         codecThread->PostMessage(msg, peerParams, nullptr, nullptr);
1141     }
1142 }
1143 
CleanPacketData(void * data)1144 void CleanPacketData(void *data)
1145 {
1146     PacketData *packetData = (PacketData *)data;
1147     PacketFree(packetData->packet);
1148     free(packetData);
1149 }
1150 }  // namespace bluetooth
1151 }  // namespace OHOS
1152