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