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