OSDN Git Service

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