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