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