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