1 /******************************************************************************
2  *
3  *  Copyright 2004-2016 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 main state
22  *  machine.
23  *
24  ******************************************************************************/
25 
26 #define LOG_TAG "bluetooth-a2dp"
27 
28 #include <bluetooth/log.h>
29 
30 #include <cstdint>
31 
32 #include "bta/av/bta_av_int.h"
33 #include "bta/include/bta_ar_api.h"
34 #include "bta/include/utl.h"
35 #include "btif/avrcp/avrcp_service.h"
36 #include "device/include/device_iot_config.h"
37 #include "device/include/interop.h"
38 #include "internal_include/bt_target.h"
39 #include "osi/include/allocator.h"
40 #include "osi/include/osi.h"  // UINT_TO_PTR PTR_TO_UINT
41 #include "osi/include/properties.h"
42 #include "stack/include/acl_api.h"
43 #include "stack/include/bt_hdr.h"
44 #include "stack/include/bt_types.h"
45 #include "stack/include/bt_uuid16.h"
46 #include "stack/include/l2c_api.h"
47 #include "stack/include/sdp_api.h"
48 #include "types/raw_address.h"
49 
50 using namespace bluetooth::legacy::stack::sdp;
51 using namespace bluetooth;
52 
53 /*****************************************************************************
54  *  Constants
55  ****************************************************************************/
56 /* the timeout to wait for open req after setconfig for incoming connections */
57 #ifndef BTA_AV_SIGNALLING_TIMEOUT_MS
58 #define BTA_AV_SIGNALLING_TIMEOUT_MS (8 * 1000) /* 8 seconds */
59 #endif
60 
61 /* Time to wait for signalling from SNK when it is initiated from SNK. */
62 /* If not, we will start signalling from SRC. */
63 #ifndef BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS
64 #define BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS (2 * 1000) /* 2 seconds */
65 #endif
66 
67 static void bta_av_accept_signalling_timer_cback(void* data);
68 
69 #ifndef AVRC_MIN_META_CMD_LEN
70 #define AVRC_MIN_META_CMD_LEN 20
71 #endif
72 
73 extern bool btif_av_is_source_enabled(void);
74 extern bool btif_av_both_enable(void);
75 extern bool btif_av_src_sink_coexist_enabled(void);
76 extern bool btif_av_is_sink_enabled(void);
77 extern bool btif_av_peer_is_connected_sink(const RawAddress& peer_address);
78 extern const RawAddress& btif_av_find_by_handle(tBTA_AV_HNDL bta_handle);
79 
80 /*******************************************************************************
81  *
82  * Function         bta_av_get_rcb_by_shdl
83  *
84  * Description      find the RCB associated with the given SCB handle.
85  *
86  * Returns          tBTA_AV_RCB
87  *
88  ******************************************************************************/
bta_av_get_rcb_by_shdl(uint8_t shdl)89 tBTA_AV_RCB* bta_av_get_rcb_by_shdl(uint8_t shdl) {
90   tBTA_AV_RCB* p_rcb = NULL;
91   int i;
92 
93   for (i = 0; i < BTA_AV_NUM_RCB; i++) {
94     if (bta_av_cb.rcb[i].shdl == shdl &&
95         bta_av_cb.rcb[i].handle != BTA_AV_RC_HANDLE_NONE) {
96       p_rcb = &bta_av_cb.rcb[i];
97       break;
98     }
99   }
100   return p_rcb;
101 }
102 #define BTA_AV_STS_NO_RSP 0xFF /* a number not used by tAVRC_STS */
103 
104 /*******************************************************************************
105  *
106  * Function         bta_av_del_rc
107  *
108  * Description      delete the given AVRC handle.
109  *
110  * Returns          void
111  *
112  ******************************************************************************/
bta_av_del_rc(tBTA_AV_RCB * p_rcb)113 void bta_av_del_rc(tBTA_AV_RCB* p_rcb) {
114   tBTA_AV_SCB* p_scb;
115   uint8_t rc_handle; /* connected AVRCP handle */
116 
117   p_scb = NULL;
118   if (p_rcb->handle != BTA_AV_RC_HANDLE_NONE) {
119     if (p_rcb->shdl) {
120       /* Validate array index*/
121       if ((p_rcb->shdl - 1) < BTA_AV_NUM_STRS) {
122         p_scb = bta_av_cb.p_scb[p_rcb->shdl - 1];
123       }
124       if (p_scb) {
125         log::verbose("shdl:{}, srch:{} rc_handle:{}", p_rcb->shdl,
126                      p_scb->rc_handle, p_rcb->handle);
127         if (p_scb->rc_handle == p_rcb->handle)
128           p_scb->rc_handle = BTA_AV_RC_HANDLE_NONE;
129         /* just in case the RC timer is active
130         if (bta_av_cb.features & BTA_AV_FEAT_RCCT && p_scb->chnl ==
131         BTA_AV_CHNL_AUDIO) */
132         alarm_cancel(p_scb->avrc_ct_timer);
133       }
134     }
135 
136     log::verbose("handle: {} status=0x{:x}, rc_acp_handle:{}, idx:{}",
137                  p_rcb->handle, p_rcb->status, bta_av_cb.rc_acp_handle,
138                  bta_av_cb.rc_acp_idx);
139     rc_handle = p_rcb->handle;
140     if (!(p_rcb->status & BTA_AV_RC_CONN_MASK) ||
141         ((p_rcb->status & BTA_AV_RC_ROLE_MASK) == BTA_AV_RC_ROLE_INT)) {
142       p_rcb->status = 0;
143       p_rcb->handle = BTA_AV_RC_HANDLE_NONE;
144       p_rcb->shdl = 0;
145       p_rcb->lidx = 0;
146     }
147     /* else ACP && connected. do not clear the handle yet */
148     AVRC_Close(rc_handle);
149     if (rc_handle == bta_av_cb.rc_acp_handle)
150       bta_av_cb.rc_acp_handle = BTA_AV_RC_HANDLE_NONE;
151     log::verbose(
152         "end del_rc handle: {} status=0x{:x}, rc_acp_handle:{}, lidx:{}",
153         p_rcb->handle, p_rcb->status, bta_av_cb.rc_acp_handle, p_rcb->lidx);
154   }
155 }
156 
157 /*******************************************************************************
158  *
159  * Function         bta_av_close_all_rc
160  *
161  * Description      close the all AVRC handle.
162  *
163  * Returns          void
164  *
165  ******************************************************************************/
bta_av_close_all_rc(tBTA_AV_CB * p_cb)166 static void bta_av_close_all_rc(tBTA_AV_CB* p_cb) {
167   int i;
168 
169   for (i = 0; i < BTA_AV_NUM_RCB; i++) {
170     if ((p_cb->disabling) || (bta_av_cb.rcb[i].shdl != 0))
171       bta_av_del_rc(&bta_av_cb.rcb[i]);
172   }
173 }
174 
175 /*******************************************************************************
176  *
177  * Function         bta_av_del_sdp_rec
178  *
179  * Description      delete the given SDP record handle.
180  *
181  * Returns          void
182  *
183  ******************************************************************************/
bta_av_del_sdp_rec(uint32_t * p_sdp_handle)184 static void bta_av_del_sdp_rec(uint32_t* p_sdp_handle) {
185   if (*p_sdp_handle != 0) {
186     if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(*p_sdp_handle)) {
187       log::warn("Unable to delete SDP record:{}", *p_sdp_handle);
188     }
189     *p_sdp_handle = 0;
190   }
191 }
192 
193 /*******************************************************************************
194  *
195  * Function         bta_av_avrc_sdp_cback
196  *
197  * Description      AVRCP service discovery callback.
198  *
199  * Returns          void
200  *
201  ******************************************************************************/
bta_av_avrc_sdp_cback(uint16_t)202 static void bta_av_avrc_sdp_cback(uint16_t /* status */) {
203   BT_HDR_RIGID* p_msg = (BT_HDR_RIGID*)osi_malloc(sizeof(BT_HDR_RIGID));
204 
205   p_msg->event = BTA_AV_SDP_AVRC_DISC_EVT;
206 
207   bta_sys_sendmsg(p_msg);
208 }
209 
210 /*******************************************************************************
211  *
212  * Function         bta_av_rc_ctrl_cback
213  *
214  * Description      AVRCP control callback.
215  *
216  * Returns          void
217  *
218  ******************************************************************************/
bta_av_rc_ctrl_cback(uint8_t handle,uint8_t event,uint16_t,const RawAddress * peer_addr)219 static void bta_av_rc_ctrl_cback(uint8_t handle, uint8_t event,
220                                  uint16_t /* result */,
221                                  const RawAddress* peer_addr) {
222   uint16_t msg_event = 0;
223 
224   if (btif_av_both_enable() && peer_addr != NULL &&
225       btif_av_peer_is_connected_sink(*peer_addr)) {
226     log::warn("not cback legacy cback, and close the handle");
227 
228     if (event == AVRC_CLOSE_IND_EVT || event == AVRC_OPEN_IND_EVT) {
229       log::verbose("resend close event");
230       tBTA_AV_RC_CONN_CHG* p_msg =
231           (tBTA_AV_RC_CONN_CHG*)osi_malloc(sizeof(tBTA_AV_RC_CONN_CHG));
232       p_msg->hdr.event = BTA_AV_AVRC_CLOSE_EVT;
233       p_msg->handle = handle;
234       p_msg->peer_addr = *peer_addr;
235       bta_sys_sendmsg(p_msg);
236     }
237     return;
238   }
239 
240   log::verbose("handle: {} event=0x{:x}", handle, event);
241   if (event == AVRC_OPEN_IND_EVT) {
242     /* save handle of opened connection
243     bta_av_cb.rc_handle = handle;*/
244 
245     msg_event = BTA_AV_AVRC_OPEN_EVT;
246   } else if (event == AVRC_CLOSE_IND_EVT) {
247     msg_event = BTA_AV_AVRC_CLOSE_EVT;
248   } else if (event == AVRC_BROWSE_OPEN_IND_EVT) {
249     msg_event = BTA_AV_AVRC_BROWSE_OPEN_EVT;
250   } else if (event == AVRC_BROWSE_CLOSE_IND_EVT) {
251     msg_event = BTA_AV_AVRC_BROWSE_CLOSE_EVT;
252   }
253 
254   if (msg_event) {
255     tBTA_AV_RC_CONN_CHG* p_msg =
256         (tBTA_AV_RC_CONN_CHG*)osi_malloc(sizeof(tBTA_AV_RC_CONN_CHG));
257     p_msg->hdr.event = msg_event;
258     p_msg->handle = handle;
259     p_msg->peer_addr = (peer_addr) ? (*peer_addr) : RawAddress::kEmpty;
260     bta_sys_sendmsg(p_msg);
261   }
262 }
263 
264 /*******************************************************************************
265  *
266  * Function         bta_av_rc_msg_cback
267  *
268  * Description      AVRCP message callback.
269  *
270  * Returns          void
271  *
272  ******************************************************************************/
bta_av_rc_msg_cback(uint8_t handle,uint8_t label,uint8_t opcode,tAVRC_MSG * p_msg)273 static void bta_av_rc_msg_cback(uint8_t handle, uint8_t label, uint8_t opcode,
274                                 tAVRC_MSG* p_msg) {
275   uint8_t* p_data_src = NULL;
276   uint16_t data_len = 0;
277 
278   log::verbose("handle: {} opcode=0x{:x}", handle, opcode);
279 
280   /* Copy avrc packet into BTA message buffer (for sending to BTA state machine)
281    */
282 
283   /* Get size of payload data  (for vendor and passthrough messages only; for
284    * browsing
285    * messages, use zero-copy) */
286   if (opcode == AVRC_OP_VENDOR && p_msg->vendor.p_vendor_data != NULL) {
287     p_data_src = p_msg->vendor.p_vendor_data;
288     data_len = (uint16_t)p_msg->vendor.vendor_len;
289   } else if (opcode == AVRC_OP_PASS_THRU && p_msg->pass.p_pass_data != NULL) {
290     p_data_src = p_msg->pass.p_pass_data;
291     data_len = (uint16_t)p_msg->pass.pass_len;
292   }
293 
294   /* Create a copy of the message */
295   tBTA_AV_RC_MSG* p_buf =
296       (tBTA_AV_RC_MSG*)osi_malloc(sizeof(tBTA_AV_RC_MSG) + data_len);
297 
298   p_buf->hdr.event = BTA_AV_AVRC_MSG_EVT;
299   p_buf->handle = handle;
300   p_buf->label = label;
301   p_buf->opcode = opcode;
302   memcpy(&p_buf->msg, p_msg, sizeof(tAVRC_MSG));
303   /* Copy the data payload, and set the pointer to it */
304   if (p_data_src != NULL) {
305     uint8_t* p_data_dst = (uint8_t*)(p_buf + 1);
306     memcpy(p_data_dst, p_data_src, data_len);
307 
308     /* Update bta message buffer to point to payload data */
309     /* (Note AVRC_OP_BROWSING uses zero-copy: p_buf->msg.browse.p_browse_data
310      * already points to original avrc buffer) */
311     if (opcode == AVRC_OP_VENDOR)
312       p_buf->msg.vendor.p_vendor_data = p_data_dst;
313     else if (opcode == AVRC_OP_PASS_THRU)
314       p_buf->msg.pass.p_pass_data = p_data_dst;
315   }
316 
317   if (opcode == AVRC_OP_BROWSE) {
318     /* set p_pkt to NULL, so avrc would not free the buffer */
319     p_msg->browse.p_browse_pkt = NULL;
320   }
321 
322   bta_sys_sendmsg(p_buf);
323 }
324 
325 /*******************************************************************************
326  *
327  * Function         bta_av_rc_create
328  *
329  * Description      alloc RCB and call AVRC_Open
330  *
331  * Returns          the created rc handle
332  *
333  ******************************************************************************/
bta_av_rc_create(tBTA_AV_CB * p_cb,uint8_t role,uint8_t shdl,uint8_t lidx)334 uint8_t bta_av_rc_create(tBTA_AV_CB* p_cb, uint8_t role, uint8_t shdl,
335                          uint8_t lidx) {
336   if ((!btif_av_src_sink_coexist_enabled() ||
337        (btif_av_src_sink_coexist_enabled() && !btif_av_is_sink_enabled() &&
338         btif_av_is_source_enabled())) &&
339       is_new_avrcp_enabled()) {
340     log::info("Skipping RC creation for the old AVRCP profile");
341     return BTA_AV_RC_HANDLE_NONE;
342   }
343 
344   tAVRC_CONN_CB ccb;
345   RawAddress bda = RawAddress::kAny;
346   uint8_t status = BTA_AV_RC_ROLE_ACP;
347   int i;
348   uint8_t rc_handle;
349   tBTA_AV_RCB* p_rcb;
350 
351   if (role == AVCT_INT) {
352     // Can't grab a stream control block that doesn't have a valid handle
353     if (!shdl) {
354       log::error("Can't grab stream control block for shdl = {} -> index = {}",
355                  shdl, shdl - 1);
356       return BTA_AV_RC_HANDLE_NONE;
357     }
358     tBTA_AV_SCB* p_scb = p_cb->p_scb[shdl - 1];
359     bda = p_scb->PeerAddress();
360     status = BTA_AV_RC_ROLE_INT;
361     DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_scb->PeerAddress(),
362                                        IOT_CONF_KEY_AVRCP_CONN_COUNT);
363 
364   } else {
365     p_rcb = bta_av_get_rcb_by_shdl(shdl);
366     if (p_rcb != NULL) {
367       log::error("ACP handle exist for shdl:{}", shdl);
368       p_rcb->lidx = lidx;
369       return p_rcb->handle;
370     }
371   }
372 
373   ccb.ctrl_cback = base::Bind(bta_av_rc_ctrl_cback);
374   ccb.msg_cback = base::Bind(bta_av_rc_msg_cback);
375   ccb.company_id = p_bta_av_cfg->company_id;
376   ccb.conn = role;
377   /* note: BTA_AV_FEAT_RCTG = AVRC_CT_TARGET, BTA_AV_FEAT_RCCT = AVRC_CT_CONTROL
378    */
379   ccb.control = p_cb->features & (BTA_AV_FEAT_RCTG | BTA_AV_FEAT_RCCT |
380                                   BTA_AV_FEAT_METADATA | AVRC_CT_PASSIVE);
381 
382   if (AVRC_Open(&rc_handle, &ccb, bda) != AVRC_SUCCESS) {
383     DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(bda, IOT_CONF_KEY_AVRCP_CONN_FAIL_COUNT);
384     return BTA_AV_RC_HANDLE_NONE;
385   }
386 
387   i = rc_handle;
388   p_rcb = &p_cb->rcb[i];
389 
390   if (p_rcb->handle != BTA_AV_RC_HANDLE_NONE) {
391     log::error("found duplicated handle:{}", rc_handle);
392   }
393 
394   p_rcb->handle = rc_handle;
395   p_rcb->status = status;
396   p_rcb->shdl = shdl;
397   p_rcb->lidx = lidx;
398   p_rcb->peer_features = 0;
399   p_rcb->peer_ct_features = 0;
400   p_rcb->peer_tg_features = 0;
401   p_rcb->cover_art_psm = 0;
402   if (lidx == (BTA_AV_NUM_LINKS + 1)) {
403     /* this LIDX is reserved for the AVRCP ACP connection */
404     p_cb->rc_acp_handle = p_rcb->handle;
405     p_cb->rc_acp_idx = (i + 1);
406     log::verbose("rc_acp_handle:{} idx:{}", p_cb->rc_acp_handle,
407                  p_cb->rc_acp_idx);
408   }
409   log::verbose(
410       "create {}, role: {}, shdl:{}, rc_handle:{}, lidx:{}, status:0x{:x}", i,
411       role, shdl, p_rcb->handle, lidx, p_rcb->status);
412 
413   return rc_handle;
414 }
415 
416 /*******************************************************************************
417  *
418  * Function         bta_av_valid_group_navi_msg
419  *
420  * Description      Check if it is Group Navigation Msg for Metadata
421  *
422  * Returns          AVRC_RSP_ACCEPT or AVRC_RSP_NOT_IMPL
423  *
424  ******************************************************************************/
bta_av_group_navi_supported(uint8_t len,uint8_t * p_data,bool is_inquiry)425 static tBTA_AV_CODE bta_av_group_navi_supported(uint8_t len, uint8_t* p_data,
426                                                 bool is_inquiry) {
427   tBTA_AV_CODE ret = AVRC_RSP_NOT_IMPL;
428   uint8_t* p_ptr = p_data;
429   uint16_t u16;
430   uint32_t u32;
431 
432   if (p_bta_av_cfg->avrc_group && len == BTA_GROUP_NAVI_MSG_OP_DATA_LEN) {
433     BTA_AV_BE_STREAM_TO_CO_ID(u32, p_ptr);
434     BE_STREAM_TO_UINT16(u16, p_ptr);
435 
436     if (u32 == AVRC_CO_METADATA) {
437       if (is_inquiry) {
438         if (u16 <= AVRC_PDU_PREV_GROUP) ret = AVRC_RSP_IMPL_STBL;
439       } else {
440         if (u16 <= AVRC_PDU_PREV_GROUP)
441           ret = AVRC_RSP_ACCEPT;
442         else
443           ret = AVRC_RSP_REJ;
444       }
445     }
446   }
447 
448   return ret;
449 }
450 
451 /*******************************************************************************
452  *
453  * Function         bta_av_op_supported
454  *
455  * Description      Check if remote control operation is supported.
456  *
457  * Returns          AVRC_RSP_ACCEPT of supported, AVRC_RSP_NOT_IMPL if not.
458  *
459  ******************************************************************************/
bta_av_op_supported(tBTA_AV_RC rc_id,bool is_inquiry)460 static tBTA_AV_CODE bta_av_op_supported(tBTA_AV_RC rc_id, bool is_inquiry) {
461   tBTA_AV_CODE ret_code = AVRC_RSP_NOT_IMPL;
462 
463   if (p_bta_av_rc_id) {
464     if (is_inquiry) {
465       if (p_bta_av_rc_id[rc_id >> 4] & (1 << (rc_id & 0x0F))) {
466         ret_code = AVRC_RSP_IMPL_STBL;
467       }
468     } else {
469       if (p_bta_av_rc_id[rc_id >> 4] & (1 << (rc_id & 0x0F))) {
470         ret_code = AVRC_RSP_ACCEPT;
471       } else if ((p_bta_av_cfg->rc_pass_rsp == AVRC_RSP_INTERIM) &&
472                  p_bta_av_rc_id_ac) {
473         if (p_bta_av_rc_id_ac[rc_id >> 4] & (1 << (rc_id & 0x0F))) {
474           ret_code = AVRC_RSP_INTERIM;
475         }
476       }
477     }
478   }
479   return ret_code;
480 }
481 
482 /*******************************************************************************
483  *
484  * Function         bta_av_find_lcb
485  *
486  * Description      Given BD_addr, find the associated LCB.
487  *
488  * Returns          NULL, if not found.
489  *
490  ******************************************************************************/
bta_av_find_lcb(const RawAddress & addr,uint8_t op)491 tBTA_AV_LCB* bta_av_find_lcb(const RawAddress& addr, uint8_t op) {
492   tBTA_AV_CB* p_cb = &bta_av_cb;
493   int xx;
494   uint8_t mask;
495   tBTA_AV_LCB* p_lcb = NULL;
496 
497   log::verbose("address: {} op:{}", addr, op);
498   for (xx = 0; xx < BTA_AV_NUM_LINKS; xx++) {
499     mask = 1 << xx; /* the used mask for this lcb */
500     if ((mask & p_cb->conn_lcb) && p_cb->lcb[xx].addr == addr) {
501       p_lcb = &p_cb->lcb[xx];
502       if (op == BTA_AV_LCB_FREE) {
503         p_cb->conn_lcb &= ~mask; /* clear the connect mask */
504         log::verbose("conn_lcb: 0x{:x}", p_cb->conn_lcb);
505       }
506       break;
507     }
508   }
509   return p_lcb;
510 }
511 
512 /*******************************************************************************
513  *
514  * Function         bta_av_rc_opened
515  *
516  * Description      Set AVRCP state to opened.
517  *
518  * Returns          void
519  *
520  ******************************************************************************/
bta_av_rc_opened(tBTA_AV_CB * p_cb,tBTA_AV_DATA * p_data)521 void bta_av_rc_opened(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) {
522   tBTA_AV_RC_OPEN rc_open;
523   tBTA_AV_SCB* p_scb;
524   int i;
525   uint8_t shdl = 0;
526   tBTA_AV_LCB* p_lcb;
527   tBTA_AV_RCB* p_rcb;
528   uint8_t tmp;
529   uint8_t disc = 0;
530 
531   /* find the SCB & stop the timer */
532   for (i = 0; i < BTA_AV_NUM_STRS; i++) {
533     p_scb = p_cb->p_scb[i];
534     if (p_scb && p_scb->PeerAddress() == p_data->rc_conn_chg.peer_addr) {
535       p_scb->rc_handle = p_data->rc_conn_chg.handle;
536       log::verbose("shdl:{}, srch {}", i + 1, p_scb->rc_handle);
537       shdl = i + 1;
538       log::info("allow incoming AVRCP connections:{}", p_scb->use_rc);
539       alarm_cancel(p_scb->avrc_ct_timer);
540       disc = p_scb->hndl;
541       break;
542     }
543   }
544 
545   i = p_data->rc_conn_chg.handle;
546   if (p_cb->rcb[i].handle == BTA_AV_RC_HANDLE_NONE) {
547     log::error("not a valid handle:{} any more", i);
548     return;
549   }
550 
551   log::verbose("local features {} peer features {}", p_cb->features,
552                p_cb->rcb[i].peer_features);
553 
554   /* listen to browsing channel when the connection is open,
555    * if peer initiated AVRCP connection and local device supports browsing
556    * channel */
557   AVRC_OpenBrowse(p_data->rc_conn_chg.handle, AVCT_ACP);
558 
559   if (p_cb->rcb[i].lidx == (BTA_AV_NUM_LINKS + 1) && shdl != 0) {
560     /* rc is opened on the RC only ACP channel, but is for a specific
561      * SCB -> need to switch RCBs */
562     p_rcb = bta_av_get_rcb_by_shdl(shdl);
563     if (p_rcb) {
564       p_rcb->shdl = p_cb->rcb[i].shdl;
565       tmp = p_rcb->lidx;
566       p_rcb->lidx = p_cb->rcb[i].lidx;
567       p_cb->rcb[i].lidx = tmp;
568       p_cb->rc_acp_handle = p_rcb->handle;
569       p_cb->rc_acp_idx = (p_rcb - p_cb->rcb) + 1;
570       log::verbose("switching RCB rc_acp_handle:{} idx:{}", p_cb->rc_acp_handle,
571                    p_cb->rc_acp_idx);
572     }
573   }
574 
575   p_cb->rcb[i].shdl = shdl;
576   rc_open.rc_handle = i;
577   log::error("rcb[{}] shdl:{} lidx:{}/{}", i, shdl, p_cb->rcb[i].lidx,
578              p_cb->lcb[BTA_AV_NUM_LINKS].lidx);
579   p_cb->rcb[i].status |= BTA_AV_RC_CONN_MASK;
580 
581   if (!shdl && 0 == p_cb->lcb[BTA_AV_NUM_LINKS].lidx) {
582     /* no associated SCB -> connected to an RC only device
583      * update the index to the extra LCB */
584     p_lcb = &p_cb->lcb[BTA_AV_NUM_LINKS];
585     p_lcb->addr = p_data->rc_conn_chg.peer_addr;
586     p_lcb->lidx = BTA_AV_NUM_LINKS + 1;
587     p_cb->rcb[i].lidx = p_lcb->lidx;
588     p_lcb->conn_msk = 1;
589     log::error("bd_addr: {} rcb[{}].lidx={}, lcb.conn_msk=x{:x}", p_lcb->addr,
590                i, p_cb->rcb[i].lidx, p_lcb->conn_msk);
591     disc = p_data->rc_conn_chg.handle | BTA_AV_CHNL_MSK;
592   }
593 
594   rc_open.peer_addr = p_data->rc_conn_chg.peer_addr;
595   rc_open.peer_features = p_cb->rcb[i].peer_features;
596   rc_open.cover_art_psm = p_cb->rcb[i].cover_art_psm;
597   if (btif_av_both_enable()) {
598     if (rc_open.peer_addr == p_cb->rc_feature.peer_addr) {
599       rc_open.peer_features = p_cb->rc_feature.peer_features;
600       rc_open.peer_ct_features = p_cb->rc_feature.peer_ct_features;
601       rc_open.peer_tg_features = p_cb->rc_feature.peer_tg_features;
602     } else {
603       rc_open.peer_features = p_cb->rcb[i].peer_features;
604       rc_open.peer_ct_features = p_cb->rcb[i].peer_ct_features;
605       rc_open.peer_tg_features = p_cb->rcb[i].peer_tg_features;
606     }
607     rc_open.status = BTA_AV_SUCCESS;
608     log::verbose(
609         "local features:0x{:x} peer_features:0x{:x}, peer_ct_feature:0x{:x}, "
610         "peer_tg_feature:0x{:x}",
611         p_cb->features, rc_open.peer_features, rc_open.peer_ct_features,
612         rc_open.peer_tg_features);
613     if (rc_open.peer_features == 0 && rc_open.peer_ct_features == 0 &&
614         rc_open.peer_tg_features == 0) {
615       /* we have not done SDP on peer RC capabilities.
616        * peer must have initiated the RC connection
617        * We Don't have SDP records of Peer, so we by
618        * default will take values depending upon registered
619        * features */
620       if (p_cb->features & BTA_AV_FEAT_RCTG) {
621         rc_open.peer_ct_features |= BTA_AV_FEAT_RCCT;
622         rc_open.peer_features |= BTA_AV_FEAT_RCCT;
623       }
624       bta_av_rc_disc(disc);
625     }
626     (*p_cb->p_cback)(BTA_AV_RC_OPEN_EVT, (tBTA_AV*)&rc_open);
627 
628     /* if local initiated AVRCP connection and both peer and locals device
629      * support
630      * browsing channel, open the browsing channel now
631      * Some TG would not broadcast browse feature hence check inter-op. */
632     if ((p_cb->features & BTA_AV_FEAT_BROWSE) &&
633         ((rc_open.peer_ct_features & BTA_AV_FEAT_BROWSE) ||
634          (rc_open.peer_tg_features & BTA_AV_FEAT_BROWSE))) {
635       if ((p_cb->rcb[i].status & BTA_AV_RC_ROLE_MASK) == BTA_AV_RC_ROLE_INT) {
636         log::verbose("opening AVRC Browse channel");
637         AVRC_OpenBrowse(p_data->rc_conn_chg.handle, AVCT_INT);
638       }
639     }
640     return;
641   }
642   rc_open.status = BTA_AV_SUCCESS;
643   log::verbose("local features:x{:x} peer_features:x{:x}", p_cb->features,
644                rc_open.peer_features);
645   log::verbose("cover art psm:x{:x}", rc_open.cover_art_psm);
646   if (rc_open.peer_features == 0) {
647     /* we have not done SDP on peer RC capabilities.
648      * peer must have initiated the RC connection */
649     if (p_cb->features & BTA_AV_FEAT_RCCT)
650       rc_open.peer_features |= BTA_AV_FEAT_RCTG;
651     if (p_cb->features & BTA_AV_FEAT_RCTG)
652       rc_open.peer_features |= BTA_AV_FEAT_RCCT;
653 
654     bta_av_rc_disc(disc);
655   }
656   tBTA_AV bta_av_data;
657   bta_av_data.rc_open = rc_open;
658   (*p_cb->p_cback)(BTA_AV_RC_OPEN_EVT, &bta_av_data);
659 
660   /* if local initiated AVRCP connection and both peer and locals device support
661    * browsing channel, open the browsing channel now
662    * TODO (sanketa): Some TG would not broadcast browse feature hence check
663    * inter-op. */
664   if ((p_cb->features & BTA_AV_FEAT_BROWSE) &&
665       (rc_open.peer_features & BTA_AV_FEAT_BROWSE) &&
666       ((p_cb->rcb[i].status & BTA_AV_RC_ROLE_MASK) == BTA_AV_RC_ROLE_INT)) {
667     log::verbose("opening AVRC Browse channel");
668     AVRC_OpenBrowse(p_data->rc_conn_chg.handle, AVCT_INT);
669   }
670 }
671 
672 /*******************************************************************************
673  *
674  * Function         bta_av_rc_remote_cmd
675  *
676  * Description      Send an AVRCP remote control command.
677  *
678  * Returns          void
679  *
680  ******************************************************************************/
bta_av_rc_remote_cmd(tBTA_AV_CB * p_cb,tBTA_AV_DATA * p_data)681 void bta_av_rc_remote_cmd(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) {
682   tBTA_AV_RCB* p_rcb;
683   if (p_cb->features & BTA_AV_FEAT_RCCT) {
684     if (p_data->hdr.layer_specific < BTA_AV_NUM_RCB) {
685       p_rcb = &p_cb->rcb[p_data->hdr.layer_specific];
686       if (p_rcb->status & BTA_AV_RC_CONN_MASK) {
687         AVRC_PassCmd(p_rcb->handle, p_data->api_remote_cmd.label,
688                      &p_data->api_remote_cmd.msg);
689       }
690     }
691   }
692 }
693 
694 /*******************************************************************************
695  *
696  * Function         bta_av_rc_vendor_cmd
697  *
698  * Description      Send an AVRCP vendor specific command.
699  *
700  * Returns          void
701  *
702  ******************************************************************************/
bta_av_rc_vendor_cmd(tBTA_AV_CB * p_cb,tBTA_AV_DATA * p_data)703 void bta_av_rc_vendor_cmd(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) {
704   tBTA_AV_RCB* p_rcb;
705   if ((p_cb->features & (BTA_AV_FEAT_RCCT | BTA_AV_FEAT_VENDOR)) ==
706       (BTA_AV_FEAT_RCCT | BTA_AV_FEAT_VENDOR)) {
707     if (p_data->hdr.layer_specific < BTA_AV_NUM_RCB) {
708       p_rcb = &p_cb->rcb[p_data->hdr.layer_specific];
709       AVRC_VendorCmd(p_rcb->handle, p_data->api_vendor.label,
710                      &p_data->api_vendor.msg);
711     }
712   }
713 }
714 
715 /*******************************************************************************
716  *
717  * Function         bta_av_rc_vendor_rsp
718  *
719  * Description      Send an AVRCP vendor specific response.
720  *
721  * Returns          void
722  *
723  ******************************************************************************/
bta_av_rc_vendor_rsp(tBTA_AV_CB * p_cb,tBTA_AV_DATA * p_data)724 void bta_av_rc_vendor_rsp(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) {
725   tBTA_AV_RCB* p_rcb;
726   if ((p_cb->features & (BTA_AV_FEAT_RCTG | BTA_AV_FEAT_VENDOR)) ==
727       (BTA_AV_FEAT_RCTG | BTA_AV_FEAT_VENDOR)) {
728     if (p_data->hdr.layer_specific < BTA_AV_NUM_RCB) {
729       p_rcb = &p_cb->rcb[p_data->hdr.layer_specific];
730       AVRC_VendorRsp(p_rcb->handle, p_data->api_vendor.label,
731                      &p_data->api_vendor.msg);
732     }
733   }
734 }
735 
736 /*******************************************************************************
737  *
738  * Function         bta_av_rc_meta_rsp
739  *
740  * Description      Send an AVRCP metadata/advanced control command/response.
741  *
742  * Returns          void
743  *
744  ******************************************************************************/
bta_av_rc_meta_rsp(tBTA_AV_CB * p_cb,tBTA_AV_DATA * p_data)745 void bta_av_rc_meta_rsp(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) {
746   tBTA_AV_RCB* p_rcb;
747   bool do_free = true;
748 
749   if ((p_cb->features & BTA_AV_FEAT_METADATA) &&
750       (p_data->hdr.layer_specific < BTA_AV_NUM_RCB)) {
751     if ((p_data->api_meta_rsp.is_rsp && (p_cb->features & BTA_AV_FEAT_RCTG)) ||
752         (!p_data->api_meta_rsp.is_rsp && (p_cb->features & BTA_AV_FEAT_RCCT))) {
753       p_rcb = &p_cb->rcb[p_data->hdr.layer_specific];
754       if (p_rcb->handle != BTA_AV_RC_HANDLE_NONE) {
755         AVRC_MsgReq(p_rcb->handle, p_data->api_meta_rsp.label,
756                     p_data->api_meta_rsp.rsp_code, p_data->api_meta_rsp.p_pkt,
757                     false);
758         do_free = false;
759       }
760     }
761   }
762 
763   if (do_free) osi_free_and_reset((void**)&p_data->api_meta_rsp.p_pkt);
764 }
765 
766 /*******************************************************************************
767  *
768  * Function         bta_av_rc_free_rsp
769  *
770  * Description      free an AVRCP metadata command buffer.
771  *
772  * Returns          void
773  *
774  ******************************************************************************/
bta_av_rc_free_rsp(tBTA_AV_CB *,tBTA_AV_DATA * p_data)775 void bta_av_rc_free_rsp(tBTA_AV_CB* /* p_cb */, tBTA_AV_DATA* p_data) {
776   osi_free_and_reset((void**)&p_data->api_meta_rsp.p_pkt);
777 }
778 
779 /*******************************************************************************
780  *
781  * Function         bta_av_rc_free_browse_msg
782  *
783  * Description      free an AVRCP browse message buffer.
784  *
785  * Returns          void
786  *
787  ******************************************************************************/
bta_av_rc_free_browse_msg(tBTA_AV_CB *,tBTA_AV_DATA * p_data)788 void bta_av_rc_free_browse_msg(tBTA_AV_CB* /* p_cb */, tBTA_AV_DATA* p_data) {
789   if (p_data->rc_msg.opcode == AVRC_OP_BROWSE) {
790     osi_free_and_reset((void**)&p_data->rc_msg.msg.browse.p_browse_pkt);
791   }
792 }
793 
794 /*******************************************************************************
795  *
796  * Function         bta_av_chk_notif_evt_id
797  *
798  * Description      make sure the requested player id is valid.
799  *
800  * Returns          BTA_AV_STS_NO_RSP, if no error
801  *
802  ******************************************************************************/
bta_av_chk_notif_evt_id(tAVRC_MSG_VENDOR * p_vendor)803 static tAVRC_STS bta_av_chk_notif_evt_id(tAVRC_MSG_VENDOR* p_vendor) {
804   tAVRC_STS status = BTA_AV_STS_NO_RSP;
805   uint8_t xx;
806   uint16_t u16;
807   uint8_t* p = p_vendor->p_vendor_data + 2;
808 
809   BE_STREAM_TO_UINT16(u16, p);
810   /* double check the fixed length */
811   if ((u16 != 5) || (p_vendor->vendor_len != 9)) {
812     status = AVRC_STS_INTERNAL_ERR;
813   } else {
814     if (btif_av_both_enable()) {
815       for (xx = 0; xx < bta_av_cfg.num_evt_ids; xx++) {
816         if (*p == bta_av_cfg.p_meta_evt_ids[xx]) {
817           return status;
818         }
819       }
820       for (xx = 0; xx < get_bta_avk_cfg()->num_evt_ids; xx++) {
821         if (*p == get_bta_avk_cfg()->p_meta_evt_ids[xx]) {
822           return status;
823         }
824       }
825       return AVRC_STS_BAD_PARAM;
826     }
827     /* make sure the player_id is valid */
828     for (xx = 0; xx < p_bta_av_cfg->num_evt_ids; xx++) {
829       if (*p == p_bta_av_cfg->p_meta_evt_ids[xx]) {
830         break;
831       }
832     }
833     if (xx == p_bta_av_cfg->num_evt_ids) {
834       status = AVRC_STS_BAD_PARAM;
835     }
836   }
837 
838   return status;
839 }
840 
bta_av_proc_rsp(tAVRC_RESPONSE * p_rc_rsp)841 void bta_av_proc_rsp(tAVRC_RESPONSE* p_rc_rsp) {
842   uint16_t rc_ver = 0x105;
843   const tBTA_AV_CFG* p_src_cfg = NULL;
844   if (rc_ver != 0x103)
845     p_src_cfg = &bta_av_cfg;
846   else
847     p_src_cfg = &bta_av_cfg_compatibility;
848   p_rc_rsp->get_caps.count = p_src_cfg->num_evt_ids;
849   memcpy(p_rc_rsp->get_caps.param.event_id, p_src_cfg->p_meta_evt_ids,
850          p_src_cfg->num_evt_ids);
851   log::verbose("ver: 0x{:x}", rc_ver);
852   /* if it's not 1.3, then there should be a absolute volume */
853   if (rc_ver != 0x103) {
854     uint8_t evt_cnt = p_rc_rsp->get_caps.count;
855     p_rc_rsp->get_caps.count += get_bta_avk_cfg()->num_evt_ids;
856     if (evt_cnt < AVRC_CAP_MAX_NUM_EVT_ID) {
857       uint32_t i = 0;
858       for (i = 0; i < get_bta_avk_cfg()->num_evt_ids &&
859                   i + evt_cnt < AVRC_CAP_MAX_NUM_EVT_ID;
860            i++) {
861         p_rc_rsp->get_caps.param.event_id[evt_cnt + i] =
862             get_bta_avk_cfg()->p_meta_evt_ids[i];
863       }
864     }
865   }
866 }
867 
868 /*******************************************************************************
869  *
870  * Function         bta_av_proc_meta_cmd
871  *
872  * Description      Process an AVRCP metadata command from the peer.
873  *
874  * Returns          true to respond immediately
875  *
876  ******************************************************************************/
bta_av_proc_meta_cmd(tAVRC_RESPONSE * p_rc_rsp,tBTA_AV_RC_MSG * p_msg,uint8_t * p_ctype)877 tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp,
878                                  tBTA_AV_RC_MSG* p_msg, uint8_t* p_ctype) {
879   tBTA_AV_EVT evt = BTA_AV_META_MSG_EVT;
880   uint8_t u8, pdu, *p;
881   uint16_t u16;
882   tAVRC_MSG_VENDOR* p_vendor = &p_msg->msg.vendor;
883 
884   if (p_vendor->vendor_len == 0) {
885     p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
886     log::verbose("p_vendor->vendor_len == 0");
887     // the caller of this function assume 0 to be an invalid event
888     return 0;
889   }
890 
891   pdu = *(p_vendor->p_vendor_data);
892   p_rc_rsp->pdu = pdu;
893   *p_ctype = AVRC_RSP_REJ;
894 
895   /* Check to ansure a  valid minimum meta data length */
896   if ((AVRC_MIN_META_CMD_LEN + p_vendor->vendor_len) > AVRC_META_CMD_BUF_SIZE) {
897     /* reject it */
898     p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
899     log::error("Invalid meta-command length: {}", p_vendor->vendor_len);
900     return 0;
901   }
902 
903   /* Metadata messages only use PANEL sub-unit type */
904   if (p_vendor->hdr.subunit_type != AVRC_SUB_PANEL) {
905     log::verbose("SUBUNIT must be PANEL");
906     /* reject it */
907     evt = 0;
908     p_vendor->hdr.ctype = AVRC_RSP_NOT_IMPL;
909     p_vendor->vendor_len = 0;
910     p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
911   } else if (!AVRC_IsValidAvcType(pdu, p_vendor->hdr.ctype)) {
912     log::verbose("Invalid pdu/ctype: 0x{:x}, {}", pdu, p_vendor->hdr.ctype);
913     /* reject invalid message without reporting to app */
914     evt = 0;
915     p_rc_rsp->rsp.status = AVRC_STS_BAD_CMD;
916   } else {
917     switch (pdu) {
918       case AVRC_PDU_GET_CAPABILITIES:
919         /* process GetCapabilities command without reporting the event to app */
920         evt = 0;
921         if (p_vendor->vendor_len != 5) {
922           p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR;
923           break;
924         }
925         u8 = *(p_vendor->p_vendor_data + 4);
926         p = p_vendor->p_vendor_data + 2;
927         p_rc_rsp->get_caps.capability_id = u8;
928         BE_STREAM_TO_UINT16(u16, p);
929         if (u16 != 1) {
930           p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR;
931         } else {
932           p_rc_rsp->get_caps.status = AVRC_STS_NO_ERROR;
933           if (u8 == AVRC_CAP_COMPANY_ID) {
934             *p_ctype = AVRC_RSP_IMPL_STBL;
935             p_rc_rsp->get_caps.count = p_bta_av_cfg->num_co_ids;
936             memcpy(p_rc_rsp->get_caps.param.company_id,
937                    p_bta_av_cfg->p_meta_co_ids,
938                    (p_bta_av_cfg->num_co_ids << 2));
939           } else if (u8 == AVRC_CAP_EVENTS_SUPPORTED) {
940             *p_ctype = AVRC_RSP_IMPL_STBL;
941             if (btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) {
942               bta_av_proc_rsp(p_rc_rsp);
943               break;
944             }
945             p_rc_rsp->get_caps.count = p_bta_av_cfg->num_evt_ids;
946             memcpy(p_rc_rsp->get_caps.param.event_id,
947                    p_bta_av_cfg->p_meta_evt_ids, p_bta_av_cfg->num_evt_ids);
948           } else {
949             log::verbose("Invalid capability ID: 0x{:x}", u8);
950             /* reject - unknown capability ID */
951             p_rc_rsp->get_caps.status = AVRC_STS_BAD_PARAM;
952           }
953         }
954         break;
955 
956       case AVRC_PDU_REGISTER_NOTIFICATION:
957         /* make sure the event_id is implemented */
958         p_rc_rsp->rsp.status = bta_av_chk_notif_evt_id(p_vendor);
959         if (p_rc_rsp->rsp.status != BTA_AV_STS_NO_RSP) evt = 0;
960         break;
961     }
962   }
963 
964   return evt;
965 }
966 
967 /*******************************************************************************
968  *
969  * Function         bta_av_rc_msg
970  *
971  * Description      Process an AVRCP message from the peer.
972  *
973  * Returns          void
974  *
975  ******************************************************************************/
bta_av_rc_msg(tBTA_AV_CB * p_cb,tBTA_AV_DATA * p_data)976 void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) {
977   tBTA_AV_EVT evt = 0;
978   tBTA_AV av;
979   BT_HDR* p_pkt = NULL;
980   tAVRC_MSG_VENDOR* p_vendor = &p_data->rc_msg.msg.vendor;
981   bool is_inquiry = ((p_data->rc_msg.msg.hdr.ctype == AVRC_CMD_SPEC_INQ) ||
982                      p_data->rc_msg.msg.hdr.ctype == AVRC_CMD_GEN_INQ);
983   uint8_t ctype = 0;
984   tAVRC_RESPONSE rc_rsp;
985 
986   rc_rsp.rsp.status = BTA_AV_STS_NO_RSP;
987 
988   if (NULL == p_data) {
989     log::error("Message from peer with no data");
990     return;
991   }
992 
993   log::verbose("opcode={:x}, ctype={:x}", p_data->rc_msg.opcode,
994                p_data->rc_msg.msg.hdr.ctype);
995 
996   if (p_data->rc_msg.opcode == AVRC_OP_PASS_THRU) {
997     /* if this is a pass thru command */
998     if ((p_data->rc_msg.msg.hdr.ctype == AVRC_CMD_CTRL) ||
999         (p_data->rc_msg.msg.hdr.ctype == AVRC_CMD_SPEC_INQ) ||
1000         (p_data->rc_msg.msg.hdr.ctype == AVRC_CMD_GEN_INQ)) {
1001       /* check if operation is supported */
1002       char avrcp_ct_support[PROPERTY_VALUE_MAX];
1003       osi_property_get("bluetooth.pts.avrcp_ct.support", avrcp_ct_support,
1004                        "false");
1005       if (p_data->rc_msg.msg.pass.op_id == AVRC_ID_VENDOR) {
1006         p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_NOT_IMPL;
1007         if (p_cb->features & BTA_AV_FEAT_METADATA)
1008           p_data->rc_msg.msg.hdr.ctype = bta_av_group_navi_supported(
1009               p_data->rc_msg.msg.pass.pass_len,
1010               p_data->rc_msg.msg.pass.p_pass_data, is_inquiry);
1011       } else if (((p_data->rc_msg.msg.pass.op_id == AVRC_ID_VOL_UP) ||
1012                   (p_data->rc_msg.msg.pass.op_id == AVRC_ID_VOL_DOWN)) &&
1013                  !strcmp(avrcp_ct_support, "true")) {
1014         p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_ACCEPT;
1015       } else {
1016         p_data->rc_msg.msg.hdr.ctype =
1017             bta_av_op_supported(p_data->rc_msg.msg.pass.op_id, is_inquiry);
1018       }
1019 
1020       log::verbose("ctype {}", p_data->rc_msg.msg.hdr.ctype);
1021 
1022       /* send response */
1023       if (p_data->rc_msg.msg.hdr.ctype != AVRC_RSP_INTERIM)
1024         AVRC_PassRsp(p_data->rc_msg.handle, p_data->rc_msg.label,
1025                      &p_data->rc_msg.msg.pass);
1026 
1027       /* set up for callback if supported */
1028       if (p_data->rc_msg.msg.hdr.ctype == AVRC_RSP_ACCEPT ||
1029           p_data->rc_msg.msg.hdr.ctype == AVRC_RSP_INTERIM) {
1030         evt = BTA_AV_REMOTE_CMD_EVT;
1031         av.remote_cmd.rc_id = p_data->rc_msg.msg.pass.op_id;
1032         av.remote_cmd.key_state = p_data->rc_msg.msg.pass.state;
1033         av.remote_cmd.p_data = p_data->rc_msg.msg.pass.p_pass_data;
1034         av.remote_cmd.len = p_data->rc_msg.msg.pass.pass_len;
1035         memcpy(&av.remote_cmd.hdr, &p_data->rc_msg.msg.hdr, sizeof(tAVRC_HDR));
1036         av.remote_cmd.label = p_data->rc_msg.label;
1037       }
1038     }
1039     /* else if this is a pass thru response */
1040     /* id response type is not impl, we have to release label */
1041     else if (p_data->rc_msg.msg.hdr.ctype >= AVRC_RSP_NOT_IMPL) {
1042       /* set up for callback */
1043       evt = BTA_AV_REMOTE_RSP_EVT;
1044       av.remote_rsp.rc_id = p_data->rc_msg.msg.pass.op_id;
1045       av.remote_rsp.key_state = p_data->rc_msg.msg.pass.state;
1046       av.remote_rsp.rsp_code = p_data->rc_msg.msg.hdr.ctype;
1047       av.remote_rsp.label = p_data->rc_msg.label;
1048       av.remote_rsp.len = p_data->rc_msg.msg.pass.pass_len;
1049       av.remote_rsp.p_data = NULL;
1050 
1051       /* If this response is for vendor unique command  */
1052       if ((p_data->rc_msg.msg.pass.op_id == AVRC_ID_VENDOR) &&
1053           (p_data->rc_msg.msg.pass.pass_len > 0)) {
1054         av.remote_rsp.p_data =
1055             (uint8_t*)osi_malloc(p_data->rc_msg.msg.pass.pass_len);
1056         log::verbose("Vendor Unique data len = {}",
1057                      p_data->rc_msg.msg.pass.pass_len);
1058         memcpy(av.remote_rsp.p_data, p_data->rc_msg.msg.pass.p_pass_data,
1059                p_data->rc_msg.msg.pass.pass_len);
1060       }
1061     }
1062     /* must be a bad ctype -> reject*/
1063     else {
1064       p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_REJ;
1065       AVRC_PassRsp(p_data->rc_msg.handle, p_data->rc_msg.label,
1066                    &p_data->rc_msg.msg.pass);
1067     }
1068   }
1069   /* else if this is a vendor specific command or response */
1070   else if (p_data->rc_msg.opcode == AVRC_OP_VENDOR) {
1071     /* set up for callback */
1072     av.vendor_cmd.code = p_data->rc_msg.msg.hdr.ctype;
1073     av.vendor_cmd.company_id = p_vendor->company_id;
1074     av.vendor_cmd.label = p_data->rc_msg.label;
1075     av.vendor_cmd.p_data = p_vendor->p_vendor_data;
1076     av.vendor_cmd.len = p_vendor->vendor_len;
1077 
1078     /* if configured to support vendor specific and it's a command */
1079     if ((p_cb->features & BTA_AV_FEAT_VENDOR) &&
1080         p_data->rc_msg.msg.hdr.ctype <= AVRC_CMD_GEN_INQ) {
1081       if ((p_cb->features & BTA_AV_FEAT_METADATA) &&
1082           (p_vendor->company_id == AVRC_CO_METADATA)) {
1083         av.meta_msg.p_msg = &p_data->rc_msg.msg;
1084         rc_rsp.rsp.status = BTA_AV_STS_NO_RSP;
1085         evt = bta_av_proc_meta_cmd(&rc_rsp, &p_data->rc_msg, &ctype);
1086       } else {
1087         evt = BTA_AV_VENDOR_CMD_EVT;
1088       }
1089     } else if ((p_cb->features & BTA_AV_FEAT_VENDOR) &&
1090                p_data->rc_msg.msg.hdr.ctype >= AVRC_RSP_NOT_IMPL) {
1091       /* else if configured to support vendor specific and it's a response */
1092       if ((p_cb->features & BTA_AV_FEAT_METADATA) &&
1093           (p_vendor->company_id == AVRC_CO_METADATA)) {
1094         av.meta_msg.p_msg = &p_data->rc_msg.msg;
1095         evt = BTA_AV_META_MSG_EVT;
1096       } else {
1097         evt = BTA_AV_VENDOR_RSP_EVT;
1098       }
1099     } else if (!(p_cb->features & BTA_AV_FEAT_VENDOR) &&
1100                p_data->rc_msg.msg.hdr.ctype <= AVRC_CMD_GEN_INQ) {
1101       /* else if not configured to support vendor specific and it's a command */
1102       if (p_data->rc_msg.msg.vendor.p_vendor_data[0] == AVRC_PDU_INVALID) {
1103         /* reject it */
1104         p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_REJ;
1105         p_data->rc_msg.msg.vendor.p_vendor_data[4] = AVRC_STS_BAD_CMD;
1106       } else {
1107         p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_NOT_IMPL;
1108       }
1109       AVRC_VendorRsp(p_data->rc_msg.handle, p_data->rc_msg.label,
1110                      &p_data->rc_msg.msg.vendor);
1111     }
1112   } else if (p_data->rc_msg.opcode == AVRC_OP_BROWSE) {
1113     /* set up for callback */
1114     av.meta_msg.rc_handle = p_data->rc_msg.handle;
1115     av.meta_msg.company_id = p_vendor->company_id;
1116     av.meta_msg.code = p_data->rc_msg.msg.hdr.ctype;
1117     av.meta_msg.label = p_data->rc_msg.label;
1118     av.meta_msg.p_msg = &p_data->rc_msg.msg;
1119     av.meta_msg.p_data = p_data->rc_msg.msg.browse.p_browse_data;
1120     av.meta_msg.len = p_data->rc_msg.msg.browse.browse_len;
1121     evt = BTA_AV_META_MSG_EVT;
1122   }
1123 
1124   if (evt == 0 && rc_rsp.rsp.status != BTA_AV_STS_NO_RSP) {
1125     if (!p_pkt) {
1126       rc_rsp.rsp.opcode = p_data->rc_msg.opcode;
1127       AVRC_BldResponse(0, &rc_rsp, &p_pkt);
1128     }
1129     if (p_pkt)
1130       AVRC_MsgReq(p_data->rc_msg.handle, p_data->rc_msg.label, ctype, p_pkt,
1131                   false);
1132   }
1133 
1134   /* call callback */
1135   if (evt != 0) {
1136     av.remote_cmd.rc_handle = p_data->rc_msg.handle;
1137     (*p_cb->p_cback)(evt, &av);
1138     /* If browsing message, then free the browse message buffer */
1139     if (p_data->rc_msg.opcode == AVRC_OP_BROWSE &&
1140         p_data->rc_msg.msg.browse.p_browse_pkt != NULL) {
1141       bta_av_rc_free_browse_msg(p_cb, p_data);
1142     }
1143   }
1144 }
1145 
1146 /*******************************************************************************
1147  *
1148  * Function         bta_av_rc_close
1149  *
1150  * Description      close the specified AVRC handle.
1151  *
1152  * Returns          void
1153  *
1154  ******************************************************************************/
bta_av_rc_close(tBTA_AV_CB * p_cb,tBTA_AV_DATA * p_data)1155 void bta_av_rc_close(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) {
1156   uint16_t handle = p_data->hdr.layer_specific;
1157   tBTA_AV_SCB* p_scb;
1158   tBTA_AV_RCB* p_rcb;
1159 
1160   if (handle < BTA_AV_NUM_RCB) {
1161     p_rcb = &p_cb->rcb[handle];
1162 
1163     log::verbose("handle: {}, status=0x{:x}", p_rcb->handle, p_rcb->status);
1164     if (p_rcb->handle != BTA_AV_RC_HANDLE_NONE) {
1165       if (p_rcb->shdl) {
1166         p_scb = bta_av_cb.p_scb[p_rcb->shdl - 1];
1167         if (p_scb) {
1168           /* just in case the RC timer is active
1169           if (bta_av_cb.features & BTA_AV_FEAT_RCCT &&
1170              p_scb->chnl == BTA_AV_CHNL_AUDIO) */
1171           alarm_cancel(p_scb->avrc_ct_timer);
1172         }
1173       }
1174 
1175       AVRC_Close(p_rcb->handle);
1176     }
1177   }
1178 }
1179 
1180 /*******************************************************************************
1181  *
1182  * Function         bta_av_get_shdl
1183  *
1184  * Returns          The index to p_scb[]
1185  *
1186  ******************************************************************************/
bta_av_get_shdl(tBTA_AV_SCB * p_scb)1187 static uint8_t bta_av_get_shdl(tBTA_AV_SCB* p_scb) {
1188   int i;
1189   uint8_t shdl = 0;
1190   /* find the SCB & stop the timer */
1191   for (i = 0; i < BTA_AV_NUM_STRS; i++) {
1192     if (p_scb == bta_av_cb.p_scb[i]) {
1193       shdl = i + 1;
1194       break;
1195     }
1196   }
1197   return shdl;
1198 }
1199 
1200 /*******************************************************************************
1201  *
1202  * Function         bta_av_stream_chg
1203  *
1204  * Description      audio streaming status changed.
1205  *
1206  * Returns          void
1207  *
1208  ******************************************************************************/
bta_av_stream_chg(tBTA_AV_SCB * p_scb,bool started)1209 void bta_av_stream_chg(tBTA_AV_SCB* p_scb, bool started) {
1210   uint8_t started_msk = BTA_AV_HNDL_TO_MSK(p_scb->hdi);
1211 
1212   log::verbose("peer {} started:{} started_msk:0x{:x}", p_scb->PeerAddress(),
1213                started, started_msk);
1214 
1215   if (started) {
1216     /* Let L2CAP know this channel is processed with high priority */
1217     if (!L2CA_SetAclPriority(p_scb->PeerAddress(), L2CAP_PRIORITY_HIGH)) {
1218       log::warn("Unable to set L2CAP acl high priority peer:{}",
1219                 p_scb->PeerAddress());
1220     }
1221   } else {
1222     /* Let L2CAP know this channel is processed with low priority */
1223     if (!L2CA_SetAclPriority(p_scb->PeerAddress(), L2CAP_PRIORITY_NORMAL)) {
1224       log::warn("Unable to set L2CAP acl normal priority peer:{}",
1225                 p_scb->PeerAddress());
1226     }
1227   }
1228 }
1229 
1230 /*******************************************************************************
1231  *
1232  * Function         bta_av_conn_chg
1233  *
1234  * Description      connetion status changed.
1235  *                  Open an AVRCP acceptor channel, if new conn.
1236  *
1237  * Returns          void
1238  *
1239  ******************************************************************************/
bta_av_conn_chg(tBTA_AV_DATA * p_data)1240 void bta_av_conn_chg(tBTA_AV_DATA* p_data) {
1241   tBTA_AV_CB* p_cb = &bta_av_cb;
1242   tBTA_AV_SCB* p_scb = NULL;
1243   tBTA_AV_SCB* p_scbi;
1244   uint8_t mask;
1245   uint8_t conn_msk;
1246   uint8_t old_msk;
1247   int i;
1248   int index = (p_data->hdr.layer_specific & BTA_AV_HNDL_MSK) - 1;
1249   tBTA_AV_LCB* p_lcb;
1250   tBTA_AV_LCB* p_lcb_rc;
1251   tBTA_AV_RCB *p_rcb, *p_rcb2;
1252   bool chk_restore = false;
1253 
1254   /* Validate array index*/
1255   if (index < BTA_AV_NUM_STRS) {
1256     p_scb = p_cb->p_scb[index];
1257   }
1258   mask = BTA_AV_HNDL_TO_MSK(index);
1259   p_lcb = bta_av_find_lcb(p_data->conn_chg.peer_addr, BTA_AV_LCB_FIND);
1260   conn_msk = 1 << (index + 1);
1261   if (p_data->conn_chg.is_up) {
1262     /* set the conned mask for this channel */
1263     if (p_scb) {
1264       if (p_lcb) {
1265         p_lcb->conn_msk |= conn_msk;
1266         for (i = 0; i < BTA_AV_NUM_RCB; i++) {
1267           if (bta_av_cb.rcb[i].lidx == p_lcb->lidx) {
1268             bta_av_cb.rcb[i].shdl = index + 1;
1269             log::verbose("conn_chg up[{}]: {}, status=0x{:x}, shdl:{}, lidx:{}",
1270                          i, bta_av_cb.rcb[i].handle, bta_av_cb.rcb[i].status,
1271                          bta_av_cb.rcb[i].shdl, bta_av_cb.rcb[i].lidx);
1272             break;
1273           }
1274         }
1275       }
1276       old_msk = p_cb->conn_audio;
1277       p_cb->conn_audio |= mask;
1278 
1279       if ((old_msk & mask) == 0) {
1280         /* increase the audio open count, if not set yet */
1281         bta_av_cb.audio_open_cnt++;
1282       }
1283 
1284       log::verbose("rc_acp_handle:{} rc_acp_idx:{}", p_cb->rc_acp_handle,
1285                    p_cb->rc_acp_idx);
1286       /* check if the AVRCP ACP channel is already connected */
1287       if (p_lcb && p_cb->rc_acp_handle != BTA_AV_RC_HANDLE_NONE &&
1288           p_cb->rc_acp_idx) {
1289         p_lcb_rc = &p_cb->lcb[BTA_AV_NUM_LINKS];
1290         log::verbose(
1291             "rc_acp is connected && conn_chg on same addr "
1292             "p_lcb_rc->conn_msk:x{:x}",
1293             p_lcb_rc->conn_msk);
1294         /* check if the RC is connected to the scb addr */
1295         log::info("p_lcb_rc->addr: {} conn_chg.peer_addr: {}", p_lcb_rc->addr,
1296                   p_data->conn_chg.peer_addr);
1297 
1298         if (p_lcb_rc->conn_msk &&
1299             p_lcb_rc->addr == p_data->conn_chg.peer_addr) {
1300           /* AVRCP is already connected.
1301            * need to update the association betwen SCB and RCB */
1302           p_lcb_rc->conn_msk = 0; /* indicate RC ONLY is not connected */
1303           p_lcb_rc->lidx = 0;
1304           p_scb->rc_handle = p_cb->rc_acp_handle;
1305           p_rcb = &p_cb->rcb[p_cb->rc_acp_idx - 1];
1306           p_rcb->shdl = bta_av_get_shdl(p_scb);
1307           log::verbose("update rc_acp shdl:{}/{} srch:{}", index + 1,
1308                        p_rcb->shdl, p_scb->rc_handle);
1309 
1310           p_rcb2 = bta_av_get_rcb_by_shdl(p_rcb->shdl);
1311           if (p_rcb2) {
1312             /* found the RCB that was created to associated with this SCB */
1313             p_cb->rc_acp_handle = p_rcb2->handle;
1314             p_cb->rc_acp_idx = (p_rcb2 - p_cb->rcb) + 1;
1315             log::verbose("new rc_acp_handle:{}, idx:{}", p_cb->rc_acp_handle,
1316                          p_cb->rc_acp_idx);
1317             p_rcb2->lidx = (BTA_AV_NUM_LINKS + 1);
1318             log::verbose("rc2 handle:{} lidx:{}/{}", p_rcb2->handle,
1319                          p_rcb2->lidx, p_cb->lcb[p_rcb2->lidx - 1].lidx);
1320           }
1321           p_rcb->lidx = p_lcb->lidx;
1322           log::verbose("rc handle:{} lidx:{}/{}", p_rcb->handle, p_rcb->lidx,
1323                        p_cb->lcb[p_rcb->lidx - 1].lidx);
1324         }
1325       }
1326     }
1327   } else {
1328     if ((p_cb->conn_audio & mask) && bta_av_cb.audio_open_cnt) {
1329       /* this channel is still marked as open. decrease the count */
1330       bta_av_cb.audio_open_cnt--;
1331     }
1332 
1333     /* clear the conned mask for this channel */
1334     p_cb->conn_audio &= ~mask;
1335     if (p_scb) {
1336       // The stream is closed. Clear the state.
1337       p_scb->OnDisconnected();
1338       if (p_scb->chnl == BTA_AV_CHNL_AUDIO) {
1339         if (p_lcb) {
1340           p_lcb->conn_msk &= ~conn_msk;
1341         }
1342         /* audio channel is down. make sure the INT channel is down */
1343         /* just in case the RC timer is active
1344         if (p_cb->features & BTA_AV_FEAT_RCCT) */
1345         { alarm_cancel(p_scb->avrc_ct_timer); }
1346         /* one audio channel goes down. check if we need to restore high
1347          * priority */
1348         chk_restore = true;
1349       }
1350     }
1351 
1352     log::verbose("shdl:{}", index + 1);
1353     for (i = 0; i < BTA_AV_NUM_RCB; i++) {
1354       log::verbose("conn_chg dn[{}]: {}, status=0x{:x}, shdl:{}, lidx:{}", i,
1355                    bta_av_cb.rcb[i].handle, bta_av_cb.rcb[i].status,
1356                    bta_av_cb.rcb[i].shdl, bta_av_cb.rcb[i].lidx);
1357       if (bta_av_cb.rcb[i].shdl == index + 1) {
1358         bta_av_del_rc(&bta_av_cb.rcb[i]);
1359         /* since the connection is already down and info was removed, clean
1360          * reference */
1361         bta_av_cb.rcb[i].shdl = 0;
1362         break;
1363       }
1364     }
1365 
1366     if (p_cb->conn_audio == 0) {
1367       /* if both channels are not connected,
1368        * close all RC channels */
1369       bta_av_close_all_rc(p_cb);
1370     }
1371 
1372     /* if the AVRCP is no longer listening, create the listening channel */
1373     if (bta_av_cb.rc_acp_handle == BTA_AV_RC_HANDLE_NONE &&
1374         bta_av_cb.features & BTA_AV_FEAT_RCTG)
1375       bta_av_rc_create(&bta_av_cb, AVCT_ACP, 0, BTA_AV_NUM_LINKS + 1);
1376   }
1377 
1378   log::verbose(
1379       "audio:{:x} up:{} conn_msk:0x{:x} chk_restore:{} audio_open_cnt:{}",
1380       p_cb->conn_audio, p_data->conn_chg.is_up, conn_msk, chk_restore,
1381       p_cb->audio_open_cnt);
1382 
1383   if (chk_restore) {
1384     if (p_cb->audio_open_cnt == 1) {
1385       /* one audio channel goes down and there's one audio channel remains open.
1386        * restore the switch role in default link policy */
1387       BTM_default_unblock_role_switch();
1388       bta_av_restore_switch();
1389     }
1390     if (p_cb->audio_open_cnt) {
1391       /* adjust flush timeout settings to longer period */
1392       for (i = 0; i < BTA_AV_NUM_STRS; i++) {
1393         p_scbi = bta_av_cb.p_scb[i];
1394         if (p_scbi && p_scbi->chnl == BTA_AV_CHNL_AUDIO && p_scbi->co_started) {
1395           /* may need to update the flush timeout of this already started stream
1396            */
1397           if (p_scbi->co_started != bta_av_cb.audio_open_cnt) {
1398             p_scbi->co_started = bta_av_cb.audio_open_cnt;
1399           }
1400         }
1401       }
1402     }
1403   }
1404 }
1405 
1406 /*******************************************************************************
1407  *
1408  * Function         bta_av_disable
1409  *
1410  * Description      disable AV.
1411  *
1412  * Returns          void
1413  *
1414  ******************************************************************************/
bta_av_disable(tBTA_AV_CB * p_cb,tBTA_AV_DATA *)1415 void bta_av_disable(tBTA_AV_CB* p_cb, tBTA_AV_DATA* /* p_data */) {
1416   BT_HDR_RIGID hdr;
1417   bool disabling_in_progress = false;
1418   uint16_t xx;
1419 
1420   p_cb->disabling = true;
1421 
1422   bta_av_close_all_rc(p_cb);
1423 
1424   osi_free_and_reset((void**)&p_cb->p_disc_db);
1425 
1426   /* disable audio/video - de-register all channels,
1427    * expect BTA_AV_DEREG_COMP_EVT when deregister is complete */
1428   for (xx = 0; xx < BTA_AV_NUM_STRS; xx++) {
1429     if (p_cb->p_scb[xx] != NULL) {
1430       // Free signalling timers
1431       alarm_free(p_cb->p_scb[xx]->link_signalling_timer);
1432       p_cb->p_scb[xx]->link_signalling_timer = NULL;
1433       alarm_free(p_cb->p_scb[xx]->accept_signalling_timer);
1434       p_cb->p_scb[xx]->accept_signalling_timer = NULL;
1435 
1436       hdr.layer_specific = xx + 1;
1437       bta_av_api_deregister((tBTA_AV_DATA*)&hdr);
1438       disabling_in_progress = true;
1439     }
1440   }
1441   // Since All channels are deregistering by API_DEREGISTER, the DEREG_COMP_EVT
1442   // would come first before API_DISABLE if there is no connections, and it is
1443   // no needed to setup this disabling flag.
1444   p_cb->disabling = disabling_in_progress;
1445 }
1446 
1447 /*******************************************************************************
1448  *
1449  * Function         bta_av_api_disconnect
1450  *
1451  * Description      .
1452  *
1453  * Returns          void
1454  *
1455  ******************************************************************************/
bta_av_api_disconnect(tBTA_AV_DATA * p_data)1456 void bta_av_api_disconnect(tBTA_AV_DATA* p_data) {
1457   tBTA_AV_SCB* p_scb =
1458       bta_av_hndl_to_scb(p_data->api_discnt.hdr.layer_specific);
1459   AVDT_DisconnectReq(p_scb->PeerAddress(), bta_av_conn_cback);
1460   alarm_cancel(p_scb->link_signalling_timer);
1461 }
1462 
1463 /*******************************************************************************
1464  *
1465  * Function         bta_av_set_use_latency_mode
1466  *
1467  * Description      Sets stream use latency mode.
1468  *
1469  * Returns          void
1470  *
1471  ******************************************************************************/
bta_av_set_use_latency_mode(tBTA_AV_SCB * p_scb,bool use_latency_mode)1472 void bta_av_set_use_latency_mode(tBTA_AV_SCB* p_scb, bool use_latency_mode) {
1473   if (!L2CA_UseLatencyMode(p_scb->PeerAddress(), use_latency_mode)) {
1474     log::warn("Unable to set L2CAP latenty mode peer:{} use_latency_mode:{}",
1475               p_scb->PeerAddress(), use_latency_mode);
1476   }
1477 }
1478 
1479 /*******************************************************************************
1480  *
1481  * Function         bta_av_api_set_latency
1482  *
1483  * Description      set stream latency.
1484  *
1485  * Returns          void
1486  *
1487  ******************************************************************************/
bta_av_api_set_latency(tBTA_AV_DATA * p_data)1488 void bta_av_api_set_latency(tBTA_AV_DATA* p_data) {
1489   tBTA_AV_SCB* p_scb =
1490       bta_av_hndl_to_scb(p_data->api_set_latency.hdr.layer_specific);
1491 
1492   tL2CAP_LATENCY latency = p_data->api_set_latency.is_low_latency
1493                                ? L2CAP_LATENCY_LOW
1494                                : L2CAP_LATENCY_NORMAL;
1495   if (!L2CA_SetAclLatency(p_scb->PeerAddress(), latency)) {
1496     log::warn("Unable to set L2CAP latenty mode peer:{} use_latency_mode:{}",
1497               p_scb->PeerAddress(), latency);
1498   }
1499 }
1500 
1501 /**
1502  * Find the index for the free LCB entry to use.
1503  *
1504  * The selection order is:
1505  * (1) Find the index if there is already SCB entry for the peer address
1506  * (2) If there is no SCB entry for the peer address, find the first
1507  * SCB entry that is not assigned.
1508  *
1509  * @param peer_address the peer address to use
1510  * @return the index for the free LCB entry to use or BTA_AV_NUM_LINKS
1511  * if no entry is found
1512  */
bta_av_find_lcb_index_by_scb_and_address(const RawAddress & peer_address)1513 static uint8_t bta_av_find_lcb_index_by_scb_and_address(
1514     const RawAddress& peer_address) {
1515   log::verbose("peer_address: {} conn_lcb: 0x{:x}", peer_address,
1516                bta_av_cb.conn_lcb);
1517 
1518   // Find the index if there is already SCB entry for the peer address
1519   for (uint8_t index = 0; index < BTA_AV_NUM_LINKS; index++) {
1520     uint8_t mask = 1 << index;
1521     if (mask & bta_av_cb.conn_lcb) {
1522       continue;
1523     }
1524     tBTA_AV_SCB* p_scb = bta_av_cb.p_scb[index];
1525     if (p_scb == nullptr) {
1526       continue;
1527     }
1528     if (p_scb->PeerAddress() == peer_address) {
1529       return index;
1530     }
1531   }
1532 
1533   // Find the first SCB entry that is not assigned.
1534   for (uint8_t index = 0; index < BTA_AV_NUM_LINKS; index++) {
1535     uint8_t mask = 1 << index;
1536     if (mask & bta_av_cb.conn_lcb) {
1537       continue;
1538     }
1539     tBTA_AV_SCB* p_scb = bta_av_cb.p_scb[index];
1540     if (p_scb == nullptr) {
1541       continue;
1542     }
1543     if (!p_scb->IsAssigned()) {
1544       const RawAddress& btif_addr = btif_av_find_by_handle(p_scb->hndl);
1545       if (!btif_addr.IsEmpty() && btif_addr != peer_address) {
1546         log::debug("btif_addr = {}, index={}!", btif_addr, index);
1547         continue;
1548       }
1549       return index;
1550     }
1551   }
1552 
1553   return BTA_AV_NUM_LINKS;
1554 }
1555 
1556 /*******************************************************************************
1557  *
1558  * Function         bta_av_sig_chg
1559  *
1560  * Description      process AVDT signal channel up/down.
1561  *
1562  * Returns          void
1563  *
1564  ******************************************************************************/
bta_av_sig_chg(tBTA_AV_DATA * p_data)1565 void bta_av_sig_chg(tBTA_AV_DATA* p_data) {
1566   uint16_t event = p_data->str_msg.hdr.layer_specific;
1567   tBTA_AV_CB* p_cb = &bta_av_cb;
1568   uint32_t xx;
1569   uint8_t mask;
1570   tBTA_AV_LCB* p_lcb = NULL;
1571 
1572   log::verbose("event: {}", event);
1573   if (event == AVDT_CONNECT_IND_EVT) {
1574     log::verbose("AVDT_CONNECT_IND_EVT: peer {}", p_data->str_msg.bd_addr);
1575 
1576     p_lcb = bta_av_find_lcb(p_data->str_msg.bd_addr, BTA_AV_LCB_FIND);
1577     if (!p_lcb) {
1578       /* if the address does not have an LCB yet, alloc one */
1579       xx = bta_av_find_lcb_index_by_scb_and_address(p_data->str_msg.bd_addr);
1580 
1581       /* check if we found something */
1582       if (xx >= BTA_AV_NUM_LINKS) {
1583         /* We do not have scb for this avdt connection.     */
1584         /* Silently close the connection.                   */
1585         log::error("av scb not available for avdt connection for {}",
1586                    p_data->str_msg.bd_addr);
1587         AVDT_DisconnectReq(p_data->str_msg.bd_addr, NULL);
1588         return;
1589       }
1590       log::info("AVDT_CONNECT_IND_EVT: peer {} selected lcb_index {}",
1591                 p_data->str_msg.bd_addr, xx);
1592 
1593       tBTA_AV_SCB* p_scb = p_cb->p_scb[xx];
1594       mask = 1 << xx;
1595       p_lcb = &p_cb->lcb[xx];
1596       p_lcb->lidx = xx + 1;
1597       p_lcb->addr = p_data->str_msg.bd_addr;
1598       p_lcb->conn_msk = 0; /* clear the connect mask */
1599       /* start listening when the signal channel is open */
1600       if (p_cb->features & BTA_AV_FEAT_RCTG) {
1601         bta_av_rc_create(p_cb, AVCT_ACP, 0, p_lcb->lidx);
1602       }
1603       /* this entry is not used yet. */
1604       p_cb->conn_lcb |= mask; /* mark it as used */
1605       log::verbose("start sig timer {}", p_data->hdr.offset);
1606       if (p_data->hdr.offset == AVDT_ACP) {
1607         log::verbose("Incoming L2CAP acquired, set state as incoming");
1608         p_scb->OnConnected(p_data->str_msg.bd_addr);
1609         p_scb->use_rc = true; /* allowing RC for incoming connection */
1610         bta_av_ssm_execute(p_scb, BTA_AV_ACP_CONNECT_EVT, p_data);
1611 
1612         /* The Pending Event should be sent as soon as the L2CAP signalling
1613          * channel
1614          * is set up, which is NOW. Earlier this was done only after
1615          * BTA_AV_SIGNALLING_TIMEOUT_MS.
1616          * The following function shall send the event and start the
1617          * recurring timer
1618          */
1619         if (!p_scb->link_signalling_timer) {
1620           p_scb->link_signalling_timer = alarm_new("link_signalling_timer");
1621         }
1622         BT_HDR hdr;
1623         hdr.layer_specific = p_scb->hndl;
1624         bta_av_signalling_timer((tBTA_AV_DATA*)&hdr);
1625 
1626         log::verbose("Re-start timer for AVDTP service");
1627         bta_sys_conn_open(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress());
1628         /* Possible collision : need to avoid outgoing processing while the
1629          * timer is running */
1630         p_scb->coll_mask = BTA_AV_COLL_INC_TMR;
1631         if (!p_scb->accept_signalling_timer) {
1632           p_scb->accept_signalling_timer = alarm_new("accept_signalling_timer");
1633         }
1634         alarm_set_on_mloop(
1635             p_scb->accept_signalling_timer, BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS,
1636             bta_av_accept_signalling_timer_cback, UINT_TO_PTR(xx));
1637       }
1638     }
1639   }
1640   else if (event == BTA_AR_AVDT_CONN_EVT) {
1641     uint8_t scb_index = p_data->str_msg.scb_index;
1642     alarm_cancel(p_cb->p_scb[scb_index]->link_signalling_timer);
1643   }
1644   else {
1645     /* disconnected. */
1646     log::verbose("bta_av_cb.conn_lcb=0x{:x}", bta_av_cb.conn_lcb);
1647 
1648     p_lcb = bta_av_find_lcb(p_data->str_msg.bd_addr, BTA_AV_LCB_FREE);
1649     if (p_lcb && (p_lcb->conn_msk || bta_av_cb.conn_lcb)) {
1650       log::verbose("conn_msk: 0x{:x}", p_lcb->conn_msk);
1651       /* clean up ssm  */
1652       for (xx = 0; xx < BTA_AV_NUM_STRS; xx++) {
1653         if (p_cb->p_scb[xx] &&
1654             p_cb->p_scb[xx]->PeerAddress() == p_data->str_msg.bd_addr) {
1655           if ((p_cb->p_scb[xx]->state == 1) &&
1656               alarm_is_scheduled(p_cb->p_scb[xx]->accept_signalling_timer) &&
1657               interop_match_addr(INTEROP_IGNORE_DISC_BEFORE_SIGNALLING_TIMEOUT,
1658                 &(p_data->str_msg.bd_addr))) {
1659             continue;
1660           }
1661           log::verbose("Closing timer for AVDTP service");
1662           bta_sys_conn_close(BTA_ID_AV, p_cb->p_scb[xx]->app_id,
1663                              p_cb->p_scb[xx]->PeerAddress());
1664         }
1665         mask = 1 << (xx + 1);
1666         if (((mask & p_lcb->conn_msk) || bta_av_cb.conn_lcb) &&
1667             p_cb->p_scb[xx] &&
1668             p_cb->p_scb[xx]->PeerAddress() == p_data->str_msg.bd_addr) {
1669           log::warn("Sending AVDT_DISCONNECT_EVT peer_addr={}",
1670                     p_cb->p_scb[xx]->PeerAddress());
1671           bta_av_ssm_execute(p_cb->p_scb[xx], BTA_AV_AVDT_DISCONNECT_EVT, NULL);
1672         }
1673       }
1674     }
1675   }
1676   log::verbose("bta_av_cb.conn_lcb=0x{:x} after sig_chg", p_cb->conn_lcb);
1677 }
1678 
1679 /*******************************************************************************
1680  *
1681  * Function         bta_av_signalling_timer
1682  *
1683  * Description      process the signal channel timer. This timer is started
1684  *                  when the AVDTP signal channel is connected. If no profile
1685  *                  is connected, the timer goes off every
1686  *                  BTA_AV_SIGNALLING_TIMEOUT_MS.
1687  *
1688  * Returns          void
1689  *
1690  ******************************************************************************/
bta_av_signalling_timer(tBTA_AV_DATA * p_data)1691 void bta_av_signalling_timer(tBTA_AV_DATA* p_data) {
1692   tBTA_AV_HNDL hndl = p_data->hdr.layer_specific;
1693   tBTA_AV_SCB* p_scb = bta_av_hndl_to_scb(hndl);
1694 
1695   tBTA_AV_CB* p_cb = &bta_av_cb;
1696   int xx;
1697   uint8_t mask;
1698   tBTA_AV_LCB* p_lcb = NULL;
1699 
1700   log::verbose("conn_lcb=0x{:x}", p_cb->conn_lcb);
1701   for (xx = 0; xx < BTA_AV_NUM_LINKS; xx++) {
1702     p_lcb = &p_cb->lcb[xx];
1703     mask = 1 << xx;
1704     log::verbose("index={} conn_lcb=0x{:x} peer={} conn_mask=0x{:x} lidx={}",
1705                  xx, p_cb->conn_lcb, p_lcb->addr, p_lcb->conn_msk, p_lcb->lidx);
1706     if (mask & p_cb->conn_lcb) {
1707       /* this entry is used. check if it is connected */
1708       if (!p_lcb->conn_msk) {
1709         log::verbose("hndl 0x{:x}", p_scb->hndl);
1710         bta_sys_start_timer(p_scb->link_signalling_timer,
1711                             BTA_AV_SIGNALLING_TIMEOUT_MS,
1712                             BTA_AV_SIGNALLING_TIMER_EVT, hndl);
1713         tBTA_AV_PEND pend;
1714         pend.bd_addr = p_lcb->addr;
1715         tBTA_AV bta_av_data;
1716         bta_av_data.pend = pend;
1717         log::verbose(
1718             "BTA_AV_PENDING_EVT for {} index={} conn_mask=0x{:x} lidx={}",
1719             pend.bd_addr, xx, p_lcb->conn_msk, p_lcb->lidx);
1720         (*p_cb->p_cback)(BTA_AV_PENDING_EVT, &bta_av_data);
1721       }
1722     }
1723   }
1724 }
1725 
1726 /*******************************************************************************
1727  *
1728  * Function         bta_av_accept_signalling_timer_cback
1729  *
1730  * Description      Process the timeout when SRC is accepting connection
1731  *                  and SNK did not start signalling.
1732  *
1733  * Returns          void
1734  *
1735  ******************************************************************************/
bta_av_accept_signalling_timer_cback(void * data)1736 static void bta_av_accept_signalling_timer_cback(void* data) {
1737   uint32_t inx = PTR_TO_UINT(data);
1738   tBTA_AV_CB* p_cb = &bta_av_cb;
1739   tBTA_AV_SCB* p_scb = NULL;
1740   if (inx < BTA_AV_NUM_STRS) {
1741     p_scb = p_cb->p_scb[inx];
1742   }
1743   if (p_scb) {
1744     log::verbose("coll_mask=0x{:02x}", p_scb->coll_mask);
1745 
1746     if (p_scb->coll_mask & BTA_AV_COLL_INC_TMR) {
1747       p_scb->coll_mask &= ~BTA_AV_COLL_INC_TMR;
1748 
1749       if (bta_av_is_scb_opening(p_scb)) {
1750         log::verbose("stream state opening: SDP started = {}",
1751                      p_scb->sdp_discovery_started);
1752         if (p_scb->sdp_discovery_started) {
1753           /* We are still doing SDP. Run the timer again. */
1754           p_scb->coll_mask |= BTA_AV_COLL_INC_TMR;
1755 
1756           alarm_set_on_mloop(p_scb->accept_signalling_timer,
1757                              BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS,
1758                              bta_av_accept_signalling_timer_cback,
1759                              UINT_TO_PTR(inx));
1760         } else {
1761           /* SNK did not start signalling, resume signalling process. */
1762           bta_av_discover_req(p_scb, NULL);
1763         }
1764       } else if (bta_av_is_scb_incoming(p_scb)) {
1765         /* Stay in incoming state if SNK does not start signalling */
1766 
1767         log::verbose("stream state incoming");
1768         /* API open was called right after SNK opened L2C connection. */
1769         if (p_scb->coll_mask & BTA_AV_COLL_API_CALLED) {
1770           p_scb->coll_mask &= ~BTA_AV_COLL_API_CALLED;
1771 
1772           /* BTA_AV_API_OPEN_EVT */
1773           tBTA_AV_API_OPEN* p_buf =
1774               (tBTA_AV_API_OPEN*)osi_malloc(sizeof(tBTA_AV_API_OPEN));
1775           memcpy(p_buf, &(p_scb->open_api), sizeof(tBTA_AV_API_OPEN));
1776           bta_sys_sendmsg(p_buf);
1777         }
1778       }
1779     }
1780   }
1781 }
1782 
bta_av_store_peer_rc_version()1783 static void bta_av_store_peer_rc_version() {
1784   tBTA_AV_CB* p_cb = &bta_av_cb;
1785   tSDP_DISC_REC* p_rec = NULL;
1786   uint16_t peer_rc_version = 0; /*Assuming Default peer version as 1.3*/
1787 
1788   if ((p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
1789            p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL)) != NULL) {
1790     if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
1791             p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) {
1792       /* get profile version (if failure, version parameter is not updated) */
1793       if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(
1794               p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) {
1795         log::warn("Unable to find AVRC profile version in record peer:{}",
1796                   p_rec->remote_bd_addr);
1797       }
1798     }
1799     if (peer_rc_version != 0)
1800       DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(
1801           p_rec->remote_bd_addr, IOT_CONF_KEY_AVRCP_CTRL_VERSION,
1802           peer_rc_version, IOT_CONF_BYTE_NUM_2);
1803   }
1804 
1805   peer_rc_version = 0;
1806   if ((p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
1807            p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL)) != NULL) {
1808     if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
1809             p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) {
1810       /* get profile version (if failure, version parameter is not updated) */
1811       if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(
1812               p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) {
1813         log::warn("Unable to find SDP profile version in record peer:{}",
1814                   p_rec->remote_bd_addr);
1815       }
1816     }
1817     if (peer_rc_version != 0)
1818       DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(
1819           p_rec->remote_bd_addr, IOT_CONF_KEY_AVRCP_TG_VERSION, peer_rc_version,
1820           IOT_CONF_BYTE_NUM_2);
1821   }
1822 }
1823 
1824 /*******************************************************************************
1825  *
1826  * Function         bta_av_check_peer_features
1827  *
1828  * Description      check supported features on the peer device from the SDP
1829  *                  record and return the feature mask
1830  *
1831  * Returns          tBTA_AV_FEAT peer device feature mask
1832  *
1833  ******************************************************************************/
bta_av_check_peer_features(uint16_t service_uuid)1834 tBTA_AV_FEAT bta_av_check_peer_features(uint16_t service_uuid) {
1835   tBTA_AV_FEAT peer_features = 0;
1836   tBTA_AV_CB* p_cb = &bta_av_cb;
1837   tSDP_DISC_REC* p_rec = NULL;
1838   tSDP_DISC_ATTR* p_attr;
1839   uint16_t peer_rc_version = 0;
1840   uint16_t categories = 0;
1841 
1842   log::verbose("service_uuid:x{:x}", service_uuid);
1843   /* loop through all records we found */
1844   while (true) {
1845     /* get next record; if none found, we're done */
1846     p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
1847         p_cb->p_disc_db, service_uuid, p_rec);
1848     if (p_rec == NULL) {
1849       break;
1850     }
1851 
1852     if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
1853             p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST)) != NULL) {
1854       /* find peer features */
1855       if (get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
1856               p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL)) {
1857         peer_features |= BTA_AV_FEAT_RCCT;
1858       }
1859       if (get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
1860               p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL)) {
1861         peer_features |= BTA_AV_FEAT_RCTG;
1862       }
1863     }
1864 
1865     if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
1866             p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) {
1867       /* get profile version (if failure, version parameter is not updated) */
1868       if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(
1869               p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) {
1870         log::warn("Unable to find AVRC profile version in record peer:{}",
1871                   p_rec->remote_bd_addr);
1872       }
1873       log::verbose("peer_rc_version 0x{:x}", peer_rc_version);
1874 
1875       if (peer_rc_version >= AVRC_REV_1_3)
1876         peer_features |= (BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_METADATA);
1877 
1878       if (peer_rc_version >= AVRC_REV_1_4) {
1879         /* get supported categories */
1880         p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
1881             p_rec, ATTR_ID_SUPPORTED_FEATURES);
1882         if (p_attr != NULL &&
1883             SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE &&
1884             SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) {
1885           categories = p_attr->attr_value.v.u16;
1886           if (categories & AVRC_SUPF_CT_CAT2)
1887             peer_features |= (BTA_AV_FEAT_ADV_CTRL);
1888           if (categories & AVRC_SUPF_CT_BROWSE)
1889             peer_features |= (BTA_AV_FEAT_BROWSE);
1890         }
1891       }
1892     }
1893   }
1894   log::verbose("peer_features:x{:x}", peer_features);
1895   return peer_features;
1896 }
1897 
1898 /*******************************************************************************
1899  *
1900  * Function         bta_avk_check_peer_features
1901  *
1902  * Description      check supported features on the peer device from the SDP
1903  *                  record and return the feature mask
1904  *
1905  * Returns          tBTA_AV_FEAT peer device feature mask
1906  *
1907  ******************************************************************************/
bta_avk_check_peer_features(uint16_t service_uuid)1908 tBTA_AV_FEAT bta_avk_check_peer_features(uint16_t service_uuid) {
1909   tBTA_AV_FEAT peer_features = 0;
1910   tBTA_AV_CB* p_cb = &bta_av_cb;
1911 
1912   log::verbose("service_uuid:x{:x}", service_uuid);
1913 
1914   /* loop through all records we found */
1915   tSDP_DISC_REC* p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
1916       p_cb->p_disc_db, service_uuid, NULL);
1917   while (p_rec) {
1918     log::verbose("found Service record for x{:x}", service_uuid);
1919 
1920     if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
1921             p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST)) != NULL) {
1922       /* find peer features */
1923       if (get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
1924               p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL)) {
1925         peer_features |= BTA_AV_FEAT_RCCT;
1926       }
1927       if (get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
1928               p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL)) {
1929         peer_features |= BTA_AV_FEAT_RCTG;
1930       }
1931     }
1932 
1933     if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
1934             p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) {
1935       /* get profile version (if failure, version parameter is not updated) */
1936       uint16_t peer_rc_version = 0;
1937       bool val = get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(
1938           p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version);
1939       log::verbose("peer_rc_version for TG 0x{:x}, profile_found {}",
1940                    peer_rc_version, val);
1941 
1942       if (peer_rc_version >= AVRC_REV_1_3)
1943         peer_features |= (BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_METADATA);
1944 
1945       /* Get supported features */
1946       tSDP_DISC_ATTR* p_attr =
1947           get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
1948               p_rec, ATTR_ID_SUPPORTED_FEATURES);
1949       if (p_attr != NULL &&
1950           SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE &&
1951           SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) {
1952         uint16_t categories = p_attr->attr_value.v.u16;
1953         /*
1954          * Though Absolute Volume came after in 1.4 and above, but there are
1955          * few devices in market which supports absolute Volume and they are
1956          * still 1.3. To avoid IOP issuses with those devices, we check for
1957          * 1.3 as minimum version
1958          */
1959         if (peer_rc_version >= AVRC_REV_1_3) {
1960           if (categories & AVRC_SUPF_TG_CAT2)
1961             peer_features |= (BTA_AV_FEAT_ADV_CTRL);
1962           if (categories & AVRC_SUPF_TG_APP_SETTINGS)
1963             peer_features |= (BTA_AV_FEAT_APP_SETTING);
1964           if (categories & AVRC_SUPF_TG_BROWSE)
1965             peer_features |= (BTA_AV_FEAT_BROWSE);
1966         }
1967 
1968         /* AVRCP Cover Artwork over BIP */
1969         if (peer_rc_version >= AVRC_REV_1_6) {
1970           if (service_uuid == UUID_SERVCLASS_AV_REM_CTRL_TARGET &&
1971               categories & AVRC_SUPF_TG_PLAYER_COVER_ART)
1972             peer_features |= (BTA_AV_FEAT_COVER_ARTWORK);
1973         }
1974       }
1975     }
1976     /* get next record; if none found, we're done */
1977     p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
1978         p_cb->p_disc_db, service_uuid, p_rec);
1979   }
1980   log::verbose("peer_features:x{:x}", peer_features);
1981   return peer_features;
1982 }
1983 
1984 /******************************************************************************
1985  *
1986  * Function         bta_avk_get_cover_art_psm
1987  *
1988  * Description      Get the PSM associated with the AVRCP Target cover art
1989  *                  feature
1990  *
1991  * Returns          uint16_t PSM value used to get cover artwork, or 0x0000 if
1992  *                  one does not exist.
1993  *
1994  *****************************************************************************/
bta_avk_get_cover_art_psm()1995 uint16_t bta_avk_get_cover_art_psm() {
1996   log::verbose("searching for cover art psm");
1997   /* Cover Art L2CAP PSM is only available on a target device */
1998   tBTA_AV_CB* p_cb = &bta_av_cb;
1999   tSDP_DISC_REC* p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
2000       p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL);
2001   while (p_rec) {
2002     tSDP_DISC_ATTR* p_attr =
2003         (get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
2004             p_rec, ATTR_ID_ADDITION_PROTO_DESC_LISTS));
2005     /*
2006      * If we have the Additional Protocol Description Lists attribute then we
2007      * specifically want the list that is an L2CAP protocol leading to OBEX.
2008      * Because the is a case where cover art is supported and browsing isn't
2009      * we need to check each list for the one we want.
2010      *
2011      * This means we need to do drop down into the protocol list and do a
2012      * "for each protocol, for each protocol element, for each protocol element
2013      * list parameter, if the parameter is L2CAP then find the PSM associated
2014      * with it, then make sure we see OBEX in that same protocol"
2015      */
2016     if (p_attr != NULL && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type)
2017         == DATA_ELE_SEQ_DESC_TYPE) {
2018       // Point to first in List of protocols (i.e [(L2CAP -> AVCTP),
2019       // (L2CAP -> OBEX)])
2020       tSDP_DISC_ATTR* p_protocol_list = p_attr->attr_value.v.p_sub_attr;
2021       while (p_protocol_list != NULL) {
2022         if (SDP_DISC_ATTR_TYPE(p_protocol_list->attr_len_type)
2023             == DATA_ELE_SEQ_DESC_TYPE) {
2024           // Point to fist in list of protocol elements (i.e. [L2CAP, AVCTP])
2025           tSDP_DISC_ATTR* p_protocol =
2026               p_protocol_list->attr_value.v.p_sub_attr;
2027           bool protocol_has_obex = false;
2028           bool protocol_has_l2cap = false;
2029           uint16_t psm = 0x0000;
2030           while (p_protocol) {
2031             if (SDP_DISC_ATTR_TYPE(p_protocol->attr_len_type)
2032                 == DATA_ELE_SEQ_DESC_TYPE) {
2033               // Point to first item protocol parameters list (i.e [UUID=L2CAP,
2034               // PSM=0x1234])
2035               tSDP_DISC_ATTR* p_protocol_param =
2036                   p_protocol->attr_value.v.p_sub_attr;
2037               /*
2038                * Currently there's only ever one UUID and one parameter. L2cap
2039                * has a single PSM, AVCTP has a version and OBEX has nothing.
2040                * Change this if that ever changes.
2041                */
2042               uint16_t protocol_uuid = 0;
2043               uint16_t protocol_param = 0;
2044               while (p_protocol_param) {
2045                 uint16_t param_type =
2046                     SDP_DISC_ATTR_TYPE(p_protocol_param->attr_len_type);
2047                 uint16_t param_len =
2048                     SDP_DISC_ATTR_LEN(p_protocol_param->attr_len_type);
2049                 if (param_type == UUID_DESC_TYPE) {
2050                   protocol_uuid = p_protocol_param->attr_value.v.u16;
2051                 } else if (param_type == UINT_DESC_TYPE) {
2052                     protocol_param = (param_len == 2)
2053                       ? p_protocol_param->attr_value.v.u16
2054                       : p_protocol_param->attr_value.v.u8;
2055                 } /* else dont care */
2056                 p_protocol_param = p_protocol_param->p_next_attr;  // next
2057               }
2058               // If we've found L2CAP then the parameter is a PSM
2059               if (protocol_uuid == UUID_PROTOCOL_L2CAP) {
2060                 protocol_has_l2cap = true;
2061                 psm = protocol_param;
2062               } else if (protocol_uuid == UUID_PROTOCOL_OBEX) {
2063                 protocol_has_obex = true;
2064               }
2065             }
2066             // If this protocol has l2cap and obex then we're found the BIP PSM
2067             if (protocol_has_l2cap && protocol_has_obex) {
2068               log::verbose("found psm 0x{:x}", psm);
2069               return psm;
2070             }
2071             p_protocol = p_protocol->p_next_attr;  // next protocol element
2072           }
2073         }
2074         p_protocol_list = p_protocol_list->p_next_attr;  // next protocol
2075       }
2076     }
2077     /* get next record; if none found, we're done */
2078     p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
2079         p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, p_rec);
2080   }
2081   /* L2CAP PSM range is 0x1000-0xFFFF so 0x0000 is safe default invalid */
2082   log::verbose("could not find a BIP psm");
2083   return 0x0000;
2084 }
2085 
bta_av_rc_disc_done_all(tBTA_AV_DATA *)2086 void bta_av_rc_disc_done_all(tBTA_AV_DATA* /* p_data */) {
2087   tBTA_AV_CB* p_cb = &bta_av_cb;
2088   tBTA_AV_SCB* p_scb = NULL;
2089   tBTA_AV_LCB* p_lcb;
2090   uint8_t rc_handle = BTA_AV_RC_HANDLE_NONE;
2091   tBTA_AV_FEAT peer_tg_features = 0;
2092   tBTA_AV_FEAT peer_ct_features = 0;
2093   uint16_t cover_art_psm = 0x0000;
2094 
2095   log::verbose("bta_av_rc_disc_done disc:x{:x}", p_cb->disc);
2096   if (!p_cb->disc) {
2097     return;
2098   }
2099 
2100   if ((p_cb->disc & BTA_AV_CHNL_MSK) == BTA_AV_CHNL_MSK) {
2101     /* this is the rc handle/index to tBTA_AV_RCB */
2102     rc_handle = p_cb->disc & (~BTA_AV_CHNL_MSK);
2103     log::error("WRONG MASK A2dp not connect");
2104   } else {
2105     /* Validate array index*/
2106     if (((p_cb->disc & BTA_AV_HNDL_MSK) - 1) < BTA_AV_NUM_STRS) {
2107       log::verbose("wrong data bta_av_rc_disc_done disc:x{:x}", p_cb->disc);
2108       p_scb = p_cb->p_scb[(p_cb->disc & BTA_AV_HNDL_MSK) - 1];
2109     }
2110     if (p_scb) {
2111       rc_handle = p_scb->rc_handle;
2112     } else {
2113       p_cb->disc = 0;
2114       return;
2115     }
2116   }
2117 
2118   log::verbose("rc_handle {}", rc_handle);
2119   if (p_cb->sdp_a2dp_snk_handle) {
2120     /* This is Sink + CT + TG(Abs Vol) */
2121     peer_tg_features =
2122         bta_avk_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET);
2123     log::verbose("populating rem ctrl target features {}", peer_tg_features);
2124     if (BTA_AV_FEAT_ADV_CTRL &
2125         bta_avk_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL))
2126       peer_tg_features |= (BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_RCCT);
2127 
2128     if (peer_tg_features & BTA_AV_FEAT_COVER_ARTWORK)
2129       cover_art_psm = bta_avk_get_cover_art_psm();
2130 
2131     log::verbose("populating rem ctrl target bip psm 0x{:x}", cover_art_psm);
2132   } else if (p_cb->sdp_a2dp_handle) {
2133     /* check peer version and whether support CT and TG role */
2134     peer_ct_features =
2135         bta_av_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL);
2136     if ((p_cb->features & BTA_AV_FEAT_ADV_CTRL) &&
2137         ((peer_ct_features & BTA_AV_FEAT_ADV_CTRL) == 0)) {
2138       /* if we support advance control and peer does not, check their support on
2139        * TG role
2140        * some implementation uses 1.3 on CT ans 1.4 on TG */
2141       peer_ct_features |=
2142           bta_av_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET);
2143     }
2144 
2145     /* Change our features if the remote AVRCP version is 1.3 or less */
2146     tSDP_DISC_REC* p_rec = nullptr;
2147     p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
2148         p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, p_rec);
2149     if (p_rec != NULL &&
2150         get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
2151             p_rec, ATTR_ID_BT_PROFILE_DESC_LIST) != NULL) {
2152       /* get profile version (if failure, version parameter is not updated) */
2153       uint16_t peer_rc_version = 0xFFFF;  // Don't change the AVRCP version
2154       if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(
2155               p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) {
2156         log::warn("Unable to find SDP in record peer:{}",
2157                   p_rec->remote_bd_addr);
2158       }
2159       if (peer_rc_version <= AVRC_REV_1_3) {
2160         log::verbose("Using AVRCP 1.3 Capabilities with remote device");
2161         p_bta_av_cfg = &bta_av_cfg_compatibility;
2162       }
2163     }
2164   }
2165 
2166   p_cb->disc = 0;
2167   osi_free_and_reset((void**)&p_cb->p_disc_db);
2168   p_cb->rc_feature.peer_ct_features = peer_ct_features;
2169   p_cb->rc_feature.peer_tg_features = peer_tg_features;
2170   p_cb->rc_feature.rc_handle = rc_handle;
2171   if (p_scb) p_cb->rc_feature.peer_addr = p_scb->PeerAddress();
2172 
2173   log::verbose(
2174       "peer_tg_features 0x{:x}, peer_ct_features 0x{:x}, features 0x{:x}",
2175       peer_tg_features, peer_ct_features, p_cb->features);
2176 
2177   /* if we have no rc connection */
2178   if (rc_handle == BTA_AV_RC_HANDLE_NONE) {
2179     if (p_scb) {
2180       /* if peer remote control service matches ours and USE_RC is true */
2181       if ((((p_cb->features & BTA_AV_FEAT_RCCT) &&
2182             (peer_tg_features & BTA_AV_FEAT_RCTG)) ||
2183            ((p_cb->features & BTA_AV_FEAT_RCTG) &&
2184             (peer_ct_features & BTA_AV_FEAT_RCCT)))) {
2185         p_lcb = bta_av_find_lcb(p_scb->PeerAddress(), BTA_AV_LCB_FIND);
2186         if (p_lcb) {
2187           rc_handle = bta_av_rc_create(p_cb, AVCT_INT,
2188                                        (uint8_t)(p_scb->hdi + 1), p_lcb->lidx);
2189           if (rc_handle != BTA_AV_RC_HANDLE_NONE) {
2190             p_cb->rcb[rc_handle].peer_ct_features = peer_ct_features;
2191             p_cb->rcb[rc_handle].peer_tg_features = peer_tg_features;
2192             p_cb->rcb[rc_handle].peer_features = 0;
2193             p_cb->rcb[rc_handle].cover_art_psm = cover_art_psm;
2194           } else {
2195             /* cannot create valid rc_handle for current device. report failure
2196              */
2197             log::error("no link resources available");
2198             p_scb->use_rc = false;
2199             tBTA_AV bta_av_data = {
2200                 .rc_open =
2201                     {
2202                         .peer_addr = p_scb->PeerAddress(),
2203                         .status = BTA_AV_FAIL_RESOURCES,
2204                     },
2205             };
2206             (*p_cb->p_cback)(BTA_AV_RC_OPEN_EVT, &bta_av_data);
2207           }
2208         } else {
2209           log::error("can not find LCB!!");
2210         }
2211       } else if (p_scb->use_rc) {
2212         /* can not find AVRC on peer device. report failure */
2213         p_scb->use_rc = false;
2214         tBTA_AV bta_av_data = {
2215             .rc_open =
2216                 {
2217                     .peer_ct_features = peer_ct_features,
2218                     .peer_tg_features = peer_tg_features,
2219                     .peer_addr = p_scb->PeerAddress(),
2220                     .status = BTA_AV_FAIL_SDP,
2221                 },
2222         };
2223         (*p_cb->p_cback)(BTA_AV_RC_OPEN_EVT, &bta_av_data);
2224       }
2225     }
2226   } else {
2227     p_cb->rcb[rc_handle].peer_ct_features = peer_ct_features;
2228     p_cb->rcb[rc_handle].peer_tg_features = peer_tg_features;
2229     p_cb->rcb[rc_handle].peer_features = 0;
2230 
2231     RawAddress peer_addr = RawAddress::kEmpty;
2232     if (p_scb == NULL) {
2233       /*
2234        * In case scb is not created by the time we are done with SDP
2235        * we still need to send RC feature event. So we need to get BD
2236        * from Message.  Note that lidx is 1 based not 0 based
2237        */
2238       if (p_cb->rcb[rc_handle].lidx > 0)
2239         peer_addr = p_cb->lcb[p_cb->rcb[rc_handle].lidx - 1].addr;
2240       else
2241         peer_addr = p_cb->lcb[p_cb->rcb[rc_handle].lidx].addr;
2242     } else {
2243       peer_addr = p_scb->PeerAddress();
2244     }
2245 
2246     tBTA_AV bta_av_feat = {.rc_feat = {
2247                                .rc_handle = rc_handle,
2248                                .peer_ct_features = peer_ct_features,
2249                                .peer_tg_features = peer_tg_features,
2250                                .peer_addr = peer_addr,
2251                            }};
2252     (*p_cb->p_cback)(BTA_AV_RC_FEAT_EVT, &bta_av_feat);
2253 
2254     // Send PSM data
2255     log::verbose("Send PSM data. rc_psm = {:#x}", cover_art_psm);
2256     p_cb->rcb[rc_handle].cover_art_psm = cover_art_psm;
2257     tBTA_AV bta_av_psm = {
2258         .rc_cover_art_psm =
2259             {
2260                 .rc_handle = rc_handle,
2261                 .cover_art_psm = cover_art_psm,
2262                 .peer_addr = peer_addr,
2263             },
2264     };
2265     (*p_cb->p_cback)(BTA_AV_RC_PSM_EVT, &bta_av_psm);
2266   }
2267 }
2268 
2269 /*******************************************************************************
2270  *
2271  * Function         bta_av_rc_disc_done
2272  *
2273  * Description      Handle AVRCP service discovery results.  If matching
2274  *                  service found, open AVRCP connection.
2275  *
2276  * Returns          void
2277  *
2278  ******************************************************************************/
bta_av_rc_disc_done(tBTA_AV_DATA * p_data)2279 void bta_av_rc_disc_done(tBTA_AV_DATA* p_data) {
2280   tBTA_AV_CB* p_cb = &bta_av_cb;
2281   tBTA_AV_SCB* p_scb = NULL;
2282   tBTA_AV_LCB* p_lcb;
2283   uint8_t rc_handle;
2284   tBTA_AV_FEAT peer_features = 0; /* peer features mask */
2285   uint16_t cover_art_psm = 0x0000;
2286 
2287   if (btif_av_both_enable()) {
2288     bta_av_rc_disc_done_all(p_data);
2289     return;
2290   }
2291 
2292   log::verbose("bta_av_rc_disc_done disc:x{:x}", p_cb->disc);
2293   if (!p_cb->disc) {
2294     return;
2295   }
2296 
2297   if ((p_cb->disc & BTA_AV_CHNL_MSK) == BTA_AV_CHNL_MSK) {
2298     /* this is the rc handle/index to tBTA_AV_RCB */
2299     rc_handle = p_cb->disc & (~BTA_AV_CHNL_MSK);
2300   } else {
2301     /* Validate array index*/
2302     if (((p_cb->disc & BTA_AV_HNDL_MSK) - 1) < BTA_AV_NUM_STRS) {
2303       p_scb = p_cb->p_scb[(p_cb->disc & BTA_AV_HNDL_MSK) - 1];
2304     }
2305     if (p_scb) {
2306       rc_handle = p_scb->rc_handle;
2307     } else {
2308       p_cb->disc = 0;
2309       return;
2310     }
2311   }
2312 
2313   log::verbose("rc_handle {}", rc_handle);
2314   if (p_cb->sdp_a2dp_snk_handle) {
2315     /* This is Sink + CT + TG(Abs Vol) */
2316     peer_features =
2317         bta_avk_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET);
2318     log::verbose("populating rem ctrl target features {}", peer_features);
2319     if (BTA_AV_FEAT_ADV_CTRL &
2320         bta_avk_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL))
2321       peer_features |= (BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_RCCT);
2322 
2323     if (peer_features & BTA_AV_FEAT_COVER_ARTWORK)
2324       cover_art_psm = bta_avk_get_cover_art_psm();
2325 
2326     log::verbose("populating rem ctrl target bip psm 0x{:x}", cover_art_psm);
2327   } else if (p_cb->sdp_a2dp_handle) {
2328     /* check peer version and whether support CT and TG role */
2329     peer_features =
2330         bta_av_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL);
2331     if ((p_cb->features & BTA_AV_FEAT_ADV_CTRL) &&
2332         ((peer_features & BTA_AV_FEAT_ADV_CTRL) == 0)) {
2333       /* if we support advance control and peer does not, check their support on
2334        * TG role
2335        * some implementation uses 1.3 on CT ans 1.4 on TG */
2336       peer_features |=
2337           bta_av_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET);
2338     }
2339 
2340     /* Change our features if the remote AVRCP version is 1.3 or less */
2341     tSDP_DISC_REC* p_rec = nullptr;
2342     p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
2343         p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, p_rec);
2344     if (p_rec != NULL &&
2345         get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(
2346             p_rec, ATTR_ID_BT_PROFILE_DESC_LIST) != NULL) {
2347       /* get profile version (if failure, version parameter is not updated) */
2348       uint16_t peer_rc_version = 0xFFFF;  // Don't change the AVRCP version
2349       if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(
2350               p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) {
2351         log::warn("Unable to find AVRCP version peer:{}",
2352                   p_rec->remote_bd_addr);
2353       }
2354       if (peer_rc_version <= AVRC_REV_1_3) {
2355         log::verbose("Using AVRCP 1.3 Capabilities with remote device");
2356         p_bta_av_cfg = &bta_av_cfg_compatibility;
2357       }
2358     }
2359   }
2360 
2361   bta_av_store_peer_rc_version();
2362 
2363   p_cb->disc = 0;
2364   osi_free_and_reset((void**)&p_cb->p_disc_db);
2365 
2366   log::verbose("peer_features 0x{:x}, features 0x{:x}", peer_features,
2367                p_cb->features);
2368 
2369   /* if we have no rc connection */
2370   if (rc_handle == BTA_AV_RC_HANDLE_NONE) {
2371     if (p_scb) {
2372       /* if peer remote control service matches ours and USE_RC is true */
2373       if ((((p_cb->features & BTA_AV_FEAT_RCCT) &&
2374             (peer_features & BTA_AV_FEAT_RCTG)) ||
2375            ((p_cb->features & BTA_AV_FEAT_RCTG) &&
2376             (peer_features & BTA_AV_FEAT_RCCT)))) {
2377         p_lcb = bta_av_find_lcb(p_scb->PeerAddress(), BTA_AV_LCB_FIND);
2378         if (p_lcb) {
2379           rc_handle = bta_av_rc_create(p_cb, AVCT_INT,
2380                                        (uint8_t)(p_scb->hdi + 1), p_lcb->lidx);
2381           if (rc_handle < BTA_AV_NUM_RCB) {
2382             p_cb->rcb[rc_handle].peer_features = peer_features;
2383             p_cb->rcb[rc_handle].cover_art_psm = cover_art_psm;
2384           } else {
2385             /* cannot create valid rc_handle for current device. report failure
2386              */
2387             log::error("no link resources available");
2388             p_scb->use_rc = false;
2389             tBTA_AV_RC_OPEN rc_open;
2390             rc_open.peer_addr = p_scb->PeerAddress();
2391             rc_open.peer_features = 0;
2392             rc_open.cover_art_psm = 0;
2393             rc_open.status = BTA_AV_FAIL_RESOURCES;
2394             tBTA_AV bta_av_data;
2395             bta_av_data.rc_open = rc_open;
2396             (*p_cb->p_cback)(BTA_AV_RC_OPEN_EVT, &bta_av_data);
2397           }
2398         } else {
2399           log::error("can not find LCB!!");
2400         }
2401       } else if (p_scb->use_rc) {
2402         /* can not find AVRC on peer device. report failure */
2403         p_scb->use_rc = false;
2404         tBTA_AV bta_av_data = {
2405           .rc_open = {
2406             .rc_handle = BTA_AV_RC_HANDLE_NONE,
2407             .cover_art_psm = 0,
2408             .peer_features = 0,
2409             .peer_addr = p_scb->PeerAddress(),
2410             .status = BTA_AV_FAIL_SDP,
2411           },
2412         };
2413         (*p_cb->p_cback)(BTA_AV_RC_OPEN_EVT, &bta_av_data);
2414       }
2415       if (peer_features != 0)
2416         DEVICE_IOT_CONFIG_ADDR_SET_HEX(p_scb->PeerAddress(),
2417                                        IOT_CONF_KEY_AVRCP_FEATURES,
2418                                        peer_features, IOT_CONF_BYTE_NUM_2);
2419     }
2420   } else {
2421     tBTA_AV_RC_FEAT rc_feat;
2422     p_cb->rcb[rc_handle].peer_features = peer_features;
2423     rc_feat.rc_handle = rc_handle;
2424     rc_feat.peer_features = peer_features;
2425     if (p_scb == NULL) {
2426       /*
2427        * In case scb is not created by the time we are done with SDP
2428        * we still need to send RC feature event. So we need to get BD
2429        * from Message.  Note that lidx is 1 based not 0 based
2430        */
2431       rc_feat.peer_addr = p_cb->lcb[p_cb->rcb[rc_handle].lidx - 1].addr;
2432     } else {
2433       rc_feat.peer_addr = p_scb->PeerAddress();
2434     }
2435 
2436     tBTA_AV bta_av_feat;
2437     bta_av_feat.rc_feat = rc_feat;
2438     (*p_cb->p_cback)(BTA_AV_RC_FEAT_EVT, &bta_av_feat);
2439 
2440     if (peer_features != 0)
2441       DEVICE_IOT_CONFIG_ADDR_SET_HEX(rc_feat.peer_addr,
2442                                      IOT_CONF_KEY_AVRCP_FEATURES, peer_features,
2443                                      IOT_CONF_BYTE_NUM_2);
2444 
2445     // Send PSM data
2446     log::verbose("Send PSM data");
2447     tBTA_AV_RC_PSM rc_psm;
2448     p_cb->rcb[rc_handle].cover_art_psm = cover_art_psm;
2449     rc_psm.rc_handle = rc_handle;
2450     rc_psm.cover_art_psm = cover_art_psm;
2451     if (p_scb == NULL) {
2452       rc_psm.peer_addr = p_cb->lcb[p_cb->rcb[rc_handle].lidx - 1].addr;
2453     } else {
2454       rc_psm.peer_addr = p_scb->PeerAddress();
2455     }
2456 
2457     log::verbose("rc_psm = 0x{:x}", rc_psm.cover_art_psm);
2458 
2459     tBTA_AV bta_av_psm;
2460     bta_av_psm.rc_cover_art_psm = rc_psm;
2461     (*p_cb->p_cback)(BTA_AV_RC_PSM_EVT, &bta_av_psm);
2462   }
2463 }
2464 
2465 /*******************************************************************************
2466  *
2467  * Function         bta_av_rc_closed
2468  *
2469  * Description      Set AVRCP state to closed.
2470  *
2471  * Returns          void
2472  *
2473  ******************************************************************************/
bta_av_rc_closed(tBTA_AV_DATA * p_data)2474 void bta_av_rc_closed(tBTA_AV_DATA* p_data) {
2475   tBTA_AV_CB* p_cb = &bta_av_cb;
2476   tBTA_AV_RC_CLOSE rc_close;
2477   tBTA_AV_RC_CONN_CHG* p_msg = (tBTA_AV_RC_CONN_CHG*)p_data;
2478   tBTA_AV_RCB* p_rcb;
2479   tBTA_AV_SCB* p_scb;
2480   int i;
2481   bool conn = false;
2482   tBTA_AV_LCB* p_lcb;
2483 
2484   rc_close.rc_handle = BTA_AV_RC_HANDLE_NONE;
2485   rc_close.peer_addr = RawAddress::kEmpty;
2486   p_scb = NULL;
2487   log::verbose("rc_handle:{}, address:{}", p_msg->handle, p_msg->peer_addr);
2488   for (i = 0; i < BTA_AV_NUM_RCB; i++) {
2489     p_rcb = &p_cb->rcb[i];
2490     log::verbose("rcb[{}] rc_handle:{}, status=0x{:x}, shdl:{}, lidx:{}", i,
2491                  p_rcb->handle, p_rcb->status, p_rcb->shdl, p_rcb->lidx);
2492     if (p_rcb->handle == p_msg->handle) {
2493       if (btif_av_src_sink_coexist_enabled() && p_rcb->shdl &&
2494           (p_rcb->shdl - 1) < BTA_AV_NUM_STRS) {
2495         p_scb = bta_av_cb.p_scb[p_rcb->shdl - 1];
2496         if (p_scb && !(p_scb->PeerAddress() == p_msg->peer_addr)) {
2497           log::verbose("handle{} {} error p_scb or addr", i,
2498                        p_scb->PeerAddress());
2499           conn = true;
2500           continue;
2501         }
2502       }
2503       rc_close.rc_handle = i;
2504       p_rcb->status &= ~BTA_AV_RC_CONN_MASK;
2505       p_rcb->peer_features = 0;
2506       p_rcb->cover_art_psm = 0;
2507       p_rcb->peer_ct_features = 0;
2508       p_rcb->peer_tg_features = 0;
2509       p_cb->rc_feature = {};
2510       log::verbose("shdl:{}, lidx:{}", p_rcb->shdl, p_rcb->lidx);
2511       if (p_rcb->shdl) {
2512         if ((p_rcb->shdl - 1) < BTA_AV_NUM_STRS) {
2513           p_scb = bta_av_cb.p_scb[p_rcb->shdl - 1];
2514         }
2515         if (p_scb) {
2516           rc_close.peer_addr = p_scb->PeerAddress();
2517           if (p_scb->rc_handle == p_rcb->handle)
2518             p_scb->rc_handle = BTA_AV_RC_HANDLE_NONE;
2519           log::verbose("shdl:{}, srch:{}", p_rcb->shdl, p_scb->rc_handle);
2520         }
2521         p_rcb->shdl = 0;
2522       } else if (p_rcb->lidx == (BTA_AV_NUM_LINKS + 1)) {
2523         /* if the RCB uses the extra LCB, use the addr for event and clean it */
2524         p_lcb = &p_cb->lcb[BTA_AV_NUM_LINKS];
2525         rc_close.peer_addr = p_msg->peer_addr;
2526         log::info("rc_only closed bd_addr: {}", p_msg->peer_addr);
2527         p_lcb->conn_msk = 0;
2528         p_lcb->lidx = 0;
2529       }
2530       p_rcb->lidx = 0;
2531 
2532       if ((p_rcb->status & BTA_AV_RC_ROLE_MASK) == BTA_AV_RC_ROLE_INT) {
2533         /* AVCT CCB is deallocated */
2534         p_rcb->handle = BTA_AV_RC_HANDLE_NONE;
2535         p_rcb->status = 0;
2536       } else {
2537         /* AVCT CCB is still there. dealloc */
2538         bta_av_del_rc(p_rcb);
2539       }
2540     } else if ((p_rcb->handle != BTA_AV_RC_HANDLE_NONE) &&
2541                (p_rcb->status & BTA_AV_RC_CONN_MASK)) {
2542       /* at least one channel is still connected */
2543       conn = true;
2544     }
2545   }
2546 
2547   if (!conn) {
2548     /* no AVRC channels are connected, go back to INIT state */
2549     bta_av_sm_execute(p_cb, BTA_AV_AVRC_NONE_EVT, NULL);
2550   }
2551 
2552   if (rc_close.rc_handle == BTA_AV_RC_HANDLE_NONE) {
2553     rc_close.rc_handle = p_msg->handle;
2554     rc_close.peer_addr = p_msg->peer_addr;
2555   }
2556   tBTA_AV bta_av_data;
2557   bta_av_data.rc_close = rc_close;
2558   (*p_cb->p_cback)(BTA_AV_RC_CLOSE_EVT, &bta_av_data);
2559   if (bta_av_cb.rc_acp_handle == BTA_AV_RC_HANDLE_NONE
2560                   && bta_av_cb.features & BTA_AV_FEAT_RCTG)
2561       bta_av_rc_create(&bta_av_cb, AVCT_ACP, 0, BTA_AV_NUM_LINKS + 1);
2562 }
2563 
2564 /*******************************************************************************
2565  *
2566  * Function         bta_av_rc_browse_opened
2567  *
2568  * Description      AVRC browsing channel is opened
2569  *
2570  * Returns          void
2571  *
2572  ******************************************************************************/
bta_av_rc_browse_opened(tBTA_AV_DATA * p_data)2573 void bta_av_rc_browse_opened(tBTA_AV_DATA* p_data) {
2574   tBTA_AV_CB* p_cb = &bta_av_cb;
2575   tBTA_AV_RC_CONN_CHG* p_msg = (tBTA_AV_RC_CONN_CHG*)p_data;
2576   tBTA_AV_RC_BROWSE_OPEN rc_browse_open;
2577 
2578   log::info("peer_addr: {} rc_handle:{}", p_msg->peer_addr, p_msg->handle);
2579 
2580   rc_browse_open.status = BTA_AV_SUCCESS;
2581   rc_browse_open.rc_handle = p_msg->handle;
2582   rc_browse_open.peer_addr = p_msg->peer_addr;
2583 
2584   tBTA_AV bta_av_data;
2585   bta_av_data.rc_browse_open = rc_browse_open;
2586   (*p_cb->p_cback)(BTA_AV_RC_BROWSE_OPEN_EVT, &bta_av_data);
2587 }
2588 
2589 /*******************************************************************************
2590  *
2591  * Function         bta_av_rc_browse_closed
2592  *
2593  * Description      AVRC browsing channel is closed
2594  *
2595  * Returns          void
2596  *
2597  ******************************************************************************/
bta_av_rc_browse_closed(tBTA_AV_DATA * p_data)2598 void bta_av_rc_browse_closed(tBTA_AV_DATA* p_data) {
2599   tBTA_AV_CB* p_cb = &bta_av_cb;
2600   tBTA_AV_RC_CONN_CHG* p_msg = (tBTA_AV_RC_CONN_CHG*)p_data;
2601   tBTA_AV_RC_BROWSE_CLOSE rc_browse_close;
2602 
2603   log::info("peer_addr: {} rc_handle:{}", p_msg->peer_addr, p_msg->handle);
2604 
2605   rc_browse_close.rc_handle = p_msg->handle;
2606   rc_browse_close.peer_addr = p_msg->peer_addr;
2607 
2608   tBTA_AV bta_av_data;
2609   bta_av_data.rc_browse_close = rc_browse_close;
2610   (*p_cb->p_cback)(BTA_AV_RC_BROWSE_CLOSE_EVT, &bta_av_data);
2611 }
2612 
2613 /*******************************************************************************
2614  *
2615  * Function         bta_av_rc_disc
2616  *
2617  * Description      start AVRC SDP discovery.
2618  *
2619  * Returns          void
2620  *
2621  ******************************************************************************/
bta_av_rc_disc(uint8_t disc)2622 void bta_av_rc_disc(uint8_t disc) {
2623   tBTA_AV_CB* p_cb = &bta_av_cb;
2624   tAVRC_SDP_DB_PARAMS db_params;
2625   uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST,
2626                           ATTR_ID_BT_PROFILE_DESC_LIST,
2627                           ATTR_ID_SUPPORTED_FEATURES,
2628                           ATTR_ID_ADDITION_PROTO_DESC_LISTS};
2629   uint8_t hdi;
2630   tBTA_AV_SCB* p_scb;
2631   RawAddress peer_addr = RawAddress::kEmpty;
2632   uint8_t rc_handle;
2633 
2634   log::verbose("disc: 0x{:x}, bta_av_cb.disc: 0x{:x}", disc, bta_av_cb.disc);
2635   if ((bta_av_cb.disc != 0) || (disc == 0)) return;
2636 
2637   if ((disc & BTA_AV_CHNL_MSK) == BTA_AV_CHNL_MSK) {
2638     /* this is the rc handle/index to tBTA_AV_RCB */
2639     rc_handle = disc & (~BTA_AV_CHNL_MSK);
2640     if (p_cb->rcb[rc_handle].lidx) {
2641       peer_addr = p_cb->lcb[p_cb->rcb[rc_handle].lidx - 1].addr;
2642     }
2643   } else {
2644     hdi = (disc & BTA_AV_HNDL_MSK) - 1;
2645     p_scb = p_cb->p_scb[hdi];
2646 
2647     if (p_scb) {
2648       log::verbose("rc_handle {}", p_scb->rc_handle);
2649       peer_addr = p_scb->PeerAddress();
2650     }
2651   }
2652 
2653   if (!peer_addr.IsEmpty()) {
2654     /* allocate discovery database */
2655     if (p_cb->p_disc_db == NULL)
2656       p_cb->p_disc_db = (tSDP_DISCOVERY_DB*)osi_malloc(BTA_AV_DISC_BUF_SIZE);
2657 
2658     /* set up parameters */
2659     db_params.db_len = BTA_AV_DISC_BUF_SIZE;
2660     db_params.num_attr = sizeof(attr_list) / sizeof(uint16_t);
2661     db_params.p_db = p_cb->p_disc_db;
2662     db_params.p_attrs = attr_list;
2663 
2664     /* searching for UUID_SERVCLASS_AV_REMOTE_CONTROL gets both TG and CT */
2665     if (AVRC_FindService(UUID_SERVCLASS_AV_REMOTE_CONTROL, peer_addr,
2666                          &db_params,
2667                          base::Bind(bta_av_avrc_sdp_cback)) == AVRC_SUCCESS) {
2668       p_cb->disc = disc;
2669       log::verbose("disc 0x{:x}", p_cb->disc);
2670     }
2671   }
2672 }
2673 
2674 /*******************************************************************************
2675  *
2676  * Function         bta_av_dereg_comp
2677  *
2678  * Description      deregister complete. free the stream control block.
2679  *
2680  * Returns          void
2681  *
2682  ******************************************************************************/
bta_av_dereg_comp(tBTA_AV_DATA * p_data)2683 void bta_av_dereg_comp(tBTA_AV_DATA* p_data) {
2684   tBTA_AV_CB* p_cb = &bta_av_cb;
2685   tBTA_AV_SCB* p_scb;
2686   tBTA_UTL_COD cod = {
2687     .minor = BTM_COD_MINOR_UNCLASSIFIED,
2688     .major = BTM_COD_MAJOR_UNCLASSIFIED,
2689     .service = 0,
2690   };
2691 
2692   uint8_t mask;
2693   BT_HDR* p_buf;
2694 
2695   /* find the stream control block */
2696   p_scb = bta_av_hndl_to_scb(p_data->hdr.layer_specific);
2697 
2698   if (p_scb) {
2699     log::verbose("deregistered {}(h{})", p_scb->chnl, p_scb->hndl);
2700     mask = BTA_AV_HNDL_TO_MSK(p_scb->hdi);
2701     p_cb->reg_audio &= ~mask;
2702     if ((p_cb->conn_audio & mask) && p_cb->audio_open_cnt) {
2703       /* this channel is still marked as open. decrease the count */
2704       p_cb->audio_open_cnt--;
2705     }
2706     p_cb->conn_audio &= ~mask;
2707 
2708     if (p_scb->q_tag == BTA_AV_Q_TAG_STREAM && p_scb->a2dp_list) {
2709       /* make sure no buffers are in a2dp_list */
2710       while (!list_is_empty(p_scb->a2dp_list)) {
2711         p_buf = (BT_HDR*)list_front(p_scb->a2dp_list);
2712         list_remove(p_scb->a2dp_list, p_buf);
2713         osi_free(p_buf);
2714       }
2715     }
2716 
2717     /* remove the A2DP SDP record, if no more audio stream is left */
2718     if (!p_cb->reg_audio) {
2719       /* Only remove the SDP record if we're the ones that created it */
2720       if (is_new_avrcp_enabled()) {
2721         log::verbose(
2722             "newavrcp is the owner of the AVRCP Target SDP record. Don't dereg "
2723             "the SDP record");
2724       } else {
2725         log::verbose("newavrcp is not enabled. Remove SDP record");
2726         bta_ar_dereg_avrc(UUID_SERVCLASS_AV_REMOTE_CONTROL);
2727       }
2728 
2729       if (p_cb->sdp_a2dp_handle) {
2730         bta_av_del_sdp_rec(&p_cb->sdp_a2dp_handle);
2731         p_cb->sdp_a2dp_handle = 0;
2732         bta_sys_remove_uuid(UUID_SERVCLASS_AUDIO_SOURCE);
2733       }
2734 
2735       if (p_cb->sdp_a2dp_snk_handle) {
2736         bta_av_del_sdp_rec(&p_cb->sdp_a2dp_snk_handle);
2737         p_cb->sdp_a2dp_snk_handle = 0;
2738         bta_sys_remove_uuid(UUID_SERVCLASS_AUDIO_SINK);
2739       }
2740     }
2741 
2742     bta_av_free_scb(p_scb);
2743   }
2744 
2745   log::verbose("audio 0x{:x}, disable:{}", p_cb->reg_audio, p_cb->disabling);
2746   /* if no stream control block is active */
2747   if (p_cb->reg_audio == 0) {
2748     /* deregister from AVDT */
2749     bta_ar_dereg_avdt();
2750 
2751     /* deregister from AVCT */
2752     bta_ar_dereg_avrc(UUID_SERVCLASS_AV_REM_CTRL_TARGET);
2753     bta_ar_dereg_avct();
2754 
2755     if (p_cb->disabling) {
2756       p_cb->disabling = false;
2757       // reset enabling parameters
2758       p_cb->features = 0;
2759       p_cb->sec_mask = 0;
2760       bta_av_cb.sink_features = 0;
2761       bta_av_cb.reg_role = 0;
2762     }
2763 
2764     /* Clear the Capturing service class bit */
2765     cod.service = BTM_COD_SERVICE_CAPTURING;
2766     utl_set_device_class(&cod, BTA_UTL_CLR_COD_SERVICE_CLASS);
2767   }
2768 }
2769