• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2004-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  This file contains action functions for advanced audio/video stream
22  *  state machine. these functions are shared by both audio and video
23  *  streams.
24  *
25  ******************************************************************************/
26 
27 #define LOG_TAG "bt_bta_av"
28 
29 #include <base/strings/stringprintf.h>
30 
31 #include <cstdint>
32 #include <cstring>
33 #include <vector>
34 
35 #include "bt_target.h"  // Must be first to define build configuration
36 #include "bta/av/bta_av_int.h"
37 #include "bta/include/bta_ar_api.h"
38 #include "bta/include/bta_av_co.h"
39 #include "btif/avrcp/avrcp_service.h"
40 #include "btif/include/btif_av_co.h"
41 #include "btif/include/btif_config.h"
42 #include "btif/include/btif_storage.h"
43 #include "device/include/interop.h"
44 #include "main/shim/dumpsys.h"
45 #include "osi/include/allocator.h"
46 #include "osi/include/log.h"
47 #include "osi/include/osi.h"
48 #include "osi/include/properties.h"
49 #include "stack/include/a2dp_sbc.h"
50 #include "stack/include/acl_api.h"
51 #include "stack/include/bt_hdr.h"
52 #include "stack/include/btm_api.h"
53 #include "stack/include/btm_client_interface.h"
54 #include "stack/include/l2c_api.h"
55 #include "types/hci_role.h"
56 #include "types/raw_address.h"
57 
58 namespace {
59 
60 constexpr char kBtmLogTag[] = "A2DP";
61 
62 }
63 
64 /*****************************************************************************
65  *  Constants
66  ****************************************************************************/
67 
68 /* the delay time in milliseconds to start service discovery on AVRCP */
69 #ifndef BTA_AV_RC_DISC_TIME_VAL
70 #define BTA_AV_RC_DISC_TIME_VAL 3500
71 #endif
72 
73 /* the timer in milliseconds to guard against link busy and AVDT_CloseReq failed
74  * to be sent */
75 #ifndef BTA_AV_CLOSE_REQ_TIME_VAL
76 #define BTA_AV_CLOSE_REQ_TIME_VAL 4000
77 #endif
78 
79 /* number to retry on reconfigure failure - some headsets requirs this number to
80  * be more than 1 */
81 #ifndef BTA_AV_RECONFIG_RETRY
82 #define BTA_AV_RECONFIG_RETRY 6
83 #endif
84 
85 /* ACL quota we are letting FW use for A2DP Offload Tx. */
86 #define BTA_AV_A2DP_OFFLOAD_XMIT_QUOTA 4
87 
88 static void bta_av_offload_codec_builder(tBTA_AV_SCB* p_scb,
89                                          tBT_A2DP_OFFLOAD* p_a2dp_offload);
90 
91 /* state machine states */
92 enum {
93   BTA_AV_INIT_SST,
94   BTA_AV_INCOMING_SST,
95   BTA_AV_OPENING_SST,
96   BTA_AV_OPEN_SST,
97   BTA_AV_RCFG_SST,
98   BTA_AV_CLOSING_SST
99 };
100 
101 /* the call out functions for audio stream */
102 const tBTA_AV_CO_FUNCTS bta_av_a2dp_cos = {bta_av_co_audio_init,
103                                            bta_av_co_audio_disc_res,
104                                            bta_av_co_audio_getconfig,
105                                            bta_av_co_audio_setconfig,
106                                            bta_av_co_audio_open,
107                                            bta_av_co_audio_close,
108                                            bta_av_co_audio_start,
109                                            bta_av_co_audio_stop,
110                                            bta_av_co_audio_source_data_path,
111                                            bta_av_co_audio_delay,
112                                            bta_av_co_audio_update_mtu,
113                                            bta_av_co_get_scmst_info};
114 
115 /* these tables translate AVDT events to SSM events */
116 static const uint16_t bta_av_stream_evt_ok[] = {
117     BTA_AV_STR_DISC_OK_EVT,      /* AVDT_DISCOVER_CFM_EVT */
118     BTA_AV_STR_GETCAP_OK_EVT,    /* AVDT_GETCAP_CFM_EVT */
119     BTA_AV_STR_OPEN_OK_EVT,      /* AVDT_OPEN_CFM_EVT */
120     BTA_AV_STR_OPEN_OK_EVT,      /* AVDT_OPEN_IND_EVT */
121     BTA_AV_STR_CONFIG_IND_EVT,   /* AVDT_CONFIG_IND_EVT */
122     BTA_AV_STR_START_OK_EVT,     /* AVDT_START_CFM_EVT */
123     BTA_AV_STR_START_OK_EVT,     /* AVDT_START_IND_EVT */
124     BTA_AV_STR_SUSPEND_CFM_EVT,  /* AVDT_SUSPEND_CFM_EVT */
125     BTA_AV_STR_SUSPEND_CFM_EVT,  /* AVDT_SUSPEND_IND_EVT */
126     BTA_AV_STR_CLOSE_EVT,        /* AVDT_CLOSE_CFM_EVT */
127     BTA_AV_STR_CLOSE_EVT,        /* AVDT_CLOSE_IND_EVT */
128     BTA_AV_STR_RECONFIG_CFM_EVT, /* AVDT_RECONFIG_CFM_EVT */
129     0,                           /* AVDT_RECONFIG_IND_EVT */
130     BTA_AV_STR_SECURITY_CFM_EVT, /* AVDT_SECURITY_CFM_EVT */
131     BTA_AV_STR_SECURITY_IND_EVT, /* AVDT_SECURITY_IND_EVT */
132     BTA_AV_STR_WRITE_CFM_EVT,    /* AVDT_WRITE_CFM_EVT */
133     BTA_AV_AVDT_CONNECT_EVT,     /* AVDT_CONNECT_IND_EVT */
134     BTA_AV_AVDT_DISCONNECT_EVT,  /* AVDT_DISCONNECT_IND_EVT */
135     BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_CONN_EVT */
136     BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_DISCONN_EVT */
137     BTA_AV_AVDT_DELAY_RPT_EVT, /* AVDT_DELAY_REPORT_EVT */
138     BTA_AV_AVDT_DELAY_RPT_CFM_EVT, /* AVDT_DELAY_REPORT_CFM_EVT */
139 };
140 
141 static const uint16_t bta_av_stream_evt_fail[] = {
142     BTA_AV_STR_DISC_FAIL_EVT,    /* AVDT_DISCOVER_CFM_EVT */
143     BTA_AV_STR_GETCAP_FAIL_EVT,  /* AVDT_GETCAP_CFM_EVT */
144     BTA_AV_STR_OPEN_FAIL_EVT,    /* AVDT_OPEN_CFM_EVT */
145     BTA_AV_STR_OPEN_OK_EVT,      /* AVDT_OPEN_IND_EVT */
146     BTA_AV_STR_CONFIG_IND_EVT,   /* AVDT_CONFIG_IND_EVT */
147     BTA_AV_STR_START_FAIL_EVT,   /* AVDT_START_CFM_EVT */
148     BTA_AV_STR_START_OK_EVT,     /* AVDT_START_IND_EVT */
149     BTA_AV_STR_SUSPEND_CFM_EVT,  /* AVDT_SUSPEND_CFM_EVT */
150     BTA_AV_STR_SUSPEND_CFM_EVT,  /* AVDT_SUSPEND_IND_EVT */
151     BTA_AV_STR_CLOSE_EVT,        /* AVDT_CLOSE_CFM_EVT */
152     BTA_AV_STR_CLOSE_EVT,        /* AVDT_CLOSE_IND_EVT */
153     BTA_AV_STR_RECONFIG_CFM_EVT, /* AVDT_RECONFIG_CFM_EVT */
154     0,                           /* AVDT_RECONFIG_IND_EVT */
155     BTA_AV_STR_SECURITY_CFM_EVT, /* AVDT_SECURITY_CFM_EVT */
156     BTA_AV_STR_SECURITY_IND_EVT, /* AVDT_SECURITY_IND_EVT */
157     BTA_AV_STR_WRITE_CFM_EVT,    /* AVDT_WRITE_CFM_EVT */
158     BTA_AV_AVDT_CONNECT_EVT,     /* AVDT_CONNECT_IND_EVT */
159     BTA_AV_AVDT_DISCONNECT_EVT,  /* AVDT_DISCONNECT_IND_EVT */
160     BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_CONN_EVT */
161     BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_DISCONN_EVT */
162     BTA_AV_AVDT_DELAY_RPT_EVT, /* AVDT_DELAY_REPORT_EVT */
163     BTA_AV_AVDT_DELAY_RPT_CFM_EVT, /* AVDT_DELAY_REPORT_CFM_EVT */
164 };
165 
166 /***********************************************
167  *
168  * Function         bta_get_scb_handle
169  *
170  * Description      gives the registered AVDT handle.by checking with sep_type.
171  *
172  *
173  * Returns          void
174  **********************************************/
bta_av_get_scb_handle(tBTA_AV_SCB * p_scb,uint8_t local_sep)175 static uint8_t bta_av_get_scb_handle(tBTA_AV_SCB* p_scb, uint8_t local_sep) {
176   for (int i = 0; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) {
177     if ((p_scb->seps[i].tsep == local_sep) &&
178         A2DP_CodecTypeEquals(p_scb->seps[i].codec_info,
179                              p_scb->cfg.codec_info)) {
180       return (p_scb->seps[i].av_handle);
181     }
182   }
183   APPL_TRACE_DEBUG("%s: local sep_type %d not found", __func__, local_sep)
184   return 0; /* return invalid handle */
185 }
186 
187 /***********************************************
188  *
189  * Function         bta_av_get_scb_sep_type
190  *
191  * Description      gives the sep type by cross-checking with AVDT handle
192  *
193  *
194  * Returns          void
195  **********************************************/
bta_av_get_scb_sep_type(tBTA_AV_SCB * p_scb,uint8_t tavdt_handle)196 static uint8_t bta_av_get_scb_sep_type(tBTA_AV_SCB* p_scb,
197                                        uint8_t tavdt_handle) {
198   for (int i = 0; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) {
199     if (p_scb->seps[i].av_handle == tavdt_handle) return (p_scb->seps[i].tsep);
200   }
201   APPL_TRACE_DEBUG("%s: avdt_handle %d not found", __func__, tavdt_handle)
202   return AVDT_TSEP_INVALID;
203 }
204 
205 /*******************************************************************************
206  *
207  * Function         bta_av_save_addr
208  *
209  * Description      copy the bd_addr and maybe reset the supported flags
210  *
211  *
212  * Returns          void
213  *
214  ******************************************************************************/
bta_av_save_addr(tBTA_AV_SCB * p_scb,const RawAddress & bd_addr)215 static void bta_av_save_addr(tBTA_AV_SCB* p_scb, const RawAddress& bd_addr) {
216   APPL_TRACE_DEBUG("%s: peer=%s recfg_sup:%d, suspend_sup:%d", __func__,
217                    bd_addr.ToString().c_str(), p_scb->recfg_sup,
218                    p_scb->suspend_sup);
219   if (p_scb->PeerAddress() != bd_addr) {
220     LOG_INFO("%s: reset flags old_addr=%s new_addr=%s", __func__,
221              p_scb->PeerAddress().ToString().c_str(),
222              bd_addr.ToString().c_str());
223     /* a new addr, reset the supported flags */
224     p_scb->recfg_sup = true;
225     p_scb->suspend_sup = true;
226   }
227 
228   /* do this copy anyway, just in case the first addr matches
229    * the control block one by accident */
230   p_scb->OnConnected(bd_addr);
231 }
232 
233 /*******************************************************************************
234  *
235  * Function         notify_start_failed
236  *
237  * Description      notify up-layer AV start failed
238  *
239  *
240  * Returns          void
241  *
242  ******************************************************************************/
notify_start_failed(tBTA_AV_SCB * p_scb)243 static void notify_start_failed(tBTA_AV_SCB* p_scb) {
244   LOG_ERROR("%s: peer %s role:0x%x bta_channel:%d bta_handle:0x%x", __func__,
245             p_scb->PeerAddress().ToString().c_str(), p_scb->role, p_scb->chnl,
246             p_scb->hndl);
247   tBTA_AV_START start;
248   /* if start failed, clear role */
249   p_scb->role &= ~BTA_AV_ROLE_START_INT;
250   start.chnl = p_scb->chnl;
251   start.status = BTA_AV_FAIL;
252   start.initiator = true;
253   start.hndl = p_scb->hndl;
254 
255   tBTA_AV bta_av_data;
256   bta_av_data.start = start;
257   (*bta_av_cb.p_cback)(BTA_AV_START_EVT, &bta_av_data);
258 }
259 
260 /*******************************************************************************
261  *
262  * Function         bta_av_st_rc_timer
263  *
264  * Description      start the AVRC timer if no RC connection & CT is supported &
265  *                  RC is used or
266  *                  as ACP (we do not really know if we want AVRC)
267  *
268  * Returns          void
269  *
270  ******************************************************************************/
bta_av_st_rc_timer(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)271 void bta_av_st_rc_timer(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
272   APPL_TRACE_DEBUG("%s: rc_handle:%d, use_rc: %d", __func__, p_scb->rc_handle,
273                    p_scb->use_rc);
274   /* for outgoing RC connection as INT/CT */
275   if ((p_scb->rc_handle == BTA_AV_RC_HANDLE_NONE) &&
276       /* (bta_av_cb.features & BTA_AV_FEAT_RCCT) && */
277       (p_scb->use_rc || (p_scb->role & BTA_AV_ROLE_AD_ACP))) {
278     if ((p_scb->wait & BTA_AV_WAIT_ROLE_SW_BITS) == 0) {
279       bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_RC_DISC_TIME_VAL,
280                           BTA_AV_AVRC_TIMER_EVT, p_scb->hndl);
281     } else {
282       p_scb->wait |= BTA_AV_WAIT_CHECK_RC;
283     }
284   }
285 }
286 
287 /*******************************************************************************
288  *
289  * Function         bta_av_next_getcap
290  *
291  * Description      The function gets the capabilities of the next available
292  *                  stream found in the discovery results.
293  *
294  * Returns          true if we sent request to AVDT, false otherwise.
295  *
296  ******************************************************************************/
bta_av_next_getcap(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)297 static bool bta_av_next_getcap(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
298   int i;
299   bool sent_cmd = false;
300   uint16_t uuid_int = p_scb->uuid_int;
301   uint8_t sep_requested = 0;
302 
303   if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE)
304     sep_requested = AVDT_TSEP_SNK;
305   else if (uuid_int == UUID_SERVCLASS_AUDIO_SINK)
306     sep_requested = AVDT_TSEP_SRC;
307 
308   for (i = p_scb->sep_info_idx; i < p_scb->num_seps; i++) {
309     /* steam not in use, is a sink, and is the right media type (audio/video) */
310     if ((!p_scb->sep_info[i].in_use) &&
311         (p_scb->sep_info[i].tsep == sep_requested) &&
312         (p_scb->sep_info[i].media_type == p_scb->media_type)) {
313       p_scb->sep_info_idx = i;
314 
315       /* we got a stream; get its capabilities */
316       bool get_all_cap = (p_scb->AvdtpVersion() >= AVDT_VERSION_1_3) &&
317                          (A2DP_GetAvdtpVersion() >= AVDT_VERSION_1_3);
318       AVDT_GetCapReq(p_scb->PeerAddress(), p_scb->hdi, p_scb->sep_info[i].seid,
319                      &p_scb->peer_cap, &bta_av_proc_stream_evt, get_all_cap);
320       sent_cmd = true;
321       break;
322     }
323   }
324 
325   /* if no streams available then stream open fails */
326   if (!sent_cmd) {
327     APPL_TRACE_ERROR("%s: BTA_AV_STR_GETCAP_FAIL_EVT: peer_addr=%s", __func__,
328                      p_scb->PeerAddress().ToString().c_str());
329     bta_av_ssm_execute(p_scb, BTA_AV_STR_GETCAP_FAIL_EVT, p_data);
330   }
331 
332   return sent_cmd;
333 }
334 
335 /*******************************************************************************
336  *
337  * Function         bta_av_proc_stream_evt
338  *
339  * Description      Utility function to compose stream events.
340  *
341  * Returns          void
342  *
343  ******************************************************************************/
bta_av_proc_stream_evt(uint8_t handle,const RawAddress & bd_addr,uint8_t event,tAVDT_CTRL * p_data,uint8_t scb_index)344 void bta_av_proc_stream_evt(uint8_t handle, const RawAddress& bd_addr,
345                             uint8_t event, tAVDT_CTRL* p_data,
346                             uint8_t scb_index) {
347   CHECK_LT(scb_index, BTA_AV_NUM_STRS);
348   tBTA_AV_SCB* p_scb = bta_av_cb.p_scb[scb_index];
349   uint16_t sec_len = 0;
350 
351   APPL_TRACE_EVENT(
352       "%s: peer_address: %s avdt_handle: %d event=0x%x scb_index=%d p_scb=%p",
353       __func__, bd_addr.ToString().c_str(), handle, event, scb_index, p_scb);
354 
355   if (p_data) {
356     if (event == AVDT_SECURITY_IND_EVT) {
357       sec_len = (p_data->security_ind.len < BTA_AV_SECURITY_MAX_LEN)
358                     ? p_data->security_ind.len
359                     : BTA_AV_SECURITY_MAX_LEN;
360     } else if (event == AVDT_SECURITY_CFM_EVT && p_data->hdr.err_code == 0) {
361       sec_len = (p_data->security_cfm.len < BTA_AV_SECURITY_MAX_LEN)
362                     ? p_data->security_cfm.len
363                     : BTA_AV_SECURITY_MAX_LEN;
364     }
365   }
366 
367   if (p_scb) {
368     tBTA_AV_STR_MSG* p_msg =
369         (tBTA_AV_STR_MSG*)osi_malloc(sizeof(tBTA_AV_STR_MSG) + sec_len);
370 
371     /* copy event data, bd addr, and handle to event message buffer */
372     p_msg->hdr.offset = 0;
373 
374     p_msg->bd_addr = bd_addr;
375     p_msg->scb_index = scb_index;
376     APPL_TRACE_EVENT("%s: stream event bd_addr: %s scb_index: %u", __func__,
377                      p_msg->bd_addr.ToString().c_str(), scb_index);
378 
379     if (p_data != NULL) {
380       memcpy(&p_msg->msg, p_data, sizeof(tAVDT_CTRL));
381       /* copy config params to event message buffer */
382       switch (event) {
383         case AVDT_CONFIG_IND_EVT:
384           p_msg->cfg = *p_data->config_ind.p_cfg;
385           break;
386 
387         case AVDT_SECURITY_IND_EVT:
388           p_msg->msg.security_ind.p_data = (uint8_t*)(p_msg + 1);
389           memcpy(p_msg->msg.security_ind.p_data, p_data->security_ind.p_data,
390                  sec_len);
391           break;
392 
393         case AVDT_SECURITY_CFM_EVT:
394           p_msg->msg.security_cfm.p_data = (uint8_t*)(p_msg + 1);
395           if (p_data->hdr.err_code == 0) {
396             memcpy(p_msg->msg.security_cfm.p_data, p_data->security_cfm.p_data,
397                    sec_len);
398           }
399           break;
400 
401         case AVDT_SUSPEND_IND_EVT:
402           p_msg->msg.hdr.err_code = 0;
403           break;
404 
405         case AVDT_CONNECT_IND_EVT:
406           p_scb->recfg_sup = true;
407           p_scb->suspend_sup = true;
408           break;
409 
410         default:
411           break;
412       }
413     } else {
414       p_msg->msg.hdr.err_code = 0;
415     }
416 
417     /* look up application event */
418     if ((p_data == NULL) || (p_data->hdr.err_code == 0)) {
419       p_msg->hdr.event = bta_av_stream_evt_ok[event];
420     } else {
421       p_msg->hdr.event = bta_av_stream_evt_fail[event];
422     }
423 
424     p_msg->initiator = false;
425     if (event == AVDT_SUSPEND_CFM_EVT) p_msg->initiator = true;
426 
427     APPL_TRACE_VERBOSE("%s: bta_handle:0x%x avdt_handle:%d", __func__,
428                        p_scb->hndl, handle);
429     p_msg->hdr.layer_specific = p_scb->hndl;
430     p_msg->handle = handle;
431     p_msg->avdt_event = event;
432     bta_sys_sendmsg(p_msg);
433   }
434 
435   if (p_data) {
436     bta_av_conn_cback(handle, bd_addr, event, p_data, scb_index);
437   } else {
438     APPL_TRACE_ERROR("%s: p_data is null", __func__);
439   }
440 }
441 
442 /*******************************************************************************
443  *
444  * Function         bta_av_sink_data_cback
445  *
446  * Description      This is the AVDTP callback function for sink stream events.
447  *
448  * Returns          void
449  *
450  ******************************************************************************/
bta_av_sink_data_cback(uint8_t handle,BT_HDR * p_pkt,uint32_t time_stamp,uint8_t m_pt)451 void bta_av_sink_data_cback(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp,
452                             uint8_t m_pt) {
453   int index = 0;
454   tBTA_AV_SCB* p_scb;
455   APPL_TRACE_DEBUG(
456       "%s: avdt_handle: %d pkt_len=0x%x  offset = 0x%x "
457       "number of frames 0x%x sequence number 0x%x",
458       __func__, handle, p_pkt->len, p_pkt->offset,
459       *((uint8_t*)(p_pkt + 1) + p_pkt->offset), p_pkt->layer_specific);
460   /* Get SCB and correct sep type */
461   for (index = 0; index < BTA_AV_NUM_STRS; index++) {
462     p_scb = bta_av_cb.p_scb[index];
463     if ((p_scb->avdt_handle == handle) &&
464         (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SNK)) {
465       break;
466     }
467   }
468   if (index == BTA_AV_NUM_STRS) {
469     /* cannot find correct handler */
470     osi_free(p_pkt);
471     return;
472   }
473   p_pkt->event = BTA_AV_SINK_MEDIA_DATA_EVT;
474   p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback(
475       p_scb->PeerAddress(), BTA_AV_SINK_MEDIA_DATA_EVT, (tBTA_AV_MEDIA*)p_pkt);
476   /* Free the buffer: a copy of the packet has been delivered */
477   osi_free(p_pkt);
478 }
479 
480 /*******************************************************************************
481  *
482  * Function         bta_av_a2dp_sdp_cback
483  *
484  * Description      A2DP service discovery callback.
485  *
486  * Returns          void
487  *
488  ******************************************************************************/
bta_av_a2dp_sdp_cback(bool found,tA2DP_Service * p_service,const RawAddress & peer_address)489 static void bta_av_a2dp_sdp_cback(bool found, tA2DP_Service* p_service,
490                                   const RawAddress& peer_address) {
491   APPL_TRACE_DEBUG("%s: peer %s : found=%s", __func__,
492                    peer_address.ToString().c_str(), (found) ? "true" : "false");
493 
494   tBTA_AV_SCB* p_scb = NULL;
495   if (peer_address != RawAddress::kEmpty) {
496     p_scb = bta_av_addr_to_scb(peer_address);
497   }
498   if (p_scb == NULL) {
499     p_scb = bta_av_hndl_to_scb(bta_av_cb.handle);
500   }
501   if (p_scb == NULL) {
502     APPL_TRACE_ERROR("%s: no scb found for SDP handle(0x%x)", __func__,
503                      bta_av_cb.handle);
504     return;
505   }
506   if (bta_av_cb.handle != p_scb->hndl) {
507     APPL_TRACE_WARNING("%s: SDP bta_handle expected=0x%x processing=0x%x",
508                        __func__, bta_av_cb.handle, p_scb->hndl);
509   }
510 
511   if (!found) {
512     APPL_TRACE_ERROR("%s: peer %s A2DP service discovery failed", __func__,
513                      p_scb->PeerAddress().ToString().c_str());
514   }
515   APPL_TRACE_DEBUG("%s: peer %s found=%s", __func__,
516                    p_scb->PeerAddress().ToString().c_str(),
517                    (found) ? "true" : "false");
518 
519   tBTA_AV_SDP_RES* p_msg =
520       (tBTA_AV_SDP_RES*)osi_malloc(sizeof(tBTA_AV_SDP_RES));
521   if (found) {
522     p_msg->hdr.event = BTA_AV_SDP_DISC_OK_EVT;
523   } else {
524     p_msg->hdr.event = BTA_AV_SDP_DISC_FAIL_EVT;
525     APPL_TRACE_ERROR("%s: BTA_AV_SDP_DISC_FAIL_EVT: peer_addr=%s", __func__,
526                      p_scb->PeerAddress().ToString().c_str());
527   }
528   if (found && (p_service != NULL)) {
529     p_scb->SetAvdtpVersion(p_service->avdt_version);
530     if (p_service->avdt_version != 0) {
531       if (btif_config_set_bin(p_scb->PeerAddress().ToString(),
532                               AVDTP_VERSION_CONFIG_KEY,
533                               (const uint8_t*)&p_service->avdt_version,
534                               sizeof(p_service->avdt_version))) {
535         btif_config_save();
536       } else {
537         APPL_TRACE_WARNING("%s: Failed to store peer AVDTP version for %s",
538                            __func__, p_scb->PeerAddress().ToString().c_str());
539       }
540     }
541   } else {
542     p_scb->SetAvdtpVersion(0);
543   }
544   p_msg->hdr.layer_specific = p_scb->hndl;
545 
546   bta_sys_sendmsg(p_msg);
547 }
548 
549 /*******************************************************************************
550  *
551  * Function         bta_av_adjust_seps_idx
552  *
553  * Description      adjust the sep_idx
554  *
555  * Returns
556  *
557  ******************************************************************************/
bta_av_adjust_seps_idx(tBTA_AV_SCB * p_scb,uint8_t avdt_handle)558 static void bta_av_adjust_seps_idx(tBTA_AV_SCB* p_scb, uint8_t avdt_handle) {
559   APPL_TRACE_DEBUG("%s: codec: %s", __func__,
560                    A2DP_CodecName(p_scb->cfg.codec_info));
561   for (int i = 0; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) {
562     APPL_TRACE_DEBUG("%s: avdt_handle: %d codec: %s", __func__,
563                      p_scb->seps[i].av_handle,
564                      A2DP_CodecName(p_scb->seps[i].codec_info));
565     if (p_scb->seps[i].av_handle && (p_scb->seps[i].av_handle == avdt_handle) &&
566         A2DP_CodecTypeEquals(p_scb->seps[i].codec_info,
567                              p_scb->cfg.codec_info)) {
568       p_scb->sep_idx = i;
569       p_scb->avdt_handle = p_scb->seps[i].av_handle;
570       break;
571     }
572   }
573 }
574 
575 /*******************************************************************************
576  *
577  * Function         bta_av_switch_role
578  *
579  * Description      Switch role was not started and a timer was started.
580  *                  another attempt to switch role now - still opening.
581  *
582  * Returns          void
583  *
584  ******************************************************************************/
bta_av_switch_role(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)585 void bta_av_switch_role(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
586   tBTA_AV_RS_RES switch_res = BTA_AV_RS_NONE;
587   tBTA_AV_API_OPEN* p_buf = &p_scb->q_info.open;
588 
589   APPL_TRACE_DEBUG("%s: peer %s wait:0x%x", __func__,
590                    p_scb->PeerAddress().ToString().c_str(), p_scb->wait);
591   if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_RES_START)
592     p_scb->wait |= BTA_AV_WAIT_ROLE_SW_RETRY;
593 
594   /* clear the masks set when the timer is started */
595   p_scb->wait &=
596       ~(BTA_AV_WAIT_ROLE_SW_RES_OPEN | BTA_AV_WAIT_ROLE_SW_RES_START);
597 
598   if (p_scb->q_tag == BTA_AV_Q_TAG_OPEN) {
599     if (bta_av_switch_if_needed(p_scb) ||
600         !bta_av_link_role_ok(p_scb, A2DP_SET_MULTL_BIT)) {
601       p_scb->wait |= BTA_AV_WAIT_ROLE_SW_RES_OPEN;
602     } else {
603       /* this should not happen in theory. Just in case...
604        * continue to do_disc_a2dp */
605       switch_res = BTA_AV_RS_DONE;
606     }
607   } else {
608     /* report failure on OPEN */
609     APPL_TRACE_ERROR("%s: peer %s role switch failed (wait=0x%x)", __func__,
610                      p_scb->PeerAddress().ToString().c_str(), p_scb->wait);
611     switch_res = BTA_AV_RS_FAIL;
612   }
613 
614   if (switch_res != BTA_AV_RS_NONE) {
615     if (bta_av_cb.rs_idx == (p_scb->hdi + 1)) {
616       bta_av_cb.rs_idx = 0;
617     }
618     p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_RETRY;
619     p_scb->q_tag = 0;
620     p_buf->switch_res = switch_res;
621     bta_av_do_disc_a2dp(p_scb, (tBTA_AV_DATA*)p_buf);
622   }
623 }
624 
625 /*******************************************************************************
626  *
627  * Function         bta_av_role_res
628  *
629  * Description      Handle the role changed event
630  *
631  *
632  * Returns          void
633  *
634  ******************************************************************************/
bta_av_role_res(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)635 void bta_av_role_res(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
636   bool initiator = false;
637 
638   APPL_TRACE_DEBUG("%s: peer %s q_tag:%d, wait:0x%x, role:0x%x", __func__,
639                    p_scb->PeerAddress().ToString().c_str(), p_scb->q_tag,
640                    p_scb->wait, p_scb->role);
641   if (p_scb->role & BTA_AV_ROLE_START_INT) initiator = true;
642 
643   if (p_scb->q_tag == BTA_AV_Q_TAG_START) {
644     if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_STARTED) {
645       p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS;
646       if (p_data->role_res.hci_status != HCI_SUCCESS) {
647         p_scb->role &= ~BTA_AV_ROLE_START_INT;
648         bta_sys_idle(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress());
649         /* start failed because of role switch. */
650         tBTA_AV_START start;
651         start.chnl = p_scb->chnl;
652         start.status = BTA_AV_FAIL_ROLE;
653         start.hndl = p_scb->hndl;
654         start.initiator = initiator;
655         tBTA_AV bta_av_data;
656         bta_av_data.start = start;
657         (*bta_av_cb.p_cback)(BTA_AV_START_EVT, &bta_av_data);
658       } else {
659         bta_av_start_ok(p_scb, p_data);
660       }
661     } else if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_RES_START)
662       p_scb->wait |= BTA_AV_WAIT_ROLE_SW_FAILED;
663   } else if (p_scb->q_tag == BTA_AV_Q_TAG_OPEN) {
664     if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_RES_OPEN) {
665       p_scb->role &= ~BTA_AV_ROLE_START_INT;
666       p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS;
667 
668       if (p_data->role_res.hci_status != HCI_SUCCESS) {
669         /* Open failed because of role switch. */
670         tBTA_AV_OPEN av_open;
671         av_open.bd_addr = p_scb->PeerAddress();
672         av_open.chnl = p_scb->chnl;
673         av_open.hndl = p_scb->hndl;
674         av_open.status = BTA_AV_FAIL_ROLE;
675         if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC) {
676           av_open.sep = AVDT_TSEP_SNK;
677         } else if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SNK) {
678           av_open.sep = AVDT_TSEP_SRC;
679         }
680         tBTA_AV bta_av_data;
681         bta_av_data.open = av_open;
682         (*bta_av_cb.p_cback)(BTA_AV_OPEN_EVT, &bta_av_data);
683       } else {
684         /* Continue av open process */
685         p_scb->q_info.open.switch_res = BTA_AV_RS_DONE;
686         bta_av_do_disc_a2dp(p_scb, (tBTA_AV_DATA*)&(p_scb->q_info.open));
687       }
688     } else {
689       APPL_TRACE_WARNING(
690           "%s: peer %s unexpected role switch event: q_tag = %d wait = 0x%x",
691           __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->q_tag,
692           p_scb->wait);
693     }
694   }
695 
696   APPL_TRACE_DEBUG("%s: peer %s wait:0x%x, role:0x%x", __func__,
697                    p_scb->PeerAddress().ToString().c_str(), p_scb->wait,
698                    p_scb->role);
699 }
700 
701 /*******************************************************************************
702  *
703  * Function         bta_av_delay_co
704  *
705  * Description      Call the delay call-out function to report the delay report
706  *                  from SNK
707  *
708  * Returns          void
709  *
710  ******************************************************************************/
bta_av_delay_co(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)711 void bta_av_delay_co(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
712   APPL_TRACE_DEBUG("%s: peer %s bta_handle:0x%x delay:%d", __func__,
713                    p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
714                    p_data->str_msg.msg.delay_rpt_cmd.delay);
715   p_scb->p_cos->delay(p_scb->hndl, p_scb->PeerAddress(),
716                       p_data->str_msg.msg.delay_rpt_cmd.delay);
717 }
718 
719 /*******************************************************************************
720  *
721  * Function         bta_av_do_disc_a2dp
722  *
723  * Description      Do service discovery for A2DP.
724  *
725  * Returns          void
726  *
727  ******************************************************************************/
bta_av_do_disc_a2dp(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)728 void bta_av_do_disc_a2dp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
729   bool ok_continue = false;
730   tA2DP_SDP_DB_PARAMS db_params;
731   uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST,
732                           ATTR_ID_PROTOCOL_DESC_LIST,
733                           ATTR_ID_BT_PROFILE_DESC_LIST};
734   uint16_t sdp_uuid = 0; /* UUID for which SDP has to be done */
735 
736   APPL_TRACE_DEBUG("%s: peer_addr: %s use_rc: %d switch_res:%d, oc:%d",
737                    __func__, p_data->api_open.bd_addr.ToString().c_str(),
738                    p_data->api_open.use_rc, p_data->api_open.switch_res,
739                    bta_av_cb.audio_open_cnt);
740 
741   memcpy(&(p_scb->open_api), &(p_data->api_open), sizeof(tBTA_AV_API_OPEN));
742 
743   switch (p_data->api_open.switch_res) {
744     case BTA_AV_RS_NONE:
745       if (bta_av_switch_if_needed(p_scb) ||
746           !bta_av_link_role_ok(p_scb, A2DP_SET_MULTL_BIT)) {
747         /* waiting for role switch result. save the api to control block */
748         memcpy(&p_scb->q_info.open, &p_data->api_open,
749                sizeof(tBTA_AV_API_OPEN));
750         p_scb->wait |= BTA_AV_WAIT_ROLE_SW_RES_OPEN;
751         p_scb->q_tag = BTA_AV_Q_TAG_OPEN;
752       } else {
753         ok_continue = true;
754       }
755       break;
756 
757     case BTA_AV_RS_FAIL:
758       /* report a new failure event  */
759       p_scb->open_status = BTA_AV_FAIL_ROLE;
760       APPL_TRACE_ERROR("%s: BTA_AV_SDP_DISC_FAIL_EVT: peer_addr=%s", __func__,
761                        p_scb->PeerAddress().ToString().c_str());
762       bta_av_ssm_execute(p_scb, BTA_AV_SDP_DISC_FAIL_EVT, NULL);
763       break;
764 
765     case BTA_AV_RS_OK:
766       p_data = (tBTA_AV_DATA*)&p_scb->q_info.open;
767       /* continue to open if link role is ok */
768       if (bta_av_link_role_ok(p_scb, A2DP_SET_MULTL_BIT)) {
769         ok_continue = true;
770       } else {
771         p_scb->wait |= BTA_AV_WAIT_ROLE_SW_RES_OPEN;
772       }
773       break;
774 
775     case BTA_AV_RS_DONE:
776       ok_continue = true;
777       break;
778   }
779 
780   APPL_TRACE_DEBUG("%s: ok_continue: %d wait:0x%x, q_tag: %d", __func__,
781                    ok_continue, p_scb->wait, p_scb->q_tag);
782   if (!ok_continue) return;
783 
784   /* clear the role switch bits */
785   p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS;
786 
787   if (p_scb->wait & BTA_AV_WAIT_CHECK_RC) {
788     p_scb->wait &= ~BTA_AV_WAIT_CHECK_RC;
789     bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_RC_DISC_TIME_VAL,
790                         BTA_AV_AVRC_TIMER_EVT, p_scb->hndl);
791   }
792 
793   /* store peer addr other parameters */
794   bta_av_save_addr(p_scb, p_data->api_open.bd_addr);
795   p_scb->use_rc = p_data->api_open.use_rc;
796 
797   bta_sys_app_open(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress());
798 
799   /* set up parameters */
800   db_params.db_len = BTA_AV_DISC_BUF_SIZE;
801   db_params.num_attr = 3;
802   db_params.p_attrs = attr_list;
803   p_scb->uuid_int = p_data->api_open.uuid;
804   p_scb->sdp_discovery_started = true;
805   if (p_scb->uuid_int == UUID_SERVCLASS_AUDIO_SINK)
806     sdp_uuid = UUID_SERVCLASS_AUDIO_SOURCE;
807   else if (p_scb->uuid_int == UUID_SERVCLASS_AUDIO_SOURCE)
808     sdp_uuid = UUID_SERVCLASS_AUDIO_SINK;
809 
810   APPL_TRACE_DEBUG(
811       "%s: Initiate SDP discovery for peer %s : uuid_int=0x%x "
812       "sdp_uuid=0x%x",
813       __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->uuid_int,
814       sdp_uuid);
815   tA2DP_STATUS find_service_status = A2DP_FindService(
816       sdp_uuid, p_scb->PeerAddress(), &db_params, bta_av_a2dp_sdp_cback);
817   if (find_service_status != A2DP_SUCCESS) {
818     APPL_TRACE_ERROR(
819         "%s: A2DP_FindService() failed for peer %s uuid_int=0x%x "
820         "sdp_uuid=0x%x : status=%d",
821         __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->uuid_int,
822         sdp_uuid, find_service_status);
823     bta_av_a2dp_sdp_cback(false, nullptr, p_scb->PeerAddress());
824   } else {
825     /* only one A2DP find service is active at a time */
826     bta_av_cb.handle = p_scb->hndl;
827   }
828 }
829 
830 /*******************************************************************************
831  *
832  * Function         bta_av_cleanup
833  *
834  * Description      cleanup AV stream control block.
835  *
836  * Returns          void
837  *
838  ******************************************************************************/
bta_av_cleanup(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)839 void bta_av_cleanup(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
840   tBTA_AV_CONN_CHG msg;
841   uint8_t role = BTA_AV_ROLE_AD_INT;
842 
843   LOG_INFO("%s peer %s", __func__, p_scb->PeerAddress().ToString().c_str());
844 
845   /* free any buffers */
846   p_scb->sdp_discovery_started = false;
847   p_scb->SetAvdtpVersion(0);
848 
849   /* initialize some control block variables */
850   p_scb->open_status = BTA_AV_SUCCESS;
851 
852   /* if de-registering shut everything down */
853   msg.hdr.layer_specific = p_scb->hndl;
854   p_scb->started = false;
855   p_scb->use_rtp_header_marker_bit = false;
856   p_scb->cong = false;
857   p_scb->role = role;
858   p_scb->cur_psc_mask = 0;
859   p_scb->wait = 0;
860   p_scb->num_disc_snks = 0;
861   p_scb->coll_mask = 0;
862   alarm_cancel(p_scb->avrc_ct_timer);
863   alarm_cancel(p_scb->link_signalling_timer);
864   alarm_cancel(p_scb->accept_signalling_timer);
865 
866   /* TODO(eisenbach): RE-IMPLEMENT USING VSC OR HAL EXTENSION
867     vendor_get_interface()->send_command(
868         (vendor_opcode_t)BT_VND_OP_A2DP_OFFLOAD_STOP, (void*)&p_scb->l2c_cid);
869     if (p_scb->offload_start_pending) {
870       tBTA_AV_STATUS status = BTA_AV_FAIL_STREAM;
871       tBTA_AV bta_av_data;
872       bta_av_data.status = status;
873       (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &bta_av_data);
874     }
875   */
876 
877   if (p_scb->deregistering) {
878     /* remove stream */
879     for (int i = 0; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) {
880       if (p_scb->seps[i].av_handle) AVDT_RemoveStream(p_scb->seps[i].av_handle);
881       p_scb->seps[i].av_handle = 0;
882     }
883 
884     bta_av_dereg_comp((tBTA_AV_DATA*)&msg);
885   } else {
886     /* report stream closed to main SM */
887     msg.is_up = false;
888     msg.peer_addr = p_scb->PeerAddress();
889     bta_av_conn_chg((tBTA_AV_DATA*)&msg);
890   }
891 }
892 
893 /*******************************************************************************
894  *
895  * Function         bta_av_free_sdb
896  *
897  * Description      Free service discovery db buffer.
898  *
899  * Returns          void
900  *
901  ******************************************************************************/
bta_av_free_sdb(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)902 void bta_av_free_sdb(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
903   p_scb->sdp_discovery_started = false;
904 }
905 
906 /*******************************************************************************
907  *
908  * Function         bta_av_config_ind
909  *
910  * Description      Handle a stream configuration indication from the peer.
911  *
912  * Returns          void
913  *
914  ******************************************************************************/
bta_av_config_ind(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)915 void bta_av_config_ind(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
916   tBTA_AV_CI_SETCONFIG setconfig{};
917   tAVDT_SEP_INFO* p_info;
918   const AvdtpSepConfig* p_evt_cfg = &p_data->str_msg.cfg;
919   uint8_t psc_mask = (p_evt_cfg->psc_mask | p_scb->cfg.psc_mask);
920   uint8_t
921       local_sep; /* sep type of local handle on which connection was received */
922   tBTA_AV_STR_MSG* p_msg = (tBTA_AV_STR_MSG*)p_data;
923 
924   local_sep = bta_av_get_scb_sep_type(p_scb, p_msg->handle);
925   p_scb->avdt_label = p_data->str_msg.msg.hdr.label;
926 
927   APPL_TRACE_DEBUG("%s: peer %s bta_handle:0x%x local_sep:%d", __func__,
928                    p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
929                    local_sep);
930   APPL_TRACE_DEBUG("%s: codec: %s", __func__,
931                    A2DP_CodecInfoString(p_evt_cfg->codec_info).c_str());
932 
933   memcpy(p_scb->cfg.codec_info, p_evt_cfg->codec_info, AVDT_CODEC_SIZE);
934   bta_av_save_addr(p_scb, p_data->str_msg.bd_addr);
935 
936   /* Clear collision mask */
937   p_scb->coll_mask = 0;
938   alarm_cancel(p_scb->accept_signalling_timer);
939 
940   /* if no codec parameters in configuration, fail */
941   if ((p_evt_cfg->num_codec == 0) ||
942       /* or the peer requests for a service we do not support */
943       ((psc_mask != p_scb->cfg.psc_mask) &&
944        (psc_mask != (p_scb->cfg.psc_mask & ~AVDT_PSC_DELAY_RPT)))) {
945     setconfig.hndl = p_scb->hndl; /* we may not need this */
946     setconfig.err_code = AVDT_ERR_UNSUP_CFG;
947     bta_av_ssm_execute(p_scb, BTA_AV_CI_SETCONFIG_FAIL_EVT,
948                        (tBTA_AV_DATA*)&setconfig);
949   } else {
950     p_info = &p_scb->sep_info[0];
951     p_info->in_use = 0;
952     p_info->media_type = p_scb->media_type;
953     p_info->seid = p_data->str_msg.msg.config_ind.int_seid;
954 
955     /* Sep type of Peer will be oppsite role to our local sep */
956     if (local_sep == AVDT_TSEP_SRC)
957       p_info->tsep = AVDT_TSEP_SNK;
958     else if (local_sep == AVDT_TSEP_SNK)
959       p_info->tsep = AVDT_TSEP_SRC;
960 
961     p_scb->role |= BTA_AV_ROLE_AD_ACP;
962     p_scb->cur_psc_mask = p_evt_cfg->psc_mask;
963     if (bta_av_cb.features & BTA_AV_FEAT_RCTG)
964       p_scb->use_rc = true;
965     else
966       p_scb->use_rc = false;
967 
968     p_scb->num_seps = 1;
969     p_scb->sep_info_idx = 0;
970     APPL_TRACE_DEBUG("%s: SEID: %d use_rc: %d cur_psc_mask:0x%x", __func__,
971                      p_info->seid, p_scb->use_rc, p_scb->cur_psc_mask);
972     /*  in case of A2DP SINK this is the first time peer data is being sent to
973      * co functions */
974     if (local_sep == AVDT_TSEP_SNK) {
975       p_scb->p_cos->setcfg(p_scb->hndl, p_scb->PeerAddress(),
976                            p_evt_cfg->codec_info, p_info->seid,
977                            p_evt_cfg->num_protect, p_evt_cfg->protect_info,
978                            AVDT_TSEP_SNK, p_msg->handle);
979     } else {
980       p_scb->p_cos->setcfg(p_scb->hndl, p_scb->PeerAddress(),
981                            p_evt_cfg->codec_info, p_info->seid,
982                            p_evt_cfg->num_protect, p_evt_cfg->protect_info,
983                            AVDT_TSEP_SRC, p_msg->handle);
984     }
985   }
986 }
987 
988 /*******************************************************************************
989  *
990  * Function         bta_av_disconnect_req
991  *
992  * Description      Disconnect AVDTP connection.
993  *
994  * Returns          void
995  *
996  ******************************************************************************/
bta_av_disconnect_req(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)997 void bta_av_disconnect_req(tBTA_AV_SCB* p_scb,
998                            UNUSED_ATTR tBTA_AV_DATA* p_data) {
999   tBTA_AV_RCB* p_rcb;
1000 
1001   APPL_TRACE_API("%s: conn_lcb: 0x%x peer_addr: %s", __func__,
1002                  bta_av_cb.conn_lcb, p_scb->PeerAddress().ToString().c_str());
1003 
1004   alarm_cancel(p_scb->link_signalling_timer);
1005   alarm_cancel(p_scb->accept_signalling_timer);
1006   alarm_cancel(p_scb->avrc_ct_timer);
1007 
1008   // conn_lcb is the index bitmask of all used LCBs, and since LCB and SCB use
1009   // the same index, it should be safe to use SCB index here.
1010   if ((bta_av_cb.conn_lcb & (1 << p_scb->hdi)) != 0) {
1011     p_rcb = bta_av_get_rcb_by_shdl((uint8_t)(p_scb->hdi + 1));
1012     if (p_rcb) bta_av_del_rc(p_rcb);
1013     AVDT_DisconnectReq(p_scb->PeerAddress(), &bta_av_proc_stream_evt);
1014   } else {
1015     APPL_TRACE_WARNING("%s: conn_lcb=0x%x bta_handle=0x%x (hdi=%u) no link",
1016                        __func__, bta_av_cb.conn_lcb, p_scb->hndl, p_scb->hdi);
1017     bta_av_ssm_execute(p_scb, BTA_AV_AVDT_DISCONNECT_EVT, NULL);
1018   }
1019 }
1020 
1021 /*******************************************************************************
1022  *
1023  * Function         bta_av_security_req
1024  *
1025  * Description      Send an AVDTP security request.
1026  *
1027  * Returns          void
1028  *
1029  ******************************************************************************/
bta_av_security_req(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1030 void bta_av_security_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1031   if (bta_av_cb.features & BTA_AV_FEAT_PROTECT) {
1032     AVDT_SecurityReq(p_scb->avdt_handle, p_data->api_protect_req.p_data,
1033                      p_data->api_protect_req.len);
1034   }
1035 }
1036 
1037 /*******************************************************************************
1038  *
1039  * Function         bta_av_security_rsp
1040  *
1041  * Description      Send an AVDTP security response.
1042  *
1043  * Returns          void
1044  *
1045  ******************************************************************************/
bta_av_security_rsp(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1046 void bta_av_security_rsp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1047   if (bta_av_cb.features & BTA_AV_FEAT_PROTECT) {
1048     AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label,
1049                      p_data->api_protect_rsp.error_code,
1050                      p_data->api_protect_rsp.p_data,
1051                      p_data->api_protect_rsp.len);
1052   } else {
1053     AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_NSC, NULL,
1054                      0);
1055   }
1056 }
1057 
1058 /*******************************************************************************
1059  *
1060  * Function         bta_av_setconfig_rsp
1061  *
1062  * Description      setconfig is OK
1063  *
1064  * Returns          void
1065  *
1066  ******************************************************************************/
bta_av_setconfig_rsp(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1067 void bta_av_setconfig_rsp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1068   uint8_t num = p_data->ci_setconfig.num_seid + 1;
1069   uint8_t avdt_handle = p_data->ci_setconfig.avdt_handle;
1070   uint8_t* p_seid = p_data->ci_setconfig.p_seid;
1071   int i;
1072   uint8_t local_sep;
1073 
1074   /* we like this codec_type. find the sep_idx */
1075   local_sep = bta_av_get_scb_sep_type(p_scb, avdt_handle);
1076   bta_av_adjust_seps_idx(p_scb, avdt_handle);
1077   LOG_INFO(
1078       "%s: peer %s bta_handle=0x%x avdt_handle=%d sep_idx=%d cur_psc_mask:0x%x",
1079       __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
1080       p_scb->avdt_handle, p_scb->sep_idx, p_scb->cur_psc_mask);
1081 
1082   if ((AVDT_TSEP_SNK == local_sep) &&
1083       (p_data->ci_setconfig.err_code == AVDT_SUCCESS) &&
1084       (p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback != NULL)) {
1085     tBTA_AV_MEDIA av_sink_codec_info;
1086     av_sink_codec_info.avk_config.bd_addr = p_scb->PeerAddress();
1087     av_sink_codec_info.avk_config.codec_info = p_scb->cfg.codec_info;
1088     p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback(
1089         p_scb->PeerAddress(), BTA_AV_SINK_MEDIA_CFG_EVT, &av_sink_codec_info);
1090   }
1091 
1092   AVDT_ConfigRsp(p_scb->avdt_handle, p_scb->avdt_label,
1093                  p_data->ci_setconfig.err_code, p_data->ci_setconfig.category);
1094 
1095   alarm_cancel(p_scb->link_signalling_timer);
1096 
1097   if (p_data->ci_setconfig.err_code == AVDT_SUCCESS) {
1098     p_scb->wait = BTA_AV_WAIT_ACP_CAPS_ON;
1099     if (p_data->ci_setconfig.recfg_needed)
1100       p_scb->role |= BTA_AV_ROLE_SUSPEND_OPT;
1101     APPL_TRACE_DEBUG("%s: recfg_needed:%d role:0x%x num:%d", __func__,
1102                      p_data->ci_setconfig.recfg_needed, p_scb->role, num);
1103     /* callout module tells BTA the number of "good" SEPs and their SEIDs.
1104      * getcap on these SEID */
1105     p_scb->num_seps = num;
1106 
1107     if (p_scb->cur_psc_mask & AVDT_PSC_DELAY_RPT)
1108       p_scb->SetAvdtpVersion(AVDT_VERSION_1_3);
1109 
1110     if (A2DP_GetCodecType(p_scb->cfg.codec_info) == A2DP_MEDIA_CT_SBC ||
1111         num > 1) {
1112       /* if SBC is used by the SNK as INT, discover req is not sent in
1113        * bta_av_config_ind.
1114        * call disc_res now */
1115       /* this is called in A2DP SRC path only, In case of SINK we don't need it
1116        */
1117       if (local_sep == AVDT_TSEP_SRC)
1118         p_scb->p_cos->disc_res(p_scb->hndl, p_scb->PeerAddress(), num, num, 0,
1119                                UUID_SERVCLASS_AUDIO_SOURCE);
1120     } else {
1121       /* we do not know the peer device and it is using non-SBC codec
1122        * we need to know all the SEPs on SNK */
1123       if (p_scb->uuid_int == 0) p_scb->uuid_int = p_scb->open_api.uuid;
1124       bta_av_discover_req(p_scb, NULL);
1125       return;
1126     }
1127 
1128     for (i = 1; i < num; i++) {
1129       APPL_TRACE_DEBUG("%s: sep_info[%d] SEID: %d", __func__, i, p_seid[i - 1]);
1130       /* initialize the sep_info[] to get capabilities */
1131       p_scb->sep_info[i].in_use = false;
1132       p_scb->sep_info[i].tsep = AVDT_TSEP_SNK;
1133       p_scb->sep_info[i].media_type = p_scb->media_type;
1134       p_scb->sep_info[i].seid = p_seid[i - 1];
1135     }
1136 
1137     /* only in case of local sep as SRC we need to look for other SEPs, In case
1138      * of SINK we don't */
1139     if (local_sep == AVDT_TSEP_SRC) {
1140       /* Make sure UUID has been initialized... */
1141       if (p_scb->uuid_int == 0) p_scb->uuid_int = p_scb->open_api.uuid;
1142       bta_av_next_getcap(p_scb, p_data);
1143     }
1144   }
1145 }
1146 
1147 /*******************************************************************************
1148  *
1149  * Function         bta_av_str_opened
1150  *
1151  * Description      Stream opened OK (incoming/outgoing).
1152  *
1153  * Returns          void
1154  *
1155  ******************************************************************************/
bta_av_str_opened(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1156 void bta_av_str_opened(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1157   tBTA_AV_CONN_CHG msg;
1158   char remote_name[BTM_MAX_REM_BD_NAME_LEN] = "";
1159   uint8_t* p;
1160 
1161   APPL_TRACE_DEBUG("%s: peer %s bta_handle: 0x%x", __func__,
1162                    p_scb->PeerAddress().ToString().c_str(), p_scb->hndl);
1163 
1164   msg.hdr.layer_specific = p_scb->hndl;
1165   msg.is_up = true;
1166   msg.peer_addr = p_scb->PeerAddress();
1167   p_scb->l2c_cid = AVDT_GetL2CapChannel(p_scb->avdt_handle);
1168   bta_av_conn_chg((tBTA_AV_DATA*)&msg);
1169   /* set the congestion flag, so AV would not send media packets by accident */
1170   p_scb->cong = true;
1171   // Don't use AVDTP SUSPEND for restrict listed devices
1172   btif_storage_get_stored_remote_name(p_scb->PeerAddress(), remote_name);
1173   if (interop_match_name(INTEROP_DISABLE_AVDTP_SUSPEND, remote_name) ||
1174       interop_match_addr(INTEROP_DISABLE_AVDTP_SUSPEND,
1175                          &p_scb->PeerAddress())) {
1176     LOG_INFO("%s: disable AVDTP SUSPEND: interop matched name %s address %s",
1177              __func__, remote_name, p_scb->PeerAddress().ToString().c_str());
1178     p_scb->suspend_sup = false;
1179   }
1180 
1181   p_scb->stream_mtu =
1182       p_data->str_msg.msg.open_ind.peer_mtu - AVDT_MEDIA_HDR_SIZE;
1183   APPL_TRACE_DEBUG("%s: l2c_cid: 0x%x stream_mtu: %d", __func__, p_scb->l2c_cid,
1184                    p_scb->stream_mtu);
1185 
1186   /* Set the media channel as high priority */
1187   L2CA_SetTxPriority(p_scb->l2c_cid, L2CAP_CHNL_PRIORITY_HIGH);
1188   L2CA_SetChnlFlushability(p_scb->l2c_cid, true);
1189 
1190   bta_sys_conn_open(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress());
1191   memset(&p_scb->q_info, 0, sizeof(tBTA_AV_Q_INFO));
1192 
1193   p_scb->l2c_bufs = 0;
1194   p_scb->p_cos->open(p_scb->hndl, p_scb->PeerAddress(), p_scb->stream_mtu);
1195 
1196   {
1197     /* TODO check if other audio channel is open.
1198      * If yes, check if reconfig is needed
1199      * Rigt now we do not do this kind of checking.
1200      * BTA-AV is INT for 2nd audio connection.
1201      * The application needs to make sure the current codec_info is proper.
1202      * If one audio connection is open and another SNK attempts to connect to
1203      * AV,
1204      * the connection will be rejected.
1205      */
1206     /* check if other audio channel is started. If yes, start */
1207     tBTA_AV_OPEN open;
1208     open.bd_addr = p_scb->PeerAddress();
1209     open.chnl = p_scb->chnl;
1210     open.hndl = p_scb->hndl;
1211     open.status = BTA_AV_SUCCESS;
1212     open.edr = 0;
1213     p = BTM_ReadRemoteFeatures(p_scb->PeerAddress());
1214     if (p != NULL) {
1215       if (HCI_EDR_ACL_2MPS_SUPPORTED(p)) open.edr |= BTA_AV_EDR_2MBPS;
1216       if (HCI_EDR_ACL_3MPS_SUPPORTED(p)) {
1217         if (!interop_match_addr(INTEROP_2MBPS_LINK_ONLY,
1218                                 &p_scb->PeerAddress())) {
1219           open.edr |= BTA_AV_EDR_3MBPS;
1220         }
1221       }
1222     }
1223     bta_ar_avdt_conn(BTA_ID_AV, open.bd_addr, p_scb->hdi);
1224     if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC) {
1225       open.starting = false;
1226       open.sep = AVDT_TSEP_SNK;
1227     } else if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SNK) {
1228       open.starting = bta_av_chk_start(p_scb);
1229       open.sep = AVDT_TSEP_SRC;
1230     }
1231 
1232     tBTA_AV bta_av_data;
1233     bta_av_data.open = open;
1234     (*bta_av_cb.p_cback)(BTA_AV_OPEN_EVT, &bta_av_data);
1235     if (open.starting) {
1236       bta_av_ssm_execute(p_scb, BTA_AV_AP_START_EVT, NULL);
1237     }
1238   }
1239 
1240   // This code is used to pass PTS TC for AVDTP ABORT
1241   char value[PROPERTY_VALUE_MAX] = {0};
1242   if ((osi_property_get("bluetooth.pts.force_a2dp_abort", value, "false")) &&
1243       (!strcmp(value, "true"))) {
1244     APPL_TRACE_ERROR("%s: Calling AVDT_AbortReq", __func__);
1245     AVDT_AbortReq(p_scb->avdt_handle);
1246   }
1247 }
1248 
1249 /*******************************************************************************
1250  *
1251  * Function         bta_av_security_ind
1252  *
1253  * Description      Handle an AVDTP security indication.
1254  *
1255  * Returns          void
1256  *
1257  ******************************************************************************/
bta_av_security_ind(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1258 void bta_av_security_ind(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1259   p_scb->avdt_label = p_data->str_msg.msg.hdr.label;
1260 
1261   if (bta_av_cb.features & BTA_AV_FEAT_PROTECT) {
1262     tBTA_AV_PROTECT_REQ protect_req;
1263     protect_req.chnl = p_scb->chnl;
1264     protect_req.hndl = p_scb->hndl;
1265     protect_req.p_data = p_data->str_msg.msg.security_ind.p_data;
1266     protect_req.len = p_data->str_msg.msg.security_ind.len;
1267 
1268     tBTA_AV bta_av_data;
1269     bta_av_data.protect_req = protect_req;
1270     (*bta_av_cb.p_cback)(BTA_AV_PROTECT_REQ_EVT, &bta_av_data);
1271   }
1272   /* app doesn't support security indication; respond with failure */
1273   else {
1274     AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_NSC, NULL,
1275                      0);
1276   }
1277 }
1278 
1279 /*******************************************************************************
1280  *
1281  * Function         bta_av_security_cfm
1282  *
1283  * Description      Handle an AVDTP security confirm.
1284  *
1285  * Returns          void
1286  *
1287  ******************************************************************************/
bta_av_security_cfm(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1288 void bta_av_security_cfm(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1289   if (bta_av_cb.features & BTA_AV_FEAT_PROTECT) {
1290     tBTA_AV_PROTECT_RSP protect_rsp;
1291     protect_rsp.chnl = p_scb->chnl;
1292     protect_rsp.hndl = p_scb->hndl;
1293     protect_rsp.p_data = p_data->str_msg.msg.security_cfm.p_data;
1294     protect_rsp.len = p_data->str_msg.msg.security_cfm.len;
1295     protect_rsp.err_code = p_data->str_msg.msg.hdr.err_code;
1296 
1297     tBTA_AV bta_av_data;
1298     bta_av_data.protect_rsp = protect_rsp;
1299     (*bta_av_cb.p_cback)(BTA_AV_PROTECT_RSP_EVT, &bta_av_data);
1300   }
1301 }
1302 
1303 /*******************************************************************************
1304  *
1305  * Function         bta_av_do_close
1306  *
1307  * Description      Close stream.
1308  *
1309  * Returns          void
1310  *
1311  ******************************************************************************/
bta_av_do_close(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)1312 void bta_av_do_close(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
1313   APPL_TRACE_DEBUG("%s: p_scb->co_started=%d", __func__, p_scb->co_started);
1314 
1315   /* stop stream if started */
1316   if (p_scb->co_started) {
1317     bta_av_str_stopped(p_scb, NULL);
1318   }
1319   alarm_cancel(p_scb->link_signalling_timer);
1320 
1321   /* close stream */
1322   p_scb->started = false;
1323   p_scb->use_rtp_header_marker_bit = false;
1324 
1325   /* drop the buffers queued in L2CAP */
1326   L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL);
1327 
1328   AVDT_CloseReq(p_scb->avdt_handle);
1329   /* just in case that the link is congested, link is flow controled by peer or
1330    * for whatever reason the the close request can not be sent in time.
1331    * when this timer expires, AVDT_DisconnectReq will be called to disconnect
1332    * the link
1333    */
1334   bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_CLOSE_REQ_TIME_VAL,
1335                       BTA_AV_API_CLOSE_EVT, p_scb->hndl);
1336 }
1337 
1338 /*******************************************************************************
1339  *
1340  * Function         bta_av_connect_req
1341  *
1342  * Description      Connect AVDTP connection.
1343  *
1344  * Returns          void
1345  *
1346  ******************************************************************************/
bta_av_connect_req(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)1347 void bta_av_connect_req(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
1348   APPL_TRACE_DEBUG("%s: peer %s coll_mask=0x%02x", __func__,
1349                    p_scb->PeerAddress().ToString().c_str(), p_scb->coll_mask);
1350   p_scb->sdp_discovery_started = false;
1351   if (p_scb->coll_mask & BTA_AV_COLL_INC_TMR) {
1352     /* SNK initiated L2C connection while SRC was doing SDP.    */
1353     /* Wait until timeout to check if SNK starts signalling.    */
1354     APPL_TRACE_WARNING("%s: coll_mask=0x%02x incoming timer is up", __func__,
1355                        p_scb->coll_mask);
1356     p_scb->coll_mask |= BTA_AV_COLL_API_CALLED;
1357     APPL_TRACE_EVENT("%s: updated coll_mask=0x%02x", __func__,
1358                      p_scb->coll_mask);
1359     return;
1360   }
1361 
1362   AVDT_ConnectReq(p_scb->PeerAddress(), p_scb->hdi, &bta_av_proc_stream_evt);
1363 }
1364 
1365 /*******************************************************************************
1366  *
1367  * Function         bta_av_sdp_failed
1368  *
1369  * Description      Service discovery failed.
1370  *
1371  * Returns          void
1372  *
1373  ******************************************************************************/
bta_av_sdp_failed(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1374 void bta_av_sdp_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1375   APPL_TRACE_ERROR("%s: peer_addr=%s open_status=%d", __func__,
1376                    p_scb->PeerAddress().ToString().c_str(), p_scb->open_status);
1377 
1378   if (p_scb->open_status == BTA_AV_SUCCESS) {
1379     p_scb->open_status = BTA_AV_FAIL_SDP;
1380   }
1381 
1382   p_scb->sdp_discovery_started = false;
1383   bta_av_str_closed(p_scb, p_data);
1384 }
1385 
1386 /*******************************************************************************
1387  *
1388  * Function         bta_av_disc_results
1389  *
1390  * Description      Handle the AVDTP discover results.  Search through the
1391  *                  results and find the first available stream, and get
1392  *                  its capabilities.
1393  *
1394  * Returns          void
1395  *
1396  ******************************************************************************/
bta_av_disc_results(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1397 void bta_av_disc_results(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1398   uint8_t num_snks = 0, num_srcs = 0, i;
1399   /* our uuid in case we initiate connection */
1400   uint16_t uuid_int = p_scb->uuid_int;
1401 
1402   APPL_TRACE_DEBUG("%s: peer %s bta_handle: 0x%x initiator UUID 0x%x", __func__,
1403                    p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
1404                    uuid_int);
1405 
1406   /* store number of stream endpoints returned */
1407   p_scb->num_seps = p_data->str_msg.msg.discover_cfm.num_seps;
1408 
1409   for (i = 0; i < p_scb->num_seps; i++) {
1410     /* steam not in use, is a sink, and is audio */
1411     if ((!p_scb->sep_info[i].in_use) &&
1412         (p_scb->sep_info[i].media_type == p_scb->media_type)) {
1413       if ((p_scb->sep_info[i].tsep == AVDT_TSEP_SNK) &&
1414           (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE))
1415         num_snks++;
1416 
1417       if ((p_scb->sep_info[i].tsep == AVDT_TSEP_SRC) &&
1418           (uuid_int == UUID_SERVCLASS_AUDIO_SINK))
1419         num_srcs++;
1420     }
1421   }
1422 
1423   p_scb->p_cos->disc_res(p_scb->hndl, p_scb->PeerAddress(), p_scb->num_seps,
1424                          num_snks, num_srcs, uuid_int);
1425   p_scb->num_disc_snks = num_snks;
1426   p_scb->num_disc_srcs = num_srcs;
1427 
1428   /* if we got any */
1429   if (p_scb->num_seps > 0) {
1430     /* initialize index into discovery results */
1431     p_scb->sep_info_idx = 0;
1432 
1433     /* get the capabilities of the first available stream */
1434     bta_av_next_getcap(p_scb, p_data);
1435   }
1436   /* else we got discover response but with no streams; we're done */
1437   else {
1438     APPL_TRACE_ERROR("%s: BTA_AV_STR_DISC_FAIL_EVT: peer_addr=%s", __func__,
1439                      p_scb->PeerAddress().ToString().c_str());
1440     bta_av_ssm_execute(p_scb, BTA_AV_STR_DISC_FAIL_EVT, p_data);
1441   }
1442 }
1443 
1444 /*******************************************************************************
1445  *
1446  * Function         bta_av_disc_res_as_acp
1447  *
1448  * Description      Handle the AVDTP discover results.  Search through the
1449  *                  results and find the first available stream, and get
1450  *                  its capabilities.
1451  *
1452  * Returns          void
1453  *
1454  ******************************************************************************/
bta_av_disc_res_as_acp(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1455 void bta_av_disc_res_as_acp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1456   uint8_t num_snks = 0, i;
1457 
1458   APPL_TRACE_DEBUG("%s: peer %s bta_handle: 0x%x", __func__,
1459                    p_scb->PeerAddress().ToString().c_str(), p_scb->hndl);
1460 
1461   /* store number of stream endpoints returned */
1462   p_scb->num_seps = p_data->str_msg.msg.discover_cfm.num_seps;
1463 
1464   for (i = 0; i < p_scb->num_seps; i++) {
1465     /* steam is a sink, and is audio */
1466     if ((p_scb->sep_info[i].tsep == AVDT_TSEP_SNK) &&
1467         (p_scb->sep_info[i].media_type == p_scb->media_type)) {
1468       p_scb->sep_info[i].in_use = false;
1469       num_snks++;
1470     }
1471   }
1472   p_scb->p_cos->disc_res(p_scb->hndl, p_scb->PeerAddress(), p_scb->num_seps,
1473                          num_snks, 0, UUID_SERVCLASS_AUDIO_SOURCE);
1474   p_scb->num_disc_snks = num_snks;
1475   p_scb->num_disc_srcs = 0;
1476 
1477   /* if we got any */
1478   if (p_scb->num_seps > 0) {
1479     /* initialize index into discovery results */
1480     p_scb->sep_info_idx = 0;
1481 
1482     /* get the capabilities of the first available stream */
1483     bta_av_next_getcap(p_scb, p_data);
1484   }
1485   /* else we got discover response but with no streams; we're done */
1486   else {
1487     APPL_TRACE_ERROR("%s: BTA_AV_STR_DISC_FAIL_EVT: peer_addr=%s", __func__,
1488                      p_scb->PeerAddress().ToString().c_str());
1489     bta_av_ssm_execute(p_scb, BTA_AV_STR_DISC_FAIL_EVT, p_data);
1490   }
1491 }
1492 
1493 /*******************************************************************************
1494  *
1495  * Function         bta_av_save_caps
1496  *
1497  * Description      report the SNK SEP capabilities to application
1498  *
1499  * Returns          void
1500  *
1501  ******************************************************************************/
bta_av_save_caps(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1502 void bta_av_save_caps(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1503   AvdtpSepConfig cfg;
1504   tAVDT_SEP_INFO* p_info = &p_scb->sep_info[p_scb->sep_info_idx];
1505   uint8_t old_wait = p_scb->wait;
1506   bool getcap_done = false;
1507 
1508   APPL_TRACE_DEBUG(
1509       "%s: peer %s bta_handle:0x%x num_seps:%d sep_info_idx:%d wait:0x%x",
1510       __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
1511       p_scb->num_seps, p_scb->sep_info_idx, p_scb->wait);
1512   APPL_TRACE_DEBUG("%s: codec: %s", __func__,
1513                    A2DP_CodecInfoString(p_scb->peer_cap.codec_info).c_str());
1514 
1515   cfg = p_scb->peer_cap;
1516   /* let application know the capability of the SNK */
1517   if (p_scb->p_cos->getcfg(p_scb->hndl, p_scb->PeerAddress(), cfg.codec_info,
1518                            &p_scb->sep_info_idx, p_info->seid, &cfg.num_protect,
1519                            cfg.protect_info) != A2DP_SUCCESS) {
1520     p_scb->sep_info_idx++;
1521     APPL_TRACE_DEBUG("%s: result: next sep_info_idx:%d", __func__,
1522                      p_scb->sep_info_idx);
1523   } else {
1524     // All capabilities found
1525     getcap_done = true;
1526     APPL_TRACE_DEBUG("%s: result: done sep_info_idx:%d", __func__,
1527                      p_scb->sep_info_idx);
1528   }
1529   APPL_TRACE_DEBUG("%s: codec: %s", __func__,
1530                    A2DP_CodecInfoString(cfg.codec_info).c_str());
1531 
1532   if (p_scb->num_seps > p_scb->sep_info_idx && !getcap_done) {
1533     /* Some devices have seps at the end of the discover list, which is not */
1534     /* matching media type(video not audio).                                */
1535     /* In this case, we are done with getcap without sending another        */
1536     /* request to AVDT.                                                     */
1537     if (!bta_av_next_getcap(p_scb, p_data)) getcap_done = true;
1538   } else {
1539     getcap_done = true;
1540   }
1541 
1542   if (getcap_done) {
1543     APPL_TRACE_DEBUG("%s: getcap_done: num_seps:%d sep_info_idx:%d wait:0x%x",
1544                      __func__, p_scb->num_seps, p_scb->sep_info_idx,
1545                      p_scb->wait);
1546     p_scb->wait &= ~(BTA_AV_WAIT_ACP_CAPS_ON | BTA_AV_WAIT_ACP_CAPS_STARTED);
1547     if (old_wait & BTA_AV_WAIT_ACP_CAPS_STARTED) {
1548       bta_av_start_ok(p_scb, NULL);
1549     }
1550   }
1551 }
1552 
1553 /*******************************************************************************
1554  *
1555  * Function         bta_av_set_use_rc
1556  *
1557  * Description      set to use AVRC for this stream control block.
1558  *
1559  * Returns          void
1560  *
1561  ******************************************************************************/
bta_av_set_use_rc(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)1562 void bta_av_set_use_rc(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
1563   p_scb->use_rc = true;
1564 }
1565 
1566 /*******************************************************************************
1567  *
1568  * Function         bta_av_cco_close
1569  *
1570  * Description      call close call-out function.
1571  *
1572  * Returns          void
1573  *
1574  ******************************************************************************/
bta_av_cco_close(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)1575 void bta_av_cco_close(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
1576   APPL_TRACE_DEBUG("%s: peer %s bta_handle:0x%x", __func__,
1577                    p_scb->PeerAddress().ToString().c_str(), p_scb->hndl);
1578   p_scb->p_cos->close(p_scb->hndl, p_scb->PeerAddress());
1579 }
1580 
1581 /*******************************************************************************
1582  *
1583  * Function         bta_av_open_failed
1584  *
1585  * Description      Failed to open an AVDT stream
1586  *
1587  * Returns          void
1588  *
1589  ******************************************************************************/
bta_av_open_failed(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1590 void bta_av_open_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1591   bool is_av_opened = false;
1592   tBTA_AV_SCB* p_opened_scb = NULL;
1593   uint8_t idx;
1594 
1595   APPL_TRACE_ERROR("%s: peer_addr=%s", __func__,
1596                    p_scb->PeerAddress().ToString().c_str());
1597   p_scb->open_status = BTA_AV_FAIL_STREAM;
1598   bta_av_cco_close(p_scb, p_data);
1599 
1600   /* check whether there is already an opened audio or video connection with the
1601    * same device */
1602   for (idx = 0; (idx < BTA_AV_NUM_STRS) && (!is_av_opened); idx++) {
1603     p_opened_scb = bta_av_cb.p_scb[idx];
1604     if (p_opened_scb && (p_opened_scb->state == BTA_AV_OPEN_SST) &&
1605         (p_opened_scb->PeerAddress() == p_scb->PeerAddress()))
1606       is_av_opened = true;
1607   }
1608 
1609   /* if there is already an active AV connnection with the same bd_addr,
1610      don't send disconnect req, just report the open event with
1611      BTA_AV_FAIL_GET_CAP status */
1612   if (is_av_opened) {
1613     tBTA_AV_OPEN open;
1614     open.bd_addr = p_scb->PeerAddress();
1615     open.chnl = p_scb->chnl;
1616     open.hndl = p_scb->hndl;
1617     open.status = BTA_AV_FAIL_GET_CAP;
1618     open.starting = bta_av_chk_start(p_scb);
1619     open.edr = 0;
1620     /* set the state back to initial state */
1621     bta_av_set_scb_sst_init(p_scb);
1622 
1623     if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC) {
1624       open.sep = AVDT_TSEP_SNK;
1625     } else if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SNK) {
1626       open.sep = AVDT_TSEP_SRC;
1627     }
1628 
1629     APPL_TRACE_ERROR(
1630         "%s: there is already an active connection: peer_addr=%s chnl=%d "
1631         "hndl=0x%x status=%d starting=%d edr=%d",
1632         __func__, open.bd_addr.ToString().c_str(), open.chnl, open.hndl,
1633         open.status, open.starting, open.edr);
1634 
1635     tBTA_AV bta_av_data;
1636     bta_av_data.open = open;
1637     (*bta_av_cb.p_cback)(BTA_AV_OPEN_EVT, &bta_av_data);
1638   } else {
1639     AVDT_DisconnectReq(p_scb->PeerAddress(), &bta_av_proc_stream_evt);
1640   }
1641 }
1642 
1643 /*******************************************************************************
1644  *
1645  * Function         bta_av_getcap_results
1646  *
1647  * Description      Handle the AVDTP get capabilities results.  Check the codec
1648  *                  type and see if it matches ours.  If it does not, get the
1649  *                  capabilities of the next stream, if any.
1650  *
1651  * Returns          void
1652  *
1653  ******************************************************************************/
bta_av_getcap_results(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1654 void bta_av_getcap_results(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1655   AvdtpSepConfig cfg = p_scb->cfg;
1656   uint8_t media_type = A2DP_GetMediaType(p_scb->peer_cap.codec_info);
1657   tAVDT_SEP_INFO* p_info = &p_scb->sep_info[p_scb->sep_info_idx];
1658 
1659   cfg.num_codec = 1;
1660   cfg.num_protect = p_scb->peer_cap.num_protect;
1661   memcpy(cfg.codec_info, p_scb->peer_cap.codec_info, AVDT_CODEC_SIZE);
1662   memcpy(cfg.protect_info, p_scb->peer_cap.protect_info, AVDT_PROTECT_SIZE);
1663 
1664   APPL_TRACE_DEBUG("%s: peer %s bta_handle:0x%x num_codec:%d psc_mask=0x%x",
1665                    __func__, p_scb->PeerAddress().ToString().c_str(),
1666                    p_scb->hndl, p_scb->peer_cap.num_codec, p_scb->cfg.psc_mask);
1667   APPL_TRACE_DEBUG("%s: media type 0x%x, 0x%x", __func__, media_type,
1668                    p_scb->media_type);
1669   APPL_TRACE_DEBUG("%s: codec: %s", __func__,
1670                    A2DP_CodecInfoString(p_scb->cfg.codec_info).c_str());
1671 
1672   /* if codec present and we get a codec configuration */
1673   if ((p_scb->peer_cap.num_codec != 0) && (media_type == p_scb->media_type) &&
1674       (p_scb->p_cos->getcfg(p_scb->hndl, p_scb->PeerAddress(), cfg.codec_info,
1675                             &p_scb->sep_info_idx, p_info->seid,
1676                             &cfg.num_protect,
1677                             cfg.protect_info) == A2DP_SUCCESS)) {
1678     /* UUID for which connection was initiatied */
1679     uint16_t uuid_int = p_scb->uuid_int;
1680 
1681     /* save copy of codec configuration */
1682     p_scb->cfg = cfg;
1683 
1684     APPL_TRACE_DEBUG("%s: result: sep_info_idx=%d", __func__,
1685                      p_scb->sep_info_idx);
1686     APPL_TRACE_DEBUG("%s: codec: %s", __func__,
1687                      A2DP_CodecInfoString(p_scb->cfg.codec_info).c_str());
1688 
1689     APPL_TRACE_DEBUG("%s: initiator UUID = 0x%x", __func__, uuid_int);
1690     if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE)
1691       bta_av_adjust_seps_idx(p_scb,
1692                              bta_av_get_scb_handle(p_scb, AVDT_TSEP_SRC));
1693     else if (uuid_int == UUID_SERVCLASS_AUDIO_SINK)
1694       bta_av_adjust_seps_idx(p_scb,
1695                              bta_av_get_scb_handle(p_scb, AVDT_TSEP_SNK));
1696     LOG_INFO("%s: sep_idx=%d avdt_handle=%d bta_handle=0x%x", __func__,
1697              p_scb->sep_idx, p_scb->avdt_handle, p_scb->hndl);
1698 
1699     /* use only the services peer supports */
1700     cfg.psc_mask &= p_scb->peer_cap.psc_mask;
1701     p_scb->cur_psc_mask = cfg.psc_mask;
1702     APPL_TRACE_DEBUG(
1703         "%s: peer %s bta_handle:0x%x sep_idx:%d sep_info_idx:%d "
1704         "cur_psc_mask:0x%x",
1705         __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
1706         p_scb->sep_idx, p_scb->sep_info_idx, p_scb->cur_psc_mask);
1707 
1708     if ((uuid_int == UUID_SERVCLASS_AUDIO_SINK) &&
1709         (p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback != NULL)) {
1710       APPL_TRACE_DEBUG("%s: configure decoder for Sink connection", __func__);
1711       tBTA_AV_MEDIA av_sink_codec_info;
1712       av_sink_codec_info.avk_config.bd_addr = p_scb->PeerAddress();
1713       av_sink_codec_info.avk_config.codec_info = p_scb->cfg.codec_info;
1714       p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback(
1715           p_scb->PeerAddress(), BTA_AV_SINK_MEDIA_CFG_EVT, &av_sink_codec_info);
1716     }
1717 
1718     if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE) {
1719       A2DP_AdjustCodec(cfg.codec_info);
1720     }
1721 
1722     /* open the stream */
1723     AVDT_OpenReq(p_scb->seps[p_scb->sep_idx].av_handle, p_scb->PeerAddress(),
1724                  p_scb->hdi, p_scb->sep_info[p_scb->sep_info_idx].seid, &cfg);
1725   } else {
1726     /* try the next stream, if any */
1727     p_scb->sep_info_idx++;
1728     bta_av_next_getcap(p_scb, p_data);
1729   }
1730 }
1731 
1732 /*******************************************************************************
1733  *
1734  * Function         bta_av_setconfig_rej
1735  *
1736  * Description      Send AVDTP set config reject.
1737  *
1738  * Returns          void
1739  *
1740  ******************************************************************************/
bta_av_setconfig_rej(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1741 void bta_av_setconfig_rej(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1742   tBTA_AV_REJECT reject;
1743   uint8_t avdt_handle = p_data->ci_setconfig.avdt_handle;
1744 
1745   bta_av_adjust_seps_idx(p_scb, avdt_handle);
1746   LOG_INFO("%s: sep_idx=%d avdt_handle=%d bta_handle=0x%x", __func__,
1747            p_scb->sep_idx, p_scb->avdt_handle, p_scb->hndl);
1748   AVDT_ConfigRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_UNSUP_CFG, 0);
1749 
1750   reject.bd_addr = p_data->str_msg.bd_addr;
1751   reject.hndl = p_scb->hndl;
1752 
1753   tBTA_AV bta_av_data;
1754   bta_av_data.reject = reject;
1755   (*bta_av_cb.p_cback)(BTA_AV_REJECT_EVT, &bta_av_data);
1756 }
1757 
1758 /*******************************************************************************
1759  *
1760  * Function         bta_av_discover_req
1761  *
1762  * Description      Send an AVDTP discover request to the peer.
1763  *
1764  * Returns          void
1765  *
1766  ******************************************************************************/
bta_av_discover_req(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)1767 void bta_av_discover_req(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
1768   /* send avdtp discover request */
1769 
1770   AVDT_DiscoverReq(p_scb->PeerAddress(), p_scb->hdi, p_scb->sep_info,
1771                    BTA_AV_NUM_SEPS, &bta_av_proc_stream_evt);
1772 }
1773 
1774 /*******************************************************************************
1775  *
1776  * Function         bta_av_conn_failed
1777  *
1778  * Description      AVDTP connection failed.
1779  *
1780  * Returns          void
1781  *
1782  ******************************************************************************/
bta_av_conn_failed(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1783 void bta_av_conn_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1784   APPL_TRACE_ERROR("%s: peer_addr=%s open_status=%d", __func__,
1785                    p_scb->PeerAddress().ToString().c_str(), p_scb->open_status);
1786 
1787   p_scb->open_status = BTA_AV_FAIL_STREAM;
1788   bta_av_str_closed(p_scb, p_data);
1789 }
1790 
1791 /*******************************************************************************
1792  *
1793  * Function         bta_av_do_start
1794  *
1795  * Description      Start stream.
1796  *
1797  * Returns          void
1798  *
1799  ******************************************************************************/
bta_av_do_start(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1800 void bta_av_do_start(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1801   LOG_INFO(
1802       "A2dp stream start peer:%s sco_occupied:%s av_role:0x%x started:%s "
1803       "wait:0x%x",
1804       PRIVATE_ADDRESS(p_scb->PeerAddress()),
1805       logbool(bta_av_cb.sco_occupied).c_str(), p_scb->role,
1806       logbool(p_scb->started).c_str(), p_scb->wait);
1807   if (bta_av_cb.sco_occupied) {
1808     LOG_WARN("A2dp stream start failed");
1809     bta_av_start_failed(p_scb, p_data);
1810     return;
1811   }
1812 
1813   if (p_scb->started) {
1814     p_scb->role |= BTA_AV_ROLE_START_INT;
1815     if (p_scb->wait != 0) {
1816       LOG_WARN(
1817           "%s: peer %s start stream request ignored: "
1818           "already waiting: sco_occupied:%s role:0x%x started:%s wait:0x%x",
1819           __func__, p_scb->PeerAddress().ToString().c_str(),
1820           logbool(bta_av_cb.sco_occupied).c_str(), p_scb->role,
1821           logbool(p_scb->started).c_str(), p_scb->wait);
1822       return;
1823     }
1824     if (p_scb->role & BTA_AV_ROLE_SUSPEND) {
1825       notify_start_failed(p_scb);
1826     } else {
1827       if (p_data) {
1828         bta_av_set_use_latency_mode(p_scb, p_data->do_start.use_latency_mode);
1829       }
1830       bta_av_start_ok(p_scb, NULL);
1831     }
1832     return;
1833   }
1834 
1835   if ((p_scb->role & BTA_AV_ROLE_START_INT) != 0) {
1836     LOG_WARN(
1837         "%s: peer %s start stream request ignored: "
1838         "already initiated: sco_occupied:%s role:0x%x started:%s wait:0x%x",
1839         __func__, p_scb->PeerAddress().ToString().c_str(),
1840         logbool(bta_av_cb.sco_occupied).c_str(), p_scb->role,
1841         logbool(p_scb->started).c_str(), p_scb->wait);
1842     return;
1843   }
1844 
1845   p_scb->role |= BTA_AV_ROLE_START_INT;
1846   bta_sys_busy(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress());
1847   /* disallow role switch during streaming, only if we are the central role
1848    * i.e. allow role switch, if we are peripheral.
1849    * It would not hurt us, if the peer device wants us to be central
1850    * disable sniff mode unconditionally during streaming */
1851   tHCI_ROLE cur_role;
1852   if ((BTM_GetRole(p_scb->PeerAddress(), &cur_role) == BTM_SUCCESS) &&
1853       (cur_role == HCI_ROLE_CENTRAL)) {
1854     BTM_block_role_switch_and_sniff_mode_for(p_scb->PeerAddress());
1855   } else {
1856     BTM_block_sniff_mode_for(p_scb->PeerAddress());
1857   }
1858 
1859   uint16_t result = AVDT_StartReq(&p_scb->avdt_handle, 1);
1860   if (result != AVDT_SUCCESS) {
1861     LOG_ERROR("%s: AVDT_StartReq failed for peer %s result:%d", __func__,
1862               p_scb->PeerAddress().ToString().c_str(), result);
1863     bta_av_start_failed(p_scb, p_data);
1864   } else if (p_data) {
1865     bta_av_set_use_latency_mode(p_scb, p_data->do_start.use_latency_mode);
1866   }
1867   LOG_INFO(
1868       "%s: peer %s start requested: sco_occupied:%s role:0x%x "
1869       "started:%s wait:0x%x",
1870       __func__, p_scb->PeerAddress().ToString().c_str(),
1871       logbool(bta_av_cb.sco_occupied).c_str(), p_scb->role,
1872       logbool(p_scb->started).c_str(), p_scb->wait);
1873 }
1874 
1875 /*******************************************************************************
1876  *
1877  * Function         bta_av_str_stopped
1878  *
1879  * Description      Stream stopped.
1880  *
1881  * Returns          void
1882  *
1883  ******************************************************************************/
bta_av_str_stopped(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1884 void bta_av_str_stopped(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1885   tBTA_AV_SUSPEND suspend_rsp;
1886   uint8_t start = p_scb->started;
1887   bool sus_evt = true;
1888   BT_HDR* p_buf;
1889 
1890   APPL_TRACE_ERROR(
1891       "%s: peer %s bta_handle:0x%x audio_open_cnt:%d, p_data %p start:%d",
1892       __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
1893       bta_av_cb.audio_open_cnt, p_data, start);
1894 
1895   bta_sys_idle(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress());
1896   BTM_unblock_role_switch_and_sniff_mode_for(p_scb->PeerAddress());
1897 
1898   if (p_scb->co_started) {
1899     if (bta_av_cb.offload_started_hndl == p_scb->hndl) {
1900       bta_av_vendor_offload_stop();
1901       bta_av_cb.offload_started_hndl = BTA_AV_INVALID_HANDLE;
1902     } else if (bta_av_cb.offload_start_pending_hndl == p_scb->hndl) {
1903       APPL_TRACE_WARNING("%s: Stop pending offload start command", __func__);
1904       bta_av_vendor_offload_stop();
1905       bta_av_cb.offload_start_pending_hndl = BTA_AV_INVALID_HANDLE;
1906     }
1907 
1908     bta_av_stream_chg(p_scb, false);
1909     p_scb->co_started = false;
1910 
1911     p_scb->p_cos->stop(p_scb->hndl, p_scb->PeerAddress());
1912   }
1913 
1914   /* if q_info.a2dp_list is not empty, drop it now */
1915   if (BTA_AV_CHNL_AUDIO == p_scb->chnl) {
1916     while (!list_is_empty(p_scb->a2dp_list)) {
1917       p_buf = (BT_HDR*)list_front(p_scb->a2dp_list);
1918       list_remove(p_scb->a2dp_list, p_buf);
1919       osi_free(p_buf);
1920     }
1921 
1922     /* drop the audio buffers queued in L2CAP */
1923     if (p_data && p_data->api_stop.flush)
1924       L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL);
1925   }
1926 
1927   suspend_rsp.chnl = p_scb->chnl;
1928   suspend_rsp.hndl = p_scb->hndl;
1929 
1930   if (p_data && p_data->api_stop.suspend) {
1931     APPL_TRACE_DEBUG("%s: peer %s suspending: %d, sup:%d", __func__,
1932                      p_scb->PeerAddress().ToString().c_str(), start,
1933                      p_scb->suspend_sup);
1934     if ((start) && (p_scb->suspend_sup)) {
1935       sus_evt = false;
1936       p_scb->l2c_bufs = 0;
1937       AVDT_SuspendReq(&p_scb->avdt_handle, 1);
1938     }
1939 
1940     /* send SUSPEND_EVT event only if not in reconfiguring state and sus_evt is
1941      * true*/
1942     if ((sus_evt) && (p_scb->state != BTA_AV_RCFG_SST)) {
1943       suspend_rsp.status = BTA_AV_SUCCESS;
1944       suspend_rsp.initiator = true;
1945       tBTA_AV bta_av_data;
1946       bta_av_data.suspend = suspend_rsp;
1947       (*bta_av_cb.p_cback)(BTA_AV_SUSPEND_EVT, &bta_av_data);
1948     }
1949   } else {
1950     suspend_rsp.status = BTA_AV_SUCCESS;
1951     suspend_rsp.initiator = true;
1952     APPL_TRACE_EVENT("%s: status %d", __func__, suspend_rsp.status);
1953 
1954     // Send STOP_EVT event only if not in reconfiguring state.
1955     // However, we should send STOP_EVT if we are reconfiguring when taking
1956     // the Close->Configure->Open->Start path.
1957     if (p_scb->state != BTA_AV_RCFG_SST ||
1958         (p_data && p_data->api_stop.reconfig_stop)) {
1959       tBTA_AV bta_av_data;
1960       bta_av_data.suspend = suspend_rsp;
1961       (*bta_av_cb.p_cback)(BTA_AV_STOP_EVT, &bta_av_data);
1962     }
1963   }
1964 }
1965 
1966 /*******************************************************************************
1967  *
1968  * Function         bta_av_reconfig
1969  *
1970  * Description      process the reconfigure request.
1971  *                  save the parameter in control block and
1972  *                  suspend, reconfigure or close the stream
1973  *
1974  * Returns          void
1975  *
1976  ******************************************************************************/
bta_av_reconfig(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)1977 void bta_av_reconfig(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
1978   AvdtpSepConfig* p_cfg;
1979   tBTA_AV_API_STOP stop;
1980   tBTA_AV_API_RCFG* p_rcfg = &p_data->api_reconfig;
1981 
1982   APPL_TRACE_DEBUG("%s: r:%d, s:%d idx: %d (o:%d)", __func__, p_scb->recfg_sup,
1983                    p_scb->suspend_sup, p_scb->rcfg_idx, p_scb->sep_info_idx);
1984 
1985   p_scb->num_recfg = 0;
1986   /* store the new configuration in control block */
1987   p_cfg = &p_scb->cfg;
1988 
1989   alarm_cancel(p_scb->avrc_ct_timer);
1990 
1991   LOG_DEBUG("p_scb->sep_info_idx=%d p_scb->rcfg_idx=%d p_rcfg->sep_info_idx=%d",
1992             p_scb->sep_info_idx, p_scb->rcfg_idx, p_rcfg->sep_info_idx);
1993   LOG_DEBUG("Peer capable codec: %s",
1994             A2DP_CodecInfoString(p_scb->peer_cap.codec_info).c_str());
1995   LOG_DEBUG("Current codec: %s",
1996             A2DP_CodecInfoString(p_scb->cfg.codec_info).c_str());
1997   LOG_DEBUG("Reconfig codec: %s",
1998             A2DP_CodecInfoString(p_rcfg->codec_info).c_str());
1999 
2000   BTM_LogHistory(
2001       kBtmLogTag, p_scb->PeerAddress(), "Codec reconfig",
2002       base::StringPrintf("%s => %s", A2DP_CodecName(p_scb->cfg.codec_info),
2003                          A2DP_CodecName(p_rcfg->codec_info)));
2004 
2005   p_cfg->num_protect = p_rcfg->num_protect;
2006   memcpy(p_cfg->codec_info, p_rcfg->codec_info, AVDT_CODEC_SIZE);
2007   memcpy(p_cfg->protect_info, p_rcfg->p_protect_info, p_rcfg->num_protect);
2008   p_scb->rcfg_idx = p_rcfg->sep_info_idx;
2009   p_cfg->psc_mask = p_scb->cur_psc_mask;
2010 
2011   // If the requested SEP index is same as the current one, then we
2012   // can Suspend->Reconfigure->Start.
2013   // Otherwise, we have to Close->Configure->Open->Start or
2014   // Close->Configure->Open for streams that are / are not started.
2015   if ((p_scb->rcfg_idx == p_scb->sep_info_idx) && p_rcfg->suspend &&
2016       p_scb->recfg_sup && p_scb->suspend_sup) {
2017     if (p_scb->started) {
2018       // Suspend->Reconfigure->Start
2019       stop.flush = false;
2020       stop.suspend = true;
2021       stop.reconfig_stop = false;
2022       bta_av_str_stopped(p_scb, (tBTA_AV_DATA*)&stop);
2023     } else {
2024       // Reconfigure
2025       APPL_TRACE_DEBUG("%s: reconfig", __func__);
2026       APPL_TRACE_DEBUG("%s: codec: %s", __func__,
2027                        A2DP_CodecInfoString(p_scb->cfg.codec_info).c_str());
2028       AVDT_ReconfigReq(p_scb->avdt_handle, &p_scb->cfg);
2029       p_scb->cfg.psc_mask = p_scb->cur_psc_mask;
2030     }
2031   } else {
2032     // Close the stream first, and then Configure it
2033     APPL_TRACE_DEBUG("%s: Close/Open started: %d state: %d num_protect: %d",
2034                      __func__, p_scb->started, p_scb->state,
2035                      p_cfg->num_protect);
2036     if (p_scb->started) {
2037       // Close->Configure->Open->Start
2038       if ((p_scb->rcfg_idx != p_scb->sep_info_idx) && p_scb->recfg_sup) {
2039         // Make sure we trigger STOP_EVT when taking the longer road to
2040         // reconfiguration, otherwise we don't call Start.
2041         stop.flush = false;
2042         stop.suspend = false;
2043         stop.reconfig_stop = true;
2044         bta_av_str_stopped(p_scb, (tBTA_AV_DATA*)&stop);
2045       } else {
2046         bta_av_str_stopped(p_scb, NULL);
2047       }
2048       p_scb->started = false;
2049     } else {
2050       // Close->Configure->Open
2051       bta_av_str_stopped(p_scb, NULL);
2052     }
2053     // Drop the buffers queued in L2CAP
2054     L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL);
2055     AVDT_CloseReq(p_scb->avdt_handle);
2056   }
2057 }
2058 
2059 /*******************************************************************************
2060  *
2061  * Function         bta_av_data_path
2062  *
2063  * Description      Handle stream data path.
2064  *
2065  * Returns          void
2066  *
2067  ******************************************************************************/
bta_av_data_path(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)2068 void bta_av_data_path(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
2069   BT_HDR* p_buf = NULL;
2070   uint32_t timestamp;
2071   bool new_buf = false;
2072   uint8_t m_pt = 0x60;
2073   tAVDT_DATA_OPT_MASK opt;
2074 
2075   if (!p_scb->started) return;
2076 
2077   if (p_scb->cong) return;
2078 
2079   if (p_scb->use_rtp_header_marker_bit) {
2080     m_pt |= AVDT_MARKER_SET;
2081   }
2082 
2083   // Always get the current number of bufs que'd up
2084   p_scb->l2c_bufs =
2085       (uint8_t)L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_GET);
2086 
2087   if (!list_is_empty(p_scb->a2dp_list)) {
2088     p_buf = (BT_HDR*)list_front(p_scb->a2dp_list);
2089     list_remove(p_scb->a2dp_list, p_buf);
2090     /* use q_info.a2dp data, read the timestamp */
2091     timestamp = *(uint32_t*)(p_buf + 1);
2092   } else {
2093     new_buf = true;
2094     /* A2DP_list empty, call co_data, dup data to other channels */
2095     p_buf = p_scb->p_cos->data(p_scb->cfg.codec_info, &timestamp);
2096 
2097     if (p_buf) {
2098       /* use the offset area for the time stamp */
2099       *(uint32_t*)(p_buf + 1) = timestamp;
2100 
2101       /* dup the data to other channels */
2102       bta_av_dup_audio_buf(p_scb, p_buf);
2103     }
2104   }
2105 
2106   if (p_buf) {
2107     if (p_scb->l2c_bufs < (BTA_AV_QUEUE_DATA_CHK_NUM)) {
2108       /* There's a buffer, just queue it to L2CAP.
2109        * There's no need to increment it here, it is always read from
2110        * L2CAP (see above).
2111        */
2112 
2113       /* opt is a bit mask, it could have several options set */
2114       opt = AVDT_DATA_OPT_NONE;
2115       if (p_scb->no_rtp_header) {
2116         opt |= AVDT_DATA_OPT_NO_RTP;
2117       }
2118 
2119       //
2120       // Fragment the payload if larger than the MTU.
2121       // NOTE: The fragmentation is RTP-compatibie.
2122       //
2123       size_t extra_fragments_n = 0;
2124       if (p_buf->len > 0) {
2125         extra_fragments_n = (p_buf->len / p_scb->stream_mtu) +
2126                             ((p_buf->len % p_scb->stream_mtu) ? 1 : 0) - 1;
2127       }
2128       std::vector<BT_HDR*> extra_fragments;
2129       extra_fragments.reserve(extra_fragments_n);
2130 
2131       uint8_t* data_begin = (uint8_t*)(p_buf + 1) + p_buf->offset;
2132       uint8_t* data_end = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len;
2133       while (extra_fragments_n-- > 0) {
2134         data_begin += p_scb->stream_mtu;
2135         size_t fragment_len = data_end - data_begin;
2136         if (fragment_len > p_scb->stream_mtu) fragment_len = p_scb->stream_mtu;
2137 
2138         BT_HDR* p_buf2 = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE);
2139         p_buf2->offset = p_buf->offset;
2140         p_buf2->len = 0;
2141         p_buf2->layer_specific = 0;
2142         uint8_t* packet2 =
2143             (uint8_t*)(p_buf2 + 1) + p_buf2->offset + p_buf2->len;
2144         memcpy(packet2, data_begin, fragment_len);
2145         p_buf2->len += fragment_len;
2146         extra_fragments.push_back(p_buf2);
2147         p_buf->len -= fragment_len;
2148       }
2149 
2150       if (!extra_fragments.empty()) {
2151         // Reset the RTP Marker bit for all fragments except the last one
2152         m_pt &= ~AVDT_MARKER_SET;
2153       }
2154       AVDT_WriteReqOpt(p_scb->avdt_handle, p_buf, timestamp, m_pt, opt);
2155       for (size_t i = 0; i < extra_fragments.size(); i++) {
2156         if (i + 1 == extra_fragments.size()) {
2157           // Set the RTP Marker bit for the last fragment
2158           m_pt |= AVDT_MARKER_SET;
2159         }
2160         BT_HDR* p_buf2 = extra_fragments[i];
2161         AVDT_WriteReqOpt(p_scb->avdt_handle, p_buf2, timestamp, m_pt, opt);
2162       }
2163       p_scb->cong = true;
2164     } else {
2165       /* there's a buffer, but L2CAP does not seem to be moving data */
2166       if (new_buf) {
2167         /* just got this buffer from co_data,
2168          * put it in queue */
2169         list_append(p_scb->a2dp_list, p_buf);
2170       } else {
2171         /* just dequeue it from the a2dp_list */
2172         if (list_length(p_scb->a2dp_list) < 3) {
2173           /* put it back to the queue */
2174           list_prepend(p_scb->a2dp_list, p_buf);
2175         } else {
2176           /* too many buffers in a2dp_list, drop it. */
2177           bta_av_co_audio_drop(p_scb->hndl, p_scb->PeerAddress());
2178           osi_free(p_buf);
2179         }
2180       }
2181     }
2182   }
2183 }
2184 
2185 /*******************************************************************************
2186  *
2187  * Function         bta_av_start_ok
2188  *
2189  * Description      Stream started.
2190  *
2191  * Returns          void
2192  *
2193  ******************************************************************************/
bta_av_start_ok(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)2194 void bta_av_start_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
2195   bool initiator = false;
2196   bool suspend = false;
2197   uint8_t new_role = p_scb->role;
2198   BT_HDR_RIGID hdr;
2199   tHCI_ROLE cur_role;
2200   uint8_t local_tsep = p_scb->seps[p_scb->sep_idx].tsep;
2201 
2202   LOG_INFO("%s: peer %s bta_handle:0x%x wait:0x%x role:0x%x local_tsep:%d",
2203            __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
2204            p_scb->wait, p_scb->role, local_tsep);
2205 
2206   p_scb->started = true;
2207 
2208   if (local_tsep == AVDT_TSEP_SRC) {
2209     // The RTP Header marker bit for the A2DP Source encoder
2210     A2dpCodecConfig* codec_config =
2211         bta_av_get_a2dp_peer_current_codec(p_scb->PeerAddress());
2212     CHECK(codec_config != nullptr);
2213     p_scb->use_rtp_header_marker_bit = codec_config->useRtpHeaderMarkerBit();
2214   }
2215 
2216   if (p_scb->sco_suspend) {
2217     p_scb->sco_suspend = false;
2218   }
2219 
2220   if (new_role & BTA_AV_ROLE_START_INT) initiator = true;
2221 
2222   /* for A2DP SINK we do not send get_caps */
2223   if ((p_scb->avdt_handle == p_scb->seps[p_scb->sep_idx].av_handle) &&
2224       (local_tsep == AVDT_TSEP_SNK)) {
2225     p_scb->wait &= ~(BTA_AV_WAIT_ACP_CAPS_ON);
2226     APPL_TRACE_DEBUG("%s: local SEP type is SNK new wait is 0x%x", __func__,
2227                      p_scb->wait);
2228   }
2229   if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_FAILED) {
2230     /* role switch has failed */
2231     APPL_TRACE_ERROR(
2232         "%s: peer %s role switch failed: bta_handle:0x%x wait:0x%x, role:0x%x",
2233         __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
2234         p_scb->wait, p_scb->role);
2235     p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_FAILED;
2236     p_data = (tBTA_AV_DATA*)&hdr;
2237     hdr.offset = BTA_AV_RS_FAIL;
2238   }
2239   APPL_TRACE_DEBUG("%s: peer %s wait:0x%x use_rtp_header_marker_bit:%s",
2240                    __func__, p_scb->PeerAddress().ToString().c_str(),
2241                    p_scb->wait,
2242                    (p_scb->use_rtp_header_marker_bit) ? "true" : "false");
2243 
2244   if (p_data && (p_data->hdr.offset != BTA_AV_RS_NONE)) {
2245     p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS;
2246     if (p_data->hdr.offset == BTA_AV_RS_FAIL) {
2247       bta_sys_idle(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress());
2248       tBTA_AV_START start;
2249       start.chnl = p_scb->chnl;
2250       start.status = BTA_AV_FAIL_ROLE;
2251       start.hndl = p_scb->hndl;
2252       start.initiator = initiator;
2253       tBTA_AV bta_av_data;
2254       bta_av_data.start = start;
2255       (*bta_av_cb.p_cback)(BTA_AV_START_EVT, &bta_av_data);
2256       return;
2257     }
2258   }
2259 
2260   if (!bta_av_link_role_ok(p_scb, A2DP_SET_ONE_BIT))
2261     p_scb->q_tag = BTA_AV_Q_TAG_START;
2262   else {
2263     /* The wait flag may be set here while we are already central on the link */
2264     /* this could happen if a role switch complete event occurred during
2265      * reconfig */
2266     /* if we are now central on the link, there is no need to wait for the role
2267      * switch, */
2268     /* complete anymore so we can clear the wait for role switch flag */
2269     p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS;
2270   }
2271 
2272   if (p_scb->wait &
2273       (BTA_AV_WAIT_ROLE_SW_RES_OPEN | BTA_AV_WAIT_ROLE_SW_RES_START)) {
2274     p_scb->wait |= BTA_AV_WAIT_ROLE_SW_STARTED;
2275     p_scb->q_tag = BTA_AV_Q_TAG_START;
2276   }
2277 
2278   if (p_scb->wait) {
2279     APPL_TRACE_ERROR("%s: peer %s wait:0x%x q_tag:%d not started", __func__,
2280                      p_scb->PeerAddress().ToString().c_str(), p_scb->wait,
2281                      p_scb->q_tag);
2282     /* Clear first bit of p_scb->wait and not to return from this point else
2283      * HAL layer gets blocked. And if there is delay in Get Capability response
2284      * as
2285      * first bit of p_scb->wait is cleared hence it ensures bt_av_start_ok is
2286      * not called
2287      * again from bta_av_save_caps.
2288      */
2289     p_scb->wait &= ~BTA_AV_WAIT_ACP_CAPS_ON;
2290   }
2291 
2292   /* tell role manager to check M/S role */
2293   bta_sys_conn_open(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress());
2294 
2295   bta_sys_busy(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress());
2296 
2297   if (p_scb->media_type == AVDT_MEDIA_TYPE_AUDIO) {
2298     /* in normal logic, conns should be bta_av_cb.audio_count - 1,
2299      * However, bta_av_stream_chg is not called to increase
2300      * bta_av_cb.audio_count yet.
2301      * If the code were to be re-arranged for some reasons, this number may need
2302      * to be changed
2303      */
2304     p_scb->co_started = bta_av_cb.audio_open_cnt;
2305   }
2306 
2307   /* clear the congestion flag */
2308   p_scb->cong = false;
2309 
2310   if (new_role & BTA_AV_ROLE_START_INT) {
2311     new_role &= ~BTA_AV_ROLE_START_INT;
2312   } else if ((new_role & BTA_AV_ROLE_AD_ACP) &&
2313              (new_role & BTA_AV_ROLE_SUSPEND_OPT)) {
2314     suspend = true;
2315   }
2316 
2317   if (!suspend) {
2318     p_scb->q_tag = BTA_AV_Q_TAG_STREAM;
2319     bta_av_stream_chg(p_scb, true);
2320   }
2321 
2322   {
2323     /* If sink starts stream, disable sniff mode here */
2324     if (!initiator) {
2325       /* If souce is the central role, disable role switch during streaming.
2326        * Otherwise allow role switch, if source is peripheral.
2327        * Because it would not hurt source, if the peer device wants source to be
2328        * central.
2329        * disable sniff mode unconditionally during streaming */
2330       if ((BTM_GetRole(p_scb->PeerAddress(), &cur_role) == BTM_SUCCESS) &&
2331           (cur_role == HCI_ROLE_CENTRAL)) {
2332         BTM_block_role_switch_and_sniff_mode_for(p_scb->PeerAddress());
2333       } else {
2334         BTM_block_sniff_mode_for(p_scb->PeerAddress());
2335       }
2336     }
2337 
2338     p_scb->role = new_role;
2339     p_scb->role &= ~BTA_AV_ROLE_AD_ACP;
2340     p_scb->role &= ~BTA_AV_ROLE_SUSPEND_OPT;
2341 
2342     p_scb->no_rtp_header = false;
2343     p_scb->p_cos->start(p_scb->hndl, p_scb->PeerAddress(),
2344                         p_scb->cfg.codec_info, &p_scb->no_rtp_header);
2345     p_scb->co_started = true;
2346 
2347     APPL_TRACE_DEBUG("%s: peer %s suspending: %d, role:0x%x, init %d", __func__,
2348                      p_scb->PeerAddress().ToString().c_str(), suspend,
2349                      p_scb->role, initiator);
2350 
2351     tBTA_AV_START start;
2352     start.suspending = suspend;
2353     start.initiator = initiator;
2354     start.chnl = p_scb->chnl;
2355     start.status = BTA_AV_SUCCESS;
2356     start.hndl = p_scb->hndl;
2357     tBTA_AV bta_av_data;
2358     bta_av_data.start = start;
2359     (*bta_av_cb.p_cback)(BTA_AV_START_EVT, &bta_av_data);
2360 
2361     if (suspend) {
2362       tBTA_AV_API_STOP stop;
2363       p_scb->role |= BTA_AV_ROLE_SUSPEND;
2364       p_scb->cong = true; /* do not allow the media data to go through */
2365       /* do not duplicate the media packets to this channel */
2366       p_scb->p_cos->stop(p_scb->hndl, p_scb->PeerAddress());
2367       p_scb->co_started = false;
2368       stop.flush = false;
2369       stop.suspend = true;
2370       stop.reconfig_stop = false;
2371       bta_av_ssm_execute(p_scb, BTA_AV_AP_STOP_EVT, (tBTA_AV_DATA*)&stop);
2372     }
2373   }
2374 }
2375 
2376 /*******************************************************************************
2377  *
2378  * Function         bta_av_start_failed
2379  *
2380  * Description      Stream start failed.
2381  *
2382  * Returns          void
2383  *
2384  ******************************************************************************/
bta_av_start_failed(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)2385 void bta_av_start_failed(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
2386   APPL_TRACE_ERROR(
2387       "%s: peer %s bta_handle:0x%x audio_open_cnt:%d started:%s co_started:%d",
2388       __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
2389       bta_av_cb.audio_open_cnt, logbool(p_scb->started).c_str(),
2390       p_scb->co_started);
2391 
2392   if (!p_scb->started && !p_scb->co_started) {
2393     bta_sys_idle(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress());
2394     notify_start_failed(p_scb);
2395   }
2396 
2397   BTM_unblock_role_switch_and_sniff_mode_for(p_scb->PeerAddress());
2398   p_scb->sco_suspend = false;
2399 }
2400 
2401 /*******************************************************************************
2402  *
2403  * Function         bta_av_str_closed
2404  *
2405  * Description      Stream closed.
2406  *
2407  * Returns          void
2408  *
2409  ******************************************************************************/
bta_av_str_closed(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)2410 void bta_av_str_closed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
2411   tBTA_AV data;
2412   tBTA_AV_EVT event;
2413 
2414   APPL_TRACE_WARNING(
2415       "%s: peer %s bta_handle:0x%x open_status:%d chnl:%d co_started:%d",
2416       __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
2417       p_scb->open_status, p_scb->chnl, p_scb->co_started);
2418 
2419   BTM_unblock_role_switch_and_sniff_mode_for(p_scb->PeerAddress());
2420   if (bta_av_cb.audio_open_cnt <= 1) {
2421     BTM_default_unblock_role_switch();
2422   }
2423 
2424   if (p_scb->open_status != BTA_AV_SUCCESS) {
2425     /* must be failure when opening the stream */
2426     data.open.bd_addr = p_scb->PeerAddress();
2427     data.open.status = p_scb->open_status;
2428     data.open.chnl = p_scb->chnl;
2429     data.open.hndl = p_scb->hndl;
2430 
2431     if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC)
2432       data.open.sep = AVDT_TSEP_SNK;
2433     else if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SNK)
2434       data.open.sep = AVDT_TSEP_SRC;
2435 
2436     event = BTA_AV_OPEN_EVT;
2437     p_scb->open_status = BTA_AV_SUCCESS;
2438 
2439     bta_sys_conn_close(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress());
2440     bta_av_cleanup(p_scb, p_data);
2441     (*bta_av_cb.p_cback)(event, &data);
2442   } else {
2443     /* do stop if we were started */
2444     if (p_scb->co_started) {
2445       bta_av_str_stopped(p_scb, NULL);
2446     }
2447 
2448     {
2449       p_scb->p_cos->close(p_scb->hndl, p_scb->PeerAddress());
2450       data.close.chnl = p_scb->chnl;
2451       data.close.hndl = p_scb->hndl;
2452       event = BTA_AV_CLOSE_EVT;
2453 
2454       bta_sys_conn_close(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress());
2455       bta_av_cleanup(p_scb, p_data);
2456       (*bta_av_cb.p_cback)(event, &data);
2457     }
2458   }
2459 }
2460 
2461 /*******************************************************************************
2462  *
2463  * Function         bta_av_clr_cong
2464  *
2465  * Description      Clear stream congestion flag.
2466  *
2467  * Returns          void
2468  *
2469  ******************************************************************************/
bta_av_clr_cong(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)2470 void bta_av_clr_cong(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
2471   APPL_TRACE_DEBUG("%s", __func__);
2472   if (p_scb->co_started) {
2473     p_scb->cong = false;
2474   }
2475 }
2476 
2477 /*******************************************************************************
2478  *
2479  * Function         bta_av_suspend_cfm
2480  *
2481  * Description      process the suspend response
2482  *
2483  * Returns          void
2484  *
2485  ******************************************************************************/
bta_av_suspend_cfm(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)2486 void bta_av_suspend_cfm(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
2487   tBTA_AV_SUSPEND suspend_rsp;
2488   uint8_t err_code = p_data->str_msg.msg.hdr.err_code;
2489 
2490   APPL_TRACE_DEBUG("%s: peer %s bta_handle:0x%x audio_open_cnt:%d err_code:%d",
2491                    __func__, p_scb->PeerAddress().ToString().c_str(),
2492                    p_scb->hndl, bta_av_cb.audio_open_cnt, err_code);
2493 
2494   if (!p_scb->started) {
2495     /* handle the condition where there is a collision of SUSPEND req from
2496      *either side
2497      ** Second SUSPEND req could be rejected. Do not treat this as a failure
2498      */
2499     APPL_TRACE_WARNING("%s: already suspended, ignore, err_code %d", __func__,
2500                        err_code);
2501     return;
2502   }
2503 
2504   suspend_rsp.status = BTA_AV_SUCCESS;
2505   if (err_code && (err_code != AVDT_ERR_BAD_STATE)) {
2506     suspend_rsp.status = BTA_AV_FAIL;
2507 
2508     APPL_TRACE_ERROR("%s: suspend failed, closing connection", __func__);
2509 
2510     /* SUSPEND failed. Close connection. */
2511     bta_av_ssm_execute(p_scb, BTA_AV_API_CLOSE_EVT, NULL);
2512   } else {
2513     /* only set started to false when suspend is successful */
2514     p_scb->started = false;
2515   }
2516 
2517   if (p_scb->role & BTA_AV_ROLE_SUSPEND) {
2518     p_scb->role &= ~BTA_AV_ROLE_SUSPEND;
2519     p_scb->cong = false;
2520   }
2521 
2522   bta_sys_idle(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress());
2523   BTM_unblock_role_switch_and_sniff_mode_for(p_scb->PeerAddress());
2524 
2525   /* in case that we received suspend_ind, we may need to call co_stop here */
2526   if (p_scb->co_started) {
2527     if (bta_av_cb.offload_started_hndl == p_scb->hndl) {
2528       bta_av_vendor_offload_stop();
2529       bta_av_cb.offload_started_hndl = BTA_AV_INVALID_HANDLE;
2530     } else if (bta_av_cb.offload_start_pending_hndl == p_scb->hndl) {
2531       APPL_TRACE_WARNING("%s: Stop pending offload start command", __func__);
2532       bta_av_vendor_offload_stop();
2533       bta_av_cb.offload_start_pending_hndl = BTA_AV_INVALID_HANDLE;
2534     }
2535     bta_av_stream_chg(p_scb, false);
2536 
2537     {
2538       p_scb->co_started = false;
2539       p_scb->p_cos->stop(p_scb->hndl, p_scb->PeerAddress());
2540     }
2541   }
2542 
2543   {
2544     suspend_rsp.chnl = p_scb->chnl;
2545     suspend_rsp.hndl = p_scb->hndl;
2546     suspend_rsp.initiator = p_data->str_msg.initiator;
2547     tBTA_AV bta_av_data;
2548     bta_av_data.suspend = suspend_rsp;
2549     (*bta_av_cb.p_cback)(BTA_AV_SUSPEND_EVT, &bta_av_data);
2550   }
2551 }
2552 
2553 /*******************************************************************************
2554  *
2555  * Function         bta_av_rcfg_str_ok
2556  *
2557  * Description      report reconfigure successful
2558  *
2559  * Returns          void
2560  *
2561  ******************************************************************************/
bta_av_rcfg_str_ok(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)2562 void bta_av_rcfg_str_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
2563   p_scb->l2c_cid = AVDT_GetL2CapChannel(p_scb->avdt_handle);
2564   APPL_TRACE_DEBUG("%s: peer %s bta_handle:0x%x l2c_cid:%d", __func__,
2565                    p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
2566                    p_scb->l2c_cid);
2567 
2568   if (p_data != NULL) {
2569     // p_data could be NULL if the reconfig was triggered by the local device
2570     p_scb->stream_mtu =
2571         p_data->str_msg.msg.open_ind.peer_mtu - AVDT_MEDIA_HDR_SIZE;
2572     APPL_TRACE_DEBUG("%s: l2c_cid: 0x%x stream_mtu: %d", __func__,
2573                      p_scb->l2c_cid, p_scb->stream_mtu);
2574     p_scb->p_cos->update_mtu(p_scb->hndl, p_scb->PeerAddress(),
2575                              p_scb->stream_mtu);
2576   }
2577 
2578   /* rc listen */
2579   bta_av_st_rc_timer(p_scb, NULL);
2580 
2581   /* No need to keep the role bits once reconfig is done. */
2582   p_scb->role &= ~BTA_AV_ROLE_AD_ACP;
2583   p_scb->role &= ~BTA_AV_ROLE_SUSPEND_OPT;
2584   p_scb->role &= ~BTA_AV_ROLE_START_INT;
2585 
2586   {
2587     /* reconfigure success  */
2588     tBTA_AV_RECONFIG reconfig;
2589     reconfig.status = BTA_AV_SUCCESS;
2590     reconfig.chnl = p_scb->chnl;
2591     reconfig.hndl = p_scb->hndl;
2592     tBTA_AV bta_av_data;
2593     bta_av_data.reconfig = reconfig;
2594     (*bta_av_cb.p_cback)(BTA_AV_RECONFIG_EVT, &bta_av_data);
2595   }
2596 }
2597 
2598 /*******************************************************************************
2599  *
2600  * Function         bta_av_rcfg_failed
2601  *
2602  * Description      process reconfigure failed
2603  *
2604  * Returns          void
2605  *
2606  ******************************************************************************/
bta_av_rcfg_failed(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)2607 void bta_av_rcfg_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
2608   APPL_TRACE_ERROR("%s: num_recfg=%d conn_lcb=0x%x peer_addr=%s", __func__,
2609                    p_scb->num_recfg, bta_av_cb.conn_lcb,
2610                    p_scb->PeerAddress().ToString().c_str());
2611 
2612   if (p_scb->num_recfg > BTA_AV_RECONFIG_RETRY) {
2613     bta_av_cco_close(p_scb, p_data);
2614     /* report failure */
2615     tBTA_AV_RECONFIG reconfig;
2616     reconfig.status = BTA_AV_FAIL_STREAM;
2617     reconfig.chnl = p_scb->chnl;
2618     reconfig.hndl = p_scb->hndl;
2619     tBTA_AV bta_av_data;
2620     bta_av_data.reconfig = reconfig;
2621     (*bta_av_cb.p_cback)(BTA_AV_RECONFIG_EVT, &bta_av_data);
2622     /* go to closing state */
2623     bta_av_ssm_execute(p_scb, BTA_AV_API_CLOSE_EVT, NULL);
2624   } else {
2625     /* open failed. try again */
2626     p_scb->num_recfg++;
2627     // conn_lcb is the index bitmask of all used LCBs, and since LCB and SCB use
2628     // the same index, it should be safe to use SCB index here.
2629     if ((bta_av_cb.conn_lcb & (1 << p_scb->hdi)) != 0) {
2630       AVDT_DisconnectReq(p_scb->PeerAddress(), &bta_av_proc_stream_evt);
2631     } else {
2632       APPL_TRACE_WARNING("%s: conn_lcb=0x%x bta_handle=0x%x (hdi=%u) no link",
2633                          __func__, bta_av_cb.conn_lcb, p_scb->hndl, p_scb->hdi);
2634       bta_av_connect_req(p_scb, NULL);
2635     }
2636   }
2637 }
2638 
2639 /*******************************************************************************
2640  *
2641  * Function         bta_av_rcfg_connect
2642  *
2643  * Description      stream closed. reconnect the stream
2644  *
2645  * Returns          void
2646  *
2647  ******************************************************************************/
bta_av_rcfg_connect(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)2648 void bta_av_rcfg_connect(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
2649   APPL_TRACE_DEBUG("%s", __func__);
2650 
2651   p_scb->cong = false;
2652   p_scb->num_recfg++;
2653   APPL_TRACE_DEBUG("%s: num_recfg: %d", __func__, p_scb->num_recfg);
2654   if (p_scb->num_recfg > BTA_AV_RECONFIG_RETRY) {
2655     /* let bta_av_rcfg_failed report fail */
2656     bta_av_rcfg_failed(p_scb, NULL);
2657   } else {
2658     AVDT_ConnectReq(p_scb->PeerAddress(), p_scb->hdi, &bta_av_proc_stream_evt);
2659   }
2660 }
2661 
2662 /*******************************************************************************
2663  *
2664  * Function         bta_av_rcfg_discntd
2665  *
2666  * Description      AVDT disconnected. reconnect the stream
2667  *
2668  * Returns          void
2669  *
2670  ******************************************************************************/
bta_av_rcfg_discntd(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)2671 void bta_av_rcfg_discntd(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
2672   APPL_TRACE_ERROR("%s: num_recfg=%d conn_lcb=0x%x peer_addr=%s", __func__,
2673                    p_scb->num_recfg, bta_av_cb.conn_lcb,
2674                    p_scb->PeerAddress().ToString().c_str());
2675 
2676   p_scb->num_recfg++;
2677   if (p_scb->num_recfg > BTA_AV_RECONFIG_RETRY) {
2678     /* report failure */
2679     tBTA_AV_RECONFIG reconfig;
2680     reconfig.status = BTA_AV_FAIL_STREAM;
2681     reconfig.chnl = p_scb->chnl;
2682     reconfig.hndl = p_scb->hndl;
2683     tBTA_AV bta_av_data;
2684     bta_av_data.reconfig = reconfig;
2685     (*bta_av_cb.p_cback)(BTA_AV_RECONFIG_EVT, &bta_av_data);
2686     /* report close event & go to init state */
2687     bta_av_ssm_execute(p_scb, BTA_AV_STR_DISC_FAIL_EVT, NULL);
2688   } else {
2689     AVDT_ConnectReq(p_scb->PeerAddress(), p_scb->hdi, &bta_av_proc_stream_evt);
2690   }
2691 }
2692 
2693 /*******************************************************************************
2694  *
2695  * Function         bta_av_suspend_cont
2696  *
2697  * Description      received the suspend response.
2698  *                  continue to reconfigure the stream
2699  *
2700  * Returns          void
2701  *
2702  ******************************************************************************/
bta_av_suspend_cont(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)2703 void bta_av_suspend_cont(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
2704   uint8_t err_code = p_data->str_msg.msg.hdr.err_code;
2705 
2706   APPL_TRACE_DEBUG("%s: err_code=%d", __func__, err_code);
2707 
2708   p_scb->started = false;
2709   p_scb->cong = false;
2710   if (err_code) {
2711     if (AVDT_ERR_CONNECT == err_code) {
2712       /* report failure */
2713       tBTA_AV_RECONFIG reconfig;
2714       reconfig.status = BTA_AV_FAIL;
2715       tBTA_AV bta_av_data;
2716       bta_av_data.reconfig = reconfig;
2717       (*bta_av_cb.p_cback)(BTA_AV_RECONFIG_EVT, &bta_av_data);
2718       APPL_TRACE_ERROR("%s: BTA_AV_STR_DISC_FAIL_EVT: peer_addr=%s", __func__,
2719                        p_scb->PeerAddress().ToString().c_str());
2720       bta_av_ssm_execute(p_scb, BTA_AV_STR_DISC_FAIL_EVT, NULL);
2721     } else {
2722       APPL_TRACE_ERROR("%s: suspend rejected, try close", __func__);
2723       /* drop the buffers queued in L2CAP */
2724       L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL);
2725 
2726       AVDT_CloseReq(p_scb->avdt_handle);
2727     }
2728   } else {
2729     APPL_TRACE_DEBUG("%s: calling AVDT_ReconfigReq", __func__);
2730     /* reconfig the stream */
2731 
2732     APPL_TRACE_DEBUG("%s: codec: %s", __func__,
2733                      A2DP_CodecInfoString(p_scb->cfg.codec_info).c_str());
2734     AVDT_ReconfigReq(p_scb->avdt_handle, &p_scb->cfg);
2735     p_scb->cfg.psc_mask = p_scb->cur_psc_mask;
2736   }
2737 }
2738 
2739 /*******************************************************************************
2740  *
2741  * Function         bta_av_rcfg_cfm
2742  *
2743  * Description      if reconfigure is successful, report the event
2744  *                  otherwise, close the stream.
2745  *
2746  * Returns          void
2747  *
2748  ******************************************************************************/
bta_av_rcfg_cfm(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)2749 void bta_av_rcfg_cfm(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
2750   uint8_t err_code = p_data->str_msg.msg.hdr.err_code;
2751 
2752   APPL_TRACE_DEBUG("%s: err_code = %d", __func__, err_code);
2753 
2754   // Disable AVDTP RECONFIGURE for rejectlisted devices
2755   bool disable_avdtp_reconfigure = false;
2756   {
2757     char remote_name[BTM_MAX_REM_BD_NAME_LEN] = "";
2758     if (btif_storage_get_stored_remote_name(p_scb->PeerAddress(),
2759                                             remote_name)) {
2760       if (interop_match_name(INTEROP_DISABLE_AVDTP_RECONFIGURE, remote_name) ||
2761           interop_match_addr(INTEROP_DISABLE_AVDTP_RECONFIGURE,
2762                              (const RawAddress*)&p_scb->PeerAddress())) {
2763         LOG_INFO(
2764             "%s: disable AVDTP RECONFIGURE: interop matched "
2765             "name %s address %s",
2766             __func__, remote_name, p_scb->PeerAddress().ToString().c_str());
2767         disable_avdtp_reconfigure = true;
2768       }
2769     }
2770   }
2771 
2772   if ((err_code != 0) || disable_avdtp_reconfigure) {
2773     APPL_TRACE_ERROR("%s: reconfig rejected, try close", __func__);
2774     /* Disable reconfiguration feature only with explicit rejection(not with
2775      * timeout) */
2776     if ((err_code != AVDT_ERR_TIMEOUT) || disable_avdtp_reconfigure) {
2777       p_scb->recfg_sup = false;
2778     }
2779     /* started flag is false when reconfigure command is sent */
2780     /* drop the buffers queued in L2CAP */
2781     L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL);
2782     AVDT_CloseReq(p_scb->avdt_handle);
2783   } else {
2784     /* update the codec info after rcfg cfm */
2785     APPL_TRACE_DEBUG(
2786         "%s: updating from codec %s to codec %s", __func__,
2787         A2DP_CodecName(p_scb->cfg.codec_info),
2788         A2DP_CodecName(p_data->str_msg.msg.reconfig_cfm.p_cfg->codec_info));
2789     memcpy(p_scb->cfg.codec_info,
2790            p_data->str_msg.msg.reconfig_cfm.p_cfg->codec_info, AVDT_CODEC_SIZE);
2791     /* take the SSM back to OPEN state */
2792     bta_av_ssm_execute(p_scb, BTA_AV_STR_OPEN_OK_EVT, NULL);
2793   }
2794 }
2795 
2796 /*******************************************************************************
2797  *
2798  * Function         bta_av_rcfg_open
2799  *
2800  * Description      AVDT is connected. open the stream with the new
2801  *                  configuration
2802  *
2803  * Returns          void
2804  *
2805  ******************************************************************************/
bta_av_rcfg_open(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)2806 void bta_av_rcfg_open(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
2807   APPL_TRACE_DEBUG("%s: peer %s bta_handle:0x%x num_disc_snks:%d", __func__,
2808                    p_scb->PeerAddress().ToString().c_str(), p_scb->hndl,
2809                    p_scb->num_disc_snks);
2810 
2811   if (p_scb->num_disc_snks == 0) {
2812     /* Need to update call-out module so that it will be ready for discover */
2813     p_scb->p_cos->stop(p_scb->hndl, p_scb->PeerAddress());
2814 
2815     /* send avdtp discover request */
2816     AVDT_DiscoverReq(p_scb->PeerAddress(), p_scb->hdi, p_scb->sep_info,
2817                      BTA_AV_NUM_SEPS, &bta_av_proc_stream_evt);
2818   } else {
2819     APPL_TRACE_DEBUG("%s: calling AVDT_OpenReq()", __func__);
2820     APPL_TRACE_DEBUG("%s: codec: %s", __func__,
2821                      A2DP_CodecInfoString(p_scb->cfg.codec_info).c_str());
2822 
2823     /* we may choose to use a different SEP at reconfig.
2824      * adjust the sep_idx now */
2825     bta_av_adjust_seps_idx(p_scb, bta_av_get_scb_handle(p_scb, AVDT_TSEP_SRC));
2826     LOG_INFO("%s: sep_idx=%d avdt_handle=%d bta_handle=0x%x", __func__,
2827              p_scb->sep_idx, p_scb->avdt_handle, p_scb->hndl);
2828 
2829     /* open the stream with the new config */
2830     p_scb->sep_info_idx = p_scb->rcfg_idx;
2831     AVDT_OpenReq(p_scb->avdt_handle, p_scb->PeerAddress(), p_scb->hdi,
2832                  p_scb->sep_info[p_scb->sep_info_idx].seid, &p_scb->cfg);
2833   }
2834 }
2835 
2836 /*******************************************************************************
2837  *
2838  * Function         bta_av_security_rej
2839  *
2840  * Description      Send an AVDTP security reject.
2841  *
2842  * Returns          void
2843  *
2844  ******************************************************************************/
bta_av_security_rej(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)2845 void bta_av_security_rej(tBTA_AV_SCB* p_scb, UNUSED_ATTR tBTA_AV_DATA* p_data) {
2846   AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_BAD_STATE,
2847                    NULL, 0);
2848 }
2849 
2850 /*******************************************************************************
2851  *
2852  * Function         bta_av_chk_2nd_start
2853  *
2854  * Description      check if this is 2nd stream and if it needs to be started.
2855  *                  This function needs to be kept very similar to
2856  *                  bta_av_chk_start
2857  *
2858  * Returns          void
2859  *
2860  ******************************************************************************/
bta_av_chk_2nd_start(tBTA_AV_SCB * p_scb,UNUSED_ATTR tBTA_AV_DATA * p_data)2861 void bta_av_chk_2nd_start(tBTA_AV_SCB* p_scb,
2862                           UNUSED_ATTR tBTA_AV_DATA* p_data) {
2863   LOG_INFO(
2864       "%s: peer %s channel:%d bta_av_cb.audio_open_cnt:%d role:0x%x "
2865       "features:0x%x",
2866       __func__, p_scb->PeerAddress().ToString().c_str(), p_scb->chnl,
2867       bta_av_cb.audio_open_cnt, p_scb->role, bta_av_cb.features);
2868 
2869   if ((p_scb->chnl == BTA_AV_CHNL_AUDIO) && (bta_av_cb.audio_open_cnt >= 2) &&
2870       (((p_scb->role & BTA_AV_ROLE_AD_ACP) == 0) ||  // Outgoing connection or
2871        (bta_av_cb.features & BTA_AV_FEAT_ACP_START))) {  // Auto-starting option
2872     // More than one audio channel is connected.
2873     if (!(p_scb->role & BTA_AV_ROLE_SUSPEND_OPT)) {
2874       // This channel does not need to be reconfigured.
2875       // If there is other channel streaming, start the stream now.
2876       bool new_started = false;
2877       for (int i = 0; i < BTA_AV_NUM_STRS; i++) {
2878         tBTA_AV_SCB* p_scbi = bta_av_cb.p_scb[i];
2879         if (p_scb == p_scbi) {
2880           continue;
2881         }
2882         if (p_scbi && p_scbi->chnl == BTA_AV_CHNL_AUDIO && p_scbi->co_started) {
2883           if (!new_started) {
2884             // Start the new stream
2885             new_started = true;
2886             LOG_INFO(
2887                 "%s: starting new stream for peer %s because peer %s "
2888                 "already started",
2889                 __func__, p_scb->PeerAddress().ToString().c_str(),
2890                 p_scbi->PeerAddress().ToString().c_str());
2891             bta_av_ssm_execute(p_scb, BTA_AV_AP_START_EVT, NULL);
2892           }
2893           // May need to update the flush timeout of this already started stream
2894           if (p_scbi->co_started != bta_av_cb.audio_open_cnt) {
2895             p_scbi->co_started = bta_av_cb.audio_open_cnt;
2896           }
2897         }
2898       }
2899     }
2900   }
2901 }
2902 
2903 /*******************************************************************************
2904  *
2905  * Function         bta_av_open_rc
2906  *
2907  * Description      Send a message to main SM to open RC channel.
2908  *
2909  * Returns          void
2910  *
2911  ******************************************************************************/
bta_av_open_rc(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)2912 void bta_av_open_rc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
2913   APPL_TRACE_DEBUG("%s: use_rc: %d, wait: 0x%x role: 0x%x", __func__,
2914                    p_scb->use_rc, p_scb->wait, p_scb->role);
2915   if ((p_scb->wait & BTA_AV_WAIT_ROLE_SW_BITS) &&
2916       (p_scb->q_tag == BTA_AV_Q_TAG_START)) {
2917     /* waiting for role switch for some reason & the timer expires */
2918     if (!bta_av_link_role_ok(p_scb, A2DP_SET_ONE_BIT)) {
2919       APPL_TRACE_ERROR(
2920           "%s: failed to start streaming for role management reasons!!",
2921           __func__);
2922       alarm_cancel(p_scb->avrc_ct_timer);
2923 
2924       tBTA_AV_START start;
2925       start.chnl = p_scb->chnl;
2926       start.status = BTA_AV_FAIL_ROLE;
2927       start.initiator = true;
2928       start.hndl = p_scb->hndl;
2929       p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS;
2930       bta_av_cb.rs_idx = 0;
2931       tBTA_AV bta_av_data;
2932       bta_av_data.start = start;
2933       (*bta_av_cb.p_cback)(BTA_AV_START_EVT, &bta_av_data);
2934     } else {
2935       /* role switch is done. continue to start streaming */
2936       bta_av_cb.rs_idx = 0;
2937       p_data->hdr.offset = BTA_AV_RS_OK;
2938       bta_av_start_ok(p_scb, p_data);
2939     }
2940     return;
2941   }
2942 
2943   if (p_scb->use_rc || (p_scb->role & BTA_AV_ROLE_AD_ACP)) {
2944     if (bta_av_cb.disc) {
2945       /* AVRC discover db is in use */
2946       if (p_scb->rc_handle == BTA_AV_RC_HANDLE_NONE) {
2947         /* AVRC channel is not connected. delay a little bit */
2948         if ((p_scb->wait & BTA_AV_WAIT_ROLE_SW_BITS) == 0) {
2949           bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_RC_DISC_TIME_VAL,
2950                               BTA_AV_AVRC_TIMER_EVT, p_scb->hndl);
2951         } else {
2952           p_scb->wait |= BTA_AV_WAIT_CHECK_RC;
2953         }
2954       }
2955     } else {
2956       /* use main SM for AVRC SDP activities */
2957       if (is_new_avrcp_enabled()) {
2958         APPL_TRACE_WARNING("%s: Using the new AVRCP Profile", __func__);
2959         bluetooth::avrcp::AvrcpService::Get()->ConnectDevice(
2960             p_scb->PeerAddress());
2961       } else {
2962         bta_av_rc_disc((uint8_t)(p_scb->hdi + 1));
2963       }
2964     }
2965   } else {
2966     if (BTA_AV_RC_HANDLE_NONE != p_scb->rc_handle) {
2967       /* the open API said that this handle does not want a RC connection.
2968        * disconnect it now */
2969       AVRC_Close(p_scb->rc_handle);
2970     }
2971   }
2972 }
2973 
2974 /*******************************************************************************
2975  *
2976  * Function         bta_av_open_at_inc
2977  *
2978  * Description      This function is called if API open is called by application
2979  *                  while state-machine is at incoming state.
2980  *
2981  * Returns          void
2982  *
2983  ******************************************************************************/
bta_av_open_at_inc(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)2984 void bta_av_open_at_inc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
2985   memcpy(&(p_scb->open_api), &(p_data->api_open), sizeof(tBTA_AV_API_OPEN));
2986 
2987   APPL_TRACE_DEBUG("%s: peer %s coll_mask=0x%02x", __func__,
2988                    p_scb->PeerAddress().ToString().c_str(), p_scb->coll_mask);
2989 
2990   if (p_scb->coll_mask & BTA_AV_COLL_INC_TMR) {
2991     p_scb->coll_mask |= BTA_AV_COLL_API_CALLED;
2992 
2993     /* API open will be handled at timeout if SNK did not start signalling. */
2994     /* API open will be ignored if SNK starts signalling.                   */
2995   } else {
2996     /* SNK did not start signalling, API was called N seconds timeout. */
2997     /* We need to switch to INIT state and start opening connection. */
2998     p_scb->coll_mask = 0;
2999     bta_av_set_scb_sst_init(p_scb);
3000 
3001     tBTA_AV_API_OPEN* p_buf =
3002         (tBTA_AV_API_OPEN*)osi_malloc(sizeof(tBTA_AV_API_OPEN));
3003     memcpy(p_buf, &(p_scb->open_api), sizeof(tBTA_AV_API_OPEN));
3004     bta_sys_sendmsg(p_buf);
3005   }
3006 }
3007 
offload_vendor_callback(tBTM_VSC_CMPL * param)3008 void offload_vendor_callback(tBTM_VSC_CMPL* param) {
3009   tBTA_AV value{0};
3010   uint8_t sub_opcode = 0;
3011   if (param->param_len) {
3012     APPL_TRACE_DEBUG("%s: param_len = %d status = %d", __func__,
3013                      param->param_len, param->p_param_buf[0]);
3014     value.status = static_cast<tBTA_AV_STATUS>(param->p_param_buf[0]);
3015   }
3016   if (value.status == 0) {
3017     sub_opcode = param->p_param_buf[1];
3018     APPL_TRACE_DEBUG("%s: subopcode = %d", __func__, sub_opcode);
3019     switch (sub_opcode) {
3020       case VS_HCI_A2DP_OFFLOAD_STOP:
3021         APPL_TRACE_DEBUG("%s: VS_HCI_STOP_A2DP_MEDIA successful", __func__);
3022         break;
3023       case VS_HCI_A2DP_OFFLOAD_START:
3024         if (bta_av_cb.offload_start_pending_hndl) {
3025           APPL_TRACE_DEBUG("%s: VS_HCI_START_A2DP_MEDIA successful", __func__);
3026           bta_av_cb.offload_started_hndl = bta_av_cb.offload_start_pending_hndl;
3027           bta_av_cb.offload_start_pending_hndl = BTA_AV_INVALID_HANDLE;
3028         } else {
3029           LOG_INFO("%s: No pending start command due to AVDTP suspend immediately", __func__);
3030         }
3031         (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &value);
3032         break;
3033       default:
3034         break;
3035     }
3036   } else {
3037     APPL_TRACE_DEBUG("%s: Offload failed for subopcode= %d", __func__,
3038                      sub_opcode);
3039     if (param->opcode != VS_HCI_A2DP_OFFLOAD_STOP) {
3040       bta_av_cb.offload_start_pending_hndl = BTA_AV_INVALID_HANDLE;
3041       (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &value);
3042     }
3043   }
3044 }
3045 
bta_av_vendor_offload_start(tBTA_AV_SCB * p_scb,tBT_A2DP_OFFLOAD * offload_start)3046 void bta_av_vendor_offload_start(tBTA_AV_SCB* p_scb,
3047                                  tBT_A2DP_OFFLOAD* offload_start) {
3048   uint8_t param[sizeof(tBT_A2DP_OFFLOAD)];
3049   APPL_TRACE_DEBUG("%s", __func__);
3050 
3051   uint8_t* p_param = param;
3052   *p_param++ = VS_HCI_A2DP_OFFLOAD_START;
3053 
3054   UINT32_TO_STREAM(p_param, offload_start->codec_type);
3055   UINT16_TO_STREAM(p_param, offload_start->max_latency);
3056   ARRAY_TO_STREAM(p_param, offload_start->scms_t_enable,
3057                   static_cast<int>(offload_start->scms_t_enable.size()));
3058   UINT32_TO_STREAM(p_param, offload_start->sample_rate);
3059   UINT8_TO_STREAM(p_param, offload_start->bits_per_sample);
3060   UINT8_TO_STREAM(p_param, offload_start->ch_mode);
3061   UINT32_TO_STREAM(p_param, offload_start->encoded_audio_bitrate);
3062   UINT16_TO_STREAM(p_param, offload_start->acl_hdl);
3063   UINT16_TO_STREAM(p_param, offload_start->l2c_rcid);
3064   UINT16_TO_STREAM(p_param, offload_start->mtu);
3065   ARRAY_TO_STREAM(p_param, offload_start->codec_info,
3066                   (int8_t)sizeof(offload_start->codec_info));
3067   bta_av_cb.offload_start_pending_hndl = p_scb->hndl;
3068   LOG_INFO(
3069       "codec: %#x, sample rate: %#x, bit depth: %#x, channel: %#x, bitrate: "
3070       "%#x, ACL: %#x, L2CAP: %#x, MTU: %#x",
3071       offload_start->codec_type, offload_start->sample_rate,
3072       offload_start->bits_per_sample, offload_start->ch_mode,
3073       offload_start->encoded_audio_bitrate, offload_start->acl_hdl,
3074       offload_start->l2c_rcid, offload_start->mtu);
3075   BTM_VendorSpecificCommand(HCI_CONTROLLER_A2DP, p_param - param,
3076                             param, offload_vendor_callback);
3077 }
3078 
bta_av_vendor_offload_stop()3079 void bta_av_vendor_offload_stop() {
3080   uint8_t param[sizeof(tBT_A2DP_OFFLOAD)];
3081   APPL_TRACE_DEBUG("%s", __func__);
3082   param[0] = VS_HCI_A2DP_OFFLOAD_STOP;
3083   BTM_VendorSpecificCommand(HCI_CONTROLLER_A2DP, 1, param,
3084                             offload_vendor_callback);
3085 }
3086 /*******************************************************************************
3087  *
3088  * Function         bta_av_offload_req
3089  *
3090  * Description      This function is called if application requests offload of
3091  *                  a2dp audio.
3092  *
3093  * Returns          void
3094  *
3095  ******************************************************************************/
bta_av_offload_req(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)3096 void bta_av_offload_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
3097   tBTA_AV_STATUS status = BTA_AV_FAIL_RESOURCES;
3098 
3099   tBT_A2DP_OFFLOAD offload_start;
3100   APPL_TRACE_DEBUG("%s: stream %s, audio channels open %d", __func__,
3101                    p_scb->started ? "STARTED" : "STOPPED",
3102                    bta_av_cb.audio_open_cnt);
3103   /* Check if stream has already been started. */
3104   /* Support offload if only one audio source stream is open. */
3105   if (p_scb->started != true) {
3106     status = BTA_AV_FAIL_STREAM;
3107   } else if (bta_av_cb.offload_start_pending_hndl ||
3108              bta_av_cb.offload_started_hndl) {
3109     APPL_TRACE_WARNING("%s: offload already started, ignore request", __func__);
3110     return;
3111   } else {
3112     bta_av_offload_codec_builder(p_scb, &offload_start);
3113     bta_av_vendor_offload_start(p_scb, &offload_start);
3114     return;
3115   }
3116   if (status != BTA_AV_SUCCESS) {
3117     tBTA_AV bta_av_data;
3118     bta_av_data.status = status;
3119     (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &bta_av_data);
3120   }
3121   /* TODO(eisenbach): RE-IMPLEMENT USING VSC OR HAL EXTENSION
3122   else if (bta_av_cb.audio_open_cnt == 1 &&
3123              p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC &&
3124              p_scb->chnl == BTA_AV_CHNL_AUDIO) {
3125     bt_vendor_op_a2dp_offload_t a2dp_offload_start;
3126 
3127     if (L2CA_GetConnectionConfig(
3128             p_scb->l2c_cid, &a2dp_offload_start.acl_data_size,
3129             &a2dp_offload_start.remote_cid, &a2dp_offload_start.lm_handle)) {
3130       APPL_TRACE_DEBUG("%s: l2cmtu %d lcid 0x%02X rcid 0x%02X lm_handle
3131   0x%02X",
3132                       __func__, a2dp_offload_start.acl_data_size,
3133                        p_scb->l2c_cid, a2dp_offload_start.remote_cid,
3134                        a2dp_offload_start.lm_handle);
3135 
3136       a2dp_offload_start.bta_av_handle = p_scb->hndl;
3137       a2dp_offload_start.xmit_quota = BTA_AV_A2DP_OFFLOAD_XMIT_QUOTA;
3138       a2dp_offload_start.stream_mtu = p_scb->stream_mtu;
3139       a2dp_offload_start.local_cid = p_scb->l2c_cid;
3140       a2dp_offload_start.is_flushable = true;
3141       a2dp_offload_start.stream_source =
3142           ((uint32_t)(p_scb->cfg.codec_info[1] | p_scb->cfg.codec_info[2]));
3143 
3144       memcpy(a2dp_offload_start.codec_info, p_scb->cfg.codec_info,
3145              sizeof(a2dp_offload_start.codec_info));
3146 
3147       if (!vendor_get_interface()->send_command(
3148               (vendor_opcode_t)BT_VND_OP_A2DP_OFFLOAD_START,
3149               &a2dp_offload_start)) {
3150         status = BTA_AV_SUCCESS;
3151         p_scb->offload_start_pending = true;
3152       }
3153     }
3154   }
3155  */
3156 }
3157 
3158 /*******************************************************************************
3159  *
3160  * Function         bta_av_offload_rsp
3161  *
3162  * Description      This function is called when the vendor lib responds to
3163  *                  BT_VND_OP_A2DP_OFFLOAD_START.
3164  *
3165  * Returns          void
3166  *
3167  ******************************************************************************/
bta_av_offload_rsp(tBTA_AV_SCB * p_scb,tBTA_AV_DATA * p_data)3168 void bta_av_offload_rsp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) {
3169   tBTA_AV_STATUS status = p_data->api_status_rsp.status;
3170 
3171   APPL_TRACE_DEBUG("%s: stream %s status %s", __func__,
3172                    p_scb->started ? "STARTED" : "STOPPED",
3173                    status ? "FAIL" : "SUCCESS");
3174 
3175   /* Check if stream has already been started. */
3176   if (status == BTA_AV_SUCCESS && p_scb->started != true) {
3177     status = BTA_AV_FAIL_STREAM;
3178   }
3179 
3180   bta_av_cb.offload_start_pending_hndl = BTA_AV_INVALID_HANDLE;
3181   tBTA_AV bta_av_data;
3182   bta_av_data.status = status;
3183   (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &bta_av_data);
3184 }
3185 
bta_av_offload_codec_builder(tBTA_AV_SCB * p_scb,tBT_A2DP_OFFLOAD * p_a2dp_offload)3186 static void bta_av_offload_codec_builder(tBTA_AV_SCB* p_scb,
3187                                          tBT_A2DP_OFFLOAD* p_a2dp_offload) {
3188   A2dpCodecConfig* CodecConfig = bta_av_get_a2dp_current_codec();
3189   btav_a2dp_codec_index_t codec_index =
3190       A2DP_SourceCodecIndex(p_scb->cfg.codec_info);
3191   uint32_t codec_type = 0;
3192   uint16_t mtu = p_scb->stream_mtu;
3193   APPL_TRACE_DEBUG("%s:codec_index = %d", __func__, codec_index);
3194   switch (codec_index) {
3195     case BTAV_A2DP_CODEC_INDEX_SOURCE_SBC:
3196       codec_type = BTA_AV_CODEC_TYPE_SBC;
3197       if (A2DP_GetMaxBitpoolSbc(p_scb->cfg.codec_info) <=
3198           A2DP_SBC_BITPOOL_MIDDLE_QUALITY) {
3199         APPL_TRACE_WARNING("%s: Restricting streaming MTU size for MQ Bitpool",
3200                            __func__);
3201         mtu = MAX_2MBPS_AVDTP_MTU;
3202       }
3203       break;
3204     case BTAV_A2DP_CODEC_INDEX_SOURCE_AAC:
3205       codec_type = BTA_AV_CODEC_TYPE_AAC;
3206       break;
3207     case BTAV_A2DP_CODEC_INDEX_SOURCE_APTX:
3208       codec_type = BTA_AV_CODEC_TYPE_APTX;
3209       break;
3210     case BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD:
3211       codec_type = BTA_AV_CODEC_TYPE_APTXHD;
3212       break;
3213     case BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC:
3214       codec_type = BTA_AV_CODEC_TYPE_LDAC;
3215       break;
3216     case BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS:
3217       codec_type = BTA_AV_CODEC_TYPE_OPUS;
3218       break;
3219     default:
3220       APPL_TRACE_ERROR("%s: Unknown Codec type ", __func__);
3221       return;
3222   }
3223   if (mtu > MAX_3MBPS_AVDTP_MTU) mtu = MAX_3MBPS_AVDTP_MTU;
3224   p_a2dp_offload->codec_type = codec_type;
3225   p_a2dp_offload->max_latency = 0;
3226   p_a2dp_offload->mtu = mtu;
3227   p_a2dp_offload->acl_hdl =
3228       get_btm_client_interface().lifecycle.BTM_GetHCIConnHandle(
3229           p_scb->PeerAddress(), BT_TRANSPORT_BR_EDR);
3230   btav_a2dp_scmst_info_t scmst_info =
3231       p_scb->p_cos->get_scmst_info(p_scb->PeerAddress());
3232   p_a2dp_offload->scms_t_enable[0] = scmst_info.enable_status;
3233   p_a2dp_offload->scms_t_enable[1] = scmst_info.cp_header;
3234   APPL_TRACE_DEBUG(
3235       "%s: SCMS-T_enable status: %d, "
3236       "SCMS-T header (if it's enabled): 0x%02x",
3237       __func__, scmst_info.enable_status, scmst_info.cp_header);
3238 
3239   switch (A2DP_GetTrackSampleRate(p_scb->cfg.codec_info)) {
3240     case 44100:
3241       p_a2dp_offload->sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_44100;
3242       break;
3243     case 48000:
3244       p_a2dp_offload->sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
3245       break;
3246     case 88200:
3247       p_a2dp_offload->sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_88200;
3248       break;
3249     case 96000:
3250       p_a2dp_offload->sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_96000;
3251       break;
3252   }
3253   if (L2CA_GetRemoteCid(p_scb->l2c_cid, &p_a2dp_offload->l2c_rcid) == false) {
3254     APPL_TRACE_ERROR("%s: Failed to fetch l2c rcid", __func__);
3255     return;
3256   }
3257   switch (CodecConfig->getAudioBitsPerSample()) {
3258     case 16:
3259       p_a2dp_offload->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16;
3260       break;
3261     case 24:
3262       p_a2dp_offload->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24;
3263       break;
3264     case 32:
3265       p_a2dp_offload->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32;
3266       break;
3267   }
3268   p_a2dp_offload->ch_mode = A2DP_GetTrackChannelCount(p_scb->cfg.codec_info);
3269   p_a2dp_offload->encoded_audio_bitrate = CodecConfig->getTrackBitRate();
3270   if (!CodecConfig->getCodecSpecificConfig(p_a2dp_offload)) {
3271     APPL_TRACE_ERROR("%s: not a valid codec info", __func__);
3272   }
3273 }
3274