OSDN Git Service

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