1 /******************************************************************************
2  *
3  *  Copyright 2003-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  *  Interface to AVRCP mandatory commands
22  *
23  ******************************************************************************/
24 #include "avrc_api.h"
25 
26 #include <android_bluetooth_sysprop.h>
27 #include <bluetooth/log.h>
28 #include <string.h>
29 
30 #include <cstdint>
31 
32 #include "avct_api.h"
33 #include "avrc_defs.h"
34 #include "avrc_int.h"
35 #include "avrcp.sysprop.h"
36 #include "btif/include/btif_av.h"
37 #include "btif/include/btif_config.h"
38 #include "internal_include/bt_target.h"
39 #include "osi/include/alarm.h"
40 #include "osi/include/allocator.h"
41 #include "osi/include/fixed_queue.h"
42 #include "osi/include/properties.h"
43 #include "stack/avct/avct_defs.h"
44 #include "stack/include/bt_hdr.h"
45 #include "stack/include/bt_types.h"
46 #include "stack/include/bt_uuid16.h"
47 #include "storage/config_keys.h"
48 #include "types/raw_address.h"
49 
50 using namespace bluetooth;
51 
52 /*****************************************************************************
53  *  Global data
54  ****************************************************************************/
55 
56 #define AVRC_MAX_RCV_CTRL_EVT AVCT_BROWSE_UNCONG_IND_EVT
57 
58 #ifndef MAX
59 #define MAX(a, b) ((a) > (b) ? (a) : (b))
60 #endif
61 
62 static const uint8_t avrc_ctrl_event_map[] = {
63         AVRC_OPEN_IND_EVT,         /* AVCT_CONNECT_CFM_EVT */
64         AVRC_OPEN_IND_EVT,         /* AVCT_CONNECT_IND_EVT */
65         AVRC_CLOSE_IND_EVT,        /* AVCT_DISCONNECT_CFM_EVT */
66         AVRC_CLOSE_IND_EVT,        /* AVCT_DISCONNECT_IND_EVT */
67         AVRC_CONG_IND_EVT,         /* AVCT_CONG_IND_EVT */
68         AVRC_UNCONG_IND_EVT,       /* AVCT_UNCONG_IND_EVT */
69         AVRC_BROWSE_OPEN_IND_EVT,  /* AVCT_BROWSE_CONN_CFM_EVT   */
70         AVRC_BROWSE_OPEN_IND_EVT,  /* AVCT_BROWSE_CONN_IND_EVT   */
71         AVRC_BROWSE_CLOSE_IND_EVT, /* AVCT_BROWSE_DISCONN_CFM_EVT */
72         AVRC_BROWSE_CLOSE_IND_EVT, /* AVCT_BROWSE_DISCONN_IND_EVT */
73         AVRC_BROWSE_CONG_IND_EVT,  /* AVCT_BROWSE_CONG_IND_EVT    */
74         AVRC_BROWSE_UNCONG_IND_EVT /* AVCT_BROWSE_UNCONG_IND_EVT  */
75 };
76 
77 /* use this unused opcode to indication no need to call the callback function */
78 #define AVRC_OP_DROP 0xFE
79 /* use this unused opcode to indication no need to call the callback function &
80  * free buffer */
81 #define AVRC_OP_DROP_N_FREE 0xFD
82 
83 #define AVRC_OP_UNIT_INFO_RSP_LEN 8
84 #define AVRC_OP_SUB_UNIT_INFO_RSP_LEN 8
85 #define AVRC_OP_REJ_MSG_LEN 11
86 
87 /* Flags definitions for AVRC_MsgReq */
88 #define AVRC_MSG_MASK_IS_VENDOR_CMD 0x01
89 #define AVRC_MSG_MASK_IS_CONTINUATION_RSP 0x02
90 
91 static void avrc_start_cmd_timer(uint8_t handle, uint8_t label, uint8_t msg_mask);
92 
93 /******************************************************************************
94  *
95  * Function         avrcp_absolute_volume_is_enabled
96  *
97  * Description      Check if config support advance control (absolute volume)
98  *
99  * Returns          return true if absolute_volume is enabled
100  *
101  *****************************************************************************/
avrcp_absolute_volume_is_enabled()102 bool avrcp_absolute_volume_is_enabled() {
103   return android::sysprop::bluetooth::Avrcp::absolute_volume().value_or(true);
104 }
105 
106 /******************************************************************************
107  *
108  * Function         avrc_ctrl_cback
109  *
110  * Description      This is the callback function used by AVCTP to report
111  *                  received link events.
112  *
113  * Returns          Nothing.
114  *
115  *****************************************************************************/
avrc_ctrl_cback(uint8_t handle,uint8_t event,uint16_t result,const RawAddress * peer_addr)116 static void avrc_ctrl_cback(uint8_t handle, uint8_t event, uint16_t result,
117                             const RawAddress* peer_addr) {
118   uint8_t avrc_event;
119 
120   if (event <= AVRC_MAX_RCV_CTRL_EVT && avrc_cb.ccb[handle].ctrl_cback) {
121     avrc_event = avrc_ctrl_event_map[event];
122     if (event == AVCT_CONNECT_CFM_EVT) {
123       if (result != 0) { /* failed */
124         avrc_event = AVRC_CLOSE_IND_EVT;
125       }
126     }
127     avrc_cb.ccb[handle].ctrl_cback.Run(handle, avrc_event, result, peer_addr);
128   }
129 
130   if ((event == AVCT_DISCONNECT_CFM_EVT) || (event == AVCT_DISCONNECT_IND_EVT)) {
131     avrc_flush_cmd_q(handle);
132     alarm_free(avrc_cb.ccb_int[handle].tle);
133     avrc_cb.ccb_int[handle].tle = NULL;
134   }
135 }
136 
137 /******************************************************************************
138  *
139  * Function         avrc_flush_cmd_q
140  *
141  * Description      Flush command queue for the specified avrc handle
142  *
143  * Returns          Nothing.
144  *
145  *****************************************************************************/
avrc_flush_cmd_q(uint8_t handle)146 void avrc_flush_cmd_q(uint8_t handle) {
147   log::verbose("AVRC: Flushing command queue for handle=0x{:02x}", handle);
148   avrc_cb.ccb_int[handle].flags &= ~AVRC_CB_FLAGS_RSP_PENDING;
149 
150   alarm_cancel(avrc_cb.ccb_int[handle].tle);
151   fixed_queue_free(avrc_cb.ccb_int[handle].cmd_q, osi_free);
152   avrc_cb.ccb_int[handle].cmd_q = NULL;
153 }
154 
155 /******************************************************************************
156  *
157  * Function         avrc_process_timeout
158  *
159  * Description      Handle avrc command timeout
160  *
161  * Returns          Nothing.
162  *
163  *****************************************************************************/
avrc_process_timeout(void * data)164 static void avrc_process_timeout(void* data) {
165   tAVRC_PARAM* param = (tAVRC_PARAM*)data;
166 
167   log::verbose("AVRC: command timeout (handle=0x{:02x}, label=0x{:02x})", param->handle,
168                param->label);
169 
170   /* Notify app */
171   if (avrc_cb.ccb[param->handle].ctrl_cback) {
172     avrc_cb.ccb[param->handle].ctrl_cback.Run(param->handle, AVRC_CMD_TIMEOUT_EVT, param->label,
173                                               NULL);
174   }
175 
176   /* If vendor command timed-out, then send next command in the queue */
177   if (param->msg_mask & AVRC_MSG_MASK_IS_VENDOR_CMD) {
178     avrc_send_next_vendor_cmd(param->handle);
179   }
180   osi_free(param);
181 }
182 
183 /******************************************************************************
184  *
185  * Function         avrc_send_next_vendor_cmd
186  *
187  * Description      Dequeue and send next vendor command for given handle
188  *
189  * Returns          Nothing.
190  *
191  *****************************************************************************/
avrc_send_next_vendor_cmd(uint8_t handle)192 void avrc_send_next_vendor_cmd(uint8_t handle) {
193   BT_HDR* p_next_cmd;
194   uint8_t next_label;
195 
196   while ((p_next_cmd = (BT_HDR*)fixed_queue_try_dequeue(avrc_cb.ccb_int[handle].cmd_q)) != NULL) {
197     p_next_cmd->event &= 0xFF;                      /* opcode */
198     next_label = (p_next_cmd->layer_specific) >> 8; /* extract label */
199     p_next_cmd->layer_specific &= 0xFF;             /* AVCT_DATA_CTRL or AVCT_DATA_BROWSE */
200 
201     log::verbose("AVRC: Dequeuing command 0x{} (handle=0x{:02x}, label=0x{:02x})",
202                  std::format_ptr(p_next_cmd), handle, next_label);
203 
204     /* Send the message */
205     if ((AVCT_MsgReq(handle, next_label, AVCT_CMD, p_next_cmd)) == AVCT_SUCCESS) {
206       /* Start command timer to wait for response */
207       avrc_start_cmd_timer(handle, next_label, AVRC_MSG_MASK_IS_VENDOR_CMD);
208       return;
209     }
210   }
211 
212   if (p_next_cmd == NULL) {
213     /* cmd queue empty */
214     avrc_cb.ccb_int[handle].flags &= ~AVRC_CB_FLAGS_RSP_PENDING;
215   }
216 }
217 
218 /******************************************************************************
219  *
220  * Function         avrc_start_cmd_timer
221  *
222  * Description      Start timer for waiting for responses
223  *
224  * Returns          Nothing.
225  *
226  *****************************************************************************/
avrc_start_cmd_timer(uint8_t handle,uint8_t label,uint8_t msg_mask)227 static void avrc_start_cmd_timer(uint8_t handle, uint8_t label, uint8_t msg_mask) {
228   if (!avrc_cb.ccb_int[handle].tle) {
229     log::warn("Unable to start response timer handle=0x{:02x} label=0x{:02x} msg_mask:0x{:02x}",
230               handle, label, msg_mask);
231     return;
232   }
233 
234   tAVRC_PARAM* param = static_cast<tAVRC_PARAM*>(osi_malloc(sizeof(tAVRC_PARAM)));
235   param->handle = handle;
236   param->label = label;
237   param->msg_mask = msg_mask;
238 
239   log::verbose("AVRC: starting timer (handle=0x{:02x} label=0x{:02x})", handle, label);
240   alarm_set_on_mloop(avrc_cb.ccb_int[handle].tle, AVRC_CMD_TOUT_MS, avrc_process_timeout, param);
241 }
242 
243 /******************************************************************************
244  *
245  * Function         avrc_get_data_ptr
246  *
247  * Description      Gets a pointer to the data payload in the packet.
248  *
249  * Returns          A pointer to the data payload.
250  *
251  *****************************************************************************/
avrc_get_data_ptr(BT_HDR * p_pkt)252 static uint8_t* avrc_get_data_ptr(BT_HDR* p_pkt) { return (uint8_t*)(p_pkt + 1) + p_pkt->offset; }
253 
254 /******************************************************************************
255  *
256  * Function         avrc_copy_packet
257  *
258  * Description      Copies an AVRC packet to a new buffer. In the new buffer,
259  *                  the payload offset is at least AVCT_MSG_OFFSET octets.
260  *
261  * Returns          The buffer with the copied data.
262  *
263  *****************************************************************************/
avrc_copy_packet(BT_HDR * p_pkt,int rsp_pkt_len)264 static BT_HDR* avrc_copy_packet(BT_HDR* p_pkt, int rsp_pkt_len) {
265   const int offset = MAX(AVCT_MSG_OFFSET, p_pkt->offset);
266   const int pkt_len = MAX(rsp_pkt_len, p_pkt->len);
267   BT_HDR* p_pkt_copy = (BT_HDR*)osi_calloc(BT_HDR_SIZE + offset + pkt_len);
268 
269   /* Copy the packet header, set the new offset, and copy the payload */
270   memcpy(p_pkt_copy, p_pkt, BT_HDR_SIZE);
271   p_pkt_copy->offset = offset;
272   uint8_t* p_data = avrc_get_data_ptr(p_pkt);
273   uint8_t* p_data_copy = avrc_get_data_ptr(p_pkt_copy);
274   memcpy(p_data_copy, p_data, p_pkt->len);
275 
276   return p_pkt_copy;
277 }
278 
279 /******************************************************************************
280  *
281  * Function         avrc_prep_end_frag
282  *
283  * Description      This function prepares an end response fragment
284  *
285  * Returns          Nothing.
286  *
287  *****************************************************************************/
avrc_prep_end_frag(uint8_t handle)288 static void avrc_prep_end_frag(uint8_t handle) {
289   tAVRC_FRAG_CB* p_fcb;
290   BT_HDR* p_pkt_new;
291   uint8_t *p_data, *p_orig_data;
292   uint8_t rsp_type;
293 
294   log::verbose("");
295   p_fcb = &avrc_cb.fcb[handle];
296 
297   /* The response type of the end fragment should be the same as the the PDU of
298    * "End Fragment Response" Errata:
299    * https://www.bluetooth.org/errata/errata_view.cfm?errata_id=4383
300    */
301   p_orig_data = ((uint8_t*)(p_fcb->p_fmsg + 1) + p_fcb->p_fmsg->offset);
302   rsp_type = ((*p_orig_data) & AVRC_CTYPE_MASK);
303 
304   p_pkt_new = p_fcb->p_fmsg;
305   p_pkt_new->len -= (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE);
306   p_pkt_new->offset += (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE);
307   p_data = (uint8_t*)(p_pkt_new + 1) + p_pkt_new->offset;
308   *p_data++ = rsp_type;
309   *p_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT);
310   *p_data++ = AVRC_OP_VENDOR;
311   AVRC_CO_ID_TO_BE_STREAM(p_data, AVRC_CO_METADATA);
312   *p_data++ = p_fcb->frag_pdu;
313   *p_data++ = AVRC_PKT_END;
314 
315   /* 4=pdu, pkt_type & len */
316   UINT16_TO_BE_STREAM(p_data, (p_pkt_new->len - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE));
317 }
318 
319 /******************************************************************************
320  *
321  * Function         avrc_send_continue_frag
322  *
323  * Description      This function sends a continue response fragment
324  *
325  * Returns          AVRC_SUCCESS if successful.
326  *                  AVRC_BAD_HANDLE if handle is invalid.
327  *
328  *****************************************************************************/
avrc_send_continue_frag(uint8_t handle,uint8_t label)329 static uint16_t avrc_send_continue_frag(uint8_t handle, uint8_t label) {
330   tAVRC_FRAG_CB* p_fcb;
331   BT_HDR *p_pkt_old, *p_pkt;
332   uint8_t *p_old, *p_data;
333   uint8_t cr = AVCT_RSP;
334 
335   p_fcb = &avrc_cb.fcb[handle];
336   p_pkt = p_fcb->p_fmsg;
337 
338   log::verbose("handle = {} label = {} len = {}", handle, label, p_pkt->len);
339   if (p_pkt->len > AVRC_MAX_CTRL_DATA_LEN) {
340     int offset_len = MAX(AVCT_MSG_OFFSET, p_pkt->offset);
341     p_pkt_old = p_fcb->p_fmsg;
342     p_pkt = (BT_HDR*)osi_calloc(AVRC_PACKET_LEN + offset_len + BT_HDR_SIZE);
343     p_pkt->len = AVRC_MAX_CTRL_DATA_LEN;
344     p_pkt->offset = AVCT_MSG_OFFSET;
345     p_pkt->layer_specific = p_pkt_old->layer_specific;
346     p_pkt->event = p_pkt_old->event;
347     p_old = (uint8_t*)(p_pkt_old + 1) + p_pkt_old->offset;
348     p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
349     memcpy(p_data, p_old, AVRC_MAX_CTRL_DATA_LEN);
350     /* use AVRC continue packet type */
351     p_data += AVRC_VENDOR_HDR_SIZE;
352     p_data++; /* pdu */
353     *p_data++ = AVRC_PKT_CONTINUE;
354     /* 4=pdu, pkt_type & len */
355     UINT16_TO_BE_STREAM(p_data, (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - 4));
356 
357     /* prepare the left over for as an end fragment */
358     avrc_prep_end_frag(handle);
359   } else {
360     /* end fragment. clean the control block */
361     p_fcb->frag_enabled = false;
362     p_fcb->p_fmsg = NULL;
363   }
364   return AVCT_MsgReq(handle, label, cr, p_pkt);
365 }
366 
367 /******************************************************************************
368  *
369  * Function         avrc_proc_vendor_command
370  *
371  * Description      This function processes received vendor command.
372  *
373  * Returns          if not NULL, the response to send right away.
374  *
375  *****************************************************************************/
avrc_proc_vendor_command(uint8_t handle,uint8_t label,BT_HDR * p_pkt,tAVRC_MSG_VENDOR * p_msg)376 static BT_HDR* avrc_proc_vendor_command(uint8_t handle, uint8_t label, BT_HDR* p_pkt,
377                                         tAVRC_MSG_VENDOR* p_msg) {
378   BT_HDR* p_rsp = NULL;
379   uint8_t* p_data;
380   uint8_t* p_begin;
381   uint8_t pkt_type;
382   bool abort_frag = false;
383   tAVRC_STS status = AVRC_STS_NO_ERROR;
384   tAVRC_FRAG_CB* p_fcb;
385 
386   p_begin = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
387   p_data = p_begin + AVRC_VENDOR_HDR_SIZE;
388   pkt_type = *(p_data + 1) & AVRC_PKT_TYPE_MASK;
389 
390   if (pkt_type != AVRC_PKT_SINGLE) {
391     /* reject - commands can only be in single packets at AVRCP level */
392     log::error("commands must be in single packet pdu:0x{:x}", *p_data);
393     /* use the current GKI buffer to send the reject */
394     status = AVRC_STS_BAD_CMD;
395   } else if (avrc_cb.fcb[handle].frag_enabled) {
396     /* check if there are fragments waiting to be sent */
397     p_fcb = &avrc_cb.fcb[handle];
398     if (p_msg->company_id == AVRC_CO_METADATA) {
399       switch (*p_data) {
400         case AVRC_PDU_ABORT_CONTINUATION_RSP:
401           /* aborted by CT - send accept response */
402           abort_frag = true;
403           p_begin = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
404           *p_begin = (AVRC_RSP_ACCEPT & AVRC_CTYPE_MASK);
405           if (*(p_data + 4) != p_fcb->frag_pdu) {
406             *p_begin = (AVRC_RSP_REJ & AVRC_CTYPE_MASK);
407             *(p_data + 4) = AVRC_STS_BAD_PARAM;
408           } else {
409             p_data = (p_begin + AVRC_VENDOR_HDR_SIZE + 2);
410             UINT16_TO_BE_STREAM(p_data, 0);
411             p_pkt->len = (p_data - p_begin);
412           }
413           AVCT_MsgReq(handle, label, AVCT_RSP, p_pkt);
414           p_msg->hdr.opcode = AVRC_OP_DROP; /* used the p_pkt to send response */
415           break;
416 
417         case AVRC_PDU_REQUEST_CONTINUATION_RSP:
418           if (*(p_data + 4) == p_fcb->frag_pdu) {
419             avrc_send_continue_frag(handle, label);
420             p_msg->hdr.opcode = AVRC_OP_DROP_N_FREE;
421           } else {
422             /* the pdu id does not match - reject the command using the current
423              * GKI buffer */
424             log::error("continue pdu: 0x{:x} does not match the current pdu: 0x{:x}", *(p_data + 4),
425                        p_fcb->frag_pdu);
426             status = AVRC_STS_BAD_PARAM;
427             abort_frag = true;
428           }
429           break;
430 
431         default:
432           /* implicit abort */
433           abort_frag = true;
434       }
435     } else {
436       abort_frag = true;
437       /* implicit abort */
438     }
439 
440     if (abort_frag) {
441       osi_free_and_reset((void**)&p_fcb->p_fmsg);
442       p_fcb->frag_enabled = false;
443     }
444   }
445 
446   if (status != AVRC_STS_NO_ERROR) {
447     p_rsp = (BT_HDR*)osi_calloc(BT_DEFAULT_BUFFER_SIZE);
448     p_rsp->offset = p_pkt->offset;
449     p_data = (uint8_t*)(p_rsp + 1) + p_pkt->offset;
450     *p_data++ = AVRC_RSP_REJ;
451     p_data += AVRC_VENDOR_HDR_SIZE; /* pdu */
452     *p_data++ = 0;                  /* pkt_type */
453     UINT16_TO_BE_STREAM(p_data, 1); /* len */
454     *p_data++ = status;             /* error code */
455     p_rsp->len = AVRC_VENDOR_HDR_SIZE + 5;
456   }
457 
458   return p_rsp;
459 }
460 
461 /******************************************************************************
462  *
463  * Function         avrc_proc_far_msg
464  *
465  * Description      This function processes metadata fragmenation
466  *                  and reassembly
467  *
468  * Returns          0, to report the message with msg_cback .
469  *
470  *****************************************************************************/
avrc_proc_far_msg(uint8_t handle,uint8_t label,uint8_t cr,BT_HDR ** pp_pkt,tAVRC_MSG_VENDOR * p_msg)471 static uint8_t avrc_proc_far_msg(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR** pp_pkt,
472                                  tAVRC_MSG_VENDOR* p_msg) {
473   BT_HDR* p_pkt = *pp_pkt;
474   uint8_t* p_data;
475   uint8_t drop_code = 0;
476   bool buf_overflow = false;
477   BT_HDR* p_rsp = NULL;
478   BT_HDR* p_cmd = NULL;
479   bool req_continue = false;
480   BT_HDR* p_pkt_new = NULL;
481   uint8_t pkt_type;
482   tAVRC_RASM_CB* p_rcb;
483   tAVRC_NEXT_CMD avrc_cmd;
484   tAVRC_STS status;
485 
486   p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
487 
488   /* Skip over vendor header (ctype, subunit*, opcode, CO_ID) */
489   p_data += AVRC_VENDOR_HDR_SIZE;
490 
491   pkt_type = *(p_data + 1) & AVRC_PKT_TYPE_MASK;
492   log::verbose("pkt_type {}", pkt_type);
493   p_rcb = &avrc_cb.rcb[handle];
494 
495   /* check if the message needs to be re-assembled */
496   if (pkt_type == AVRC_PKT_SINGLE || pkt_type == AVRC_PKT_START) {
497     /* previous fragments need to be dropped, when received another new message
498      */
499     p_rcb->rasm_offset = 0;
500     osi_free_and_reset((void**)&p_rcb->p_rmsg);
501   }
502 
503   if (pkt_type != AVRC_PKT_SINGLE && cr == AVCT_RSP) {
504     /* not a single response packet - need to re-assemble metadata messages */
505     if (pkt_type == AVRC_PKT_START) {
506       /* Allocate buffer for re-assembly */
507       p_rcb->rasm_pdu = *p_data;
508       p_rcb->p_rmsg = (BT_HDR*)osi_calloc(BT_DEFAULT_BUFFER_SIZE);
509       /* Copy START packet to buffer for re-assembling fragments */
510       memcpy(p_rcb->p_rmsg, p_pkt, sizeof(BT_HDR)); /* Copy bt hdr */
511 
512       /* Copy metadata message */
513       memcpy((uint8_t*)(p_rcb->p_rmsg + 1), (uint8_t*)(p_pkt + 1) + p_pkt->offset, p_pkt->len);
514 
515       /* offset of start of metadata response in reassembly buffer */
516       p_rcb->p_rmsg->offset = p_rcb->rasm_offset = 0;
517 
518       /*
519        * Free original START packet, replace with pointer to
520        * reassembly buffer.
521        */
522       osi_free(p_pkt);
523       *pp_pkt = p_rcb->p_rmsg;
524 
525       /*
526        * Set offset to point to where to copy next - use the same
527        * reassembly logic as AVCT.
528        */
529       p_rcb->p_rmsg->offset += p_rcb->p_rmsg->len;
530       req_continue = true;
531     } else if (p_rcb->p_rmsg == NULL) {
532       /* Received a CONTINUE/END, but no corresponding START
533                       (or previous fragmented response was dropped) */
534       log::verbose(
535               "Received a CONTINUE/END without no corresponding START (or previous "
536               "fragmented response was dropped)");
537       drop_code = 5;
538       osi_free(p_pkt);
539       *pp_pkt = NULL;
540     } else {
541       /* get size of buffer holding assembled message */
542       /*
543        * NOTE: The buffer is allocated above at the beginning of the
544        * reassembly, and is always of size BT_DEFAULT_BUFFER_SIZE.
545        */
546       uint16_t buf_len = BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR);
547       /* adjust offset and len of fragment for header byte */
548       p_pkt->offset += (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE);
549       p_pkt->len -= (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE);
550       /* verify length */
551       if ((p_rcb->p_rmsg->offset + p_pkt->len) > buf_len) {
552         log::warn("Fragmented message too big! - report the partial message");
553         p_pkt->len = buf_len - p_rcb->p_rmsg->offset;
554         pkt_type = AVRC_PKT_END;
555         buf_overflow = true;
556       }
557 
558       /* copy contents of p_pkt to p_rx_msg */
559       memcpy((uint8_t*)(p_rcb->p_rmsg + 1) + p_rcb->p_rmsg->offset,
560              (uint8_t*)(p_pkt + 1) + p_pkt->offset, p_pkt->len);
561 
562       if (pkt_type == AVRC_PKT_END) {
563         p_rcb->p_rmsg->offset = p_rcb->rasm_offset;
564         p_rcb->p_rmsg->len += p_pkt->len;
565         p_pkt_new = p_rcb->p_rmsg;
566         p_rcb->rasm_offset = 0;
567         p_rcb->p_rmsg = NULL;
568         p_msg->p_vendor_data = (uint8_t*)(p_pkt_new + 1) + p_pkt_new->offset;
569         p_msg->hdr.ctype = p_msg->p_vendor_data[0] & AVRC_CTYPE_MASK;
570         /* 6 = ctype, subunit*, opcode & CO_ID */
571         p_msg->p_vendor_data += AVRC_VENDOR_HDR_SIZE;
572         p_msg->vendor_len = p_pkt_new->len - AVRC_VENDOR_HDR_SIZE;
573         p_data = p_msg->p_vendor_data + 1; /* skip pdu */
574         *p_data++ = AVRC_PKT_SINGLE;
575         UINT16_TO_BE_STREAM(p_data, (p_msg->vendor_len - AVRC_MIN_META_HDR_SIZE));
576         log::verbose("end frag:{}, total len:{}, offset:{}", p_pkt->len, p_pkt_new->len,
577                      p_pkt_new->offset);
578       } else {
579         p_rcb->p_rmsg->offset += p_pkt->len;
580         p_rcb->p_rmsg->len += p_pkt->len;
581         p_pkt_new = NULL;
582         req_continue = true;
583       }
584       osi_free(p_pkt);
585       *pp_pkt = p_pkt_new;
586     }
587   }
588 
589   if (cr == AVCT_CMD) {
590     p_rsp = avrc_proc_vendor_command(handle, label, *pp_pkt, p_msg);
591     if (p_rsp) {
592       AVCT_MsgReq(handle, label, AVCT_RSP, p_rsp);
593       osi_free_and_reset((void**)pp_pkt);
594       drop_code = 3;
595     } else if (p_msg->hdr.opcode == AVRC_OP_DROP) {
596       drop_code = 1;
597     } else if (p_msg->hdr.opcode == AVRC_OP_DROP_N_FREE) {
598       drop_code = 4;
599     }
600 
601   } else if (cr == AVCT_RSP) {
602     if (req_continue) {
603       avrc_cmd.pdu = AVRC_PDU_REQUEST_CONTINUATION_RSP;
604       drop_code = 2;
605     } else if (buf_overflow) {
606       /* Incoming message too big to fit in BT_DEFAULT_BUFFER_SIZE. Send abort
607        * to peer  */
608       avrc_cmd.pdu = AVRC_PDU_ABORT_CONTINUATION_RSP;
609       drop_code = 4;
610     } else {
611       return drop_code;
612     }
613     avrc_cmd.status = AVRC_STS_NO_ERROR;
614     avrc_cmd.opcode = AVRC_OP_INVALID;
615     avrc_cmd.target_pdu = p_rcb->rasm_pdu;
616 
617     tAVRC_COMMAND avrc_command;
618     avrc_command.continu = avrc_cmd;
619     status = AVRC_BldCommand(&avrc_command, &p_cmd);
620     if (status == AVRC_STS_NO_ERROR) {
621       AVRC_MsgReq(handle, (uint8_t)(label), AVRC_CMD_CTRL, p_cmd, false);
622     }
623   }
624 
625   return drop_code;
626 }
627 
628 /******************************************************************************
629  *
630  * Function         avrc_msg_cback
631  *
632  * Description      This is the callback function used by AVCTP to report
633  *                  received AV control messages.
634  *
635  * Returns          Nothing.
636  *
637  *****************************************************************************/
avrc_msg_cback(uint8_t handle,uint8_t label,uint8_t cr,BT_HDR * p_pkt)638 static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR* p_pkt) {
639   uint8_t opcode;
640   tAVRC_MSG msg;
641   uint8_t* p_data;
642   uint8_t* p_begin;
643   bool drop = false;
644   bool do_free = true;
645   BT_HDR* p_rsp = NULL;
646   uint8_t* p_rsp_data;
647   int xx;
648   bool reject = false;
649   const char* p_drop_msg = "dropped";
650   tAVRC_MSG_VENDOR* p_msg = &msg.vendor;
651 
652   if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL && p_pkt->len > AVRC_PACKET_LEN)) {
653     log::warn("Command length {} too long: must be at most {}", p_pkt->len, AVRC_PACKET_LEN);
654     osi_free(p_pkt);
655     return;
656   }
657 
658   if (cr == AVCT_REJ) {
659     /* The peer thinks that this PID is no longer open - remove this handle */
660     /*  */
661     osi_free(p_pkt);
662     AVCT_RemoveConn(handle);
663     return;
664   } else if (cr == AVCT_RSP) {
665     /* Received response. Stop command timeout timer */
666     log::verbose("AVRC: stopping timer (handle=0x{:02x})", handle);
667     alarm_cancel(avrc_cb.ccb_int[handle].tle);
668   }
669 
670   p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
671   memset(&msg, 0, sizeof(tAVRC_MSG));
672 
673   if (p_pkt->layer_specific == AVCT_DATA_BROWSE) {
674     opcode = AVRC_OP_BROWSE;
675     msg.browse.hdr.ctype = cr;
676     msg.browse.p_browse_data = p_data;
677     msg.browse.browse_len = p_pkt->len;
678     msg.browse.p_browse_pkt = p_pkt;
679   } else {
680     if (p_pkt->len < AVRC_AVC_HDR_SIZE) {
681       log::warn("message length {} too short: must be at least {}", p_pkt->len, AVRC_AVC_HDR_SIZE);
682       osi_free(p_pkt);
683       return;
684     }
685     msg.hdr.ctype = p_data[0] & AVRC_CTYPE_MASK;
686     log::verbose("handle:{}, ctype:{}, offset:{}, len: {}", handle, msg.hdr.ctype, p_pkt->offset,
687                  p_pkt->len);
688     msg.hdr.subunit_type = (p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT;
689     msg.hdr.subunit_id = p_data[1] & AVRC_SUBID_MASK;
690     opcode = p_data[2];
691   }
692 
693   if (((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) ||
694       ((avrc_cb.ccb[handle].control & AVRC_CT_CONTROL) && (cr == AVCT_RSP))) {
695     switch (opcode) {
696       case AVRC_OP_UNIT_INFO:
697         if (cr == AVCT_CMD) {
698           /* send the response to the peer */
699           p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_UNIT_INFO_RSP_LEN);
700           p_rsp_data = avrc_get_data_ptr(p_rsp);
701           *p_rsp_data = AVRC_RSP_IMPL_STBL;
702           /* check & set the offset. set response code, set subunit_type &
703              subunit_id,
704              set AVRC_OP_UNIT_INFO */
705           /* 3 bytes: ctype, subunit*, opcode */
706           p_rsp_data += AVRC_AVC_HDR_SIZE;
707           *p_rsp_data++ = 7;
708           /* Panel subunit & id=0 */
709           *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT);
710           AVRC_CO_ID_TO_BE_STREAM(p_rsp_data, avrc_cb.ccb[handle].company_id);
711           p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset);
712           cr = AVCT_RSP;
713           p_drop_msg = "auto respond";
714         } else {
715           /* parse response */
716           if (p_pkt->len < AVRC_OP_UNIT_INFO_RSP_LEN) {
717             log::warn("message length {} too short: must be at least {}", p_pkt->len,
718                       AVRC_OP_UNIT_INFO_RSP_LEN);
719             drop = true;
720             p_drop_msg = "UNIT_INFO_RSP too short";
721             break;
722           }
723           p_data += 4; /* 3 bytes: ctype, subunit*, opcode + octet 3 (is 7)*/
724           msg.unit.unit_type = (*p_data & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT;
725           msg.unit.unit = *p_data & AVRC_SUBID_MASK;
726           p_data++;
727           AVRC_BE_STREAM_TO_CO_ID(msg.unit.company_id, p_data);
728         }
729         break;
730 
731       case AVRC_OP_SUB_INFO:
732         if (cr == AVCT_CMD) {
733           /* send the response to the peer */
734           p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_SUB_UNIT_INFO_RSP_LEN);
735           p_rsp_data = avrc_get_data_ptr(p_rsp);
736           *p_rsp_data = AVRC_RSP_IMPL_STBL;
737           /* check & set the offset. set response code, set (subunit_type &
738              subunit_id),
739              set AVRC_OP_SUB_INFO, set (page & extention code) */
740           p_rsp_data += 4;
741           /* Panel subunit & id=0 */
742           *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT);
743           memset(p_rsp_data, AVRC_CMD_OPRND_PAD, AVRC_SUBRSP_OPRND_BYTES);
744           p_rsp_data += AVRC_SUBRSP_OPRND_BYTES;
745           p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset);
746           cr = AVCT_RSP;
747           p_drop_msg = "auto responded";
748         } else {
749           /* parse response */
750           if (p_pkt->len < AVRC_OP_SUB_UNIT_INFO_RSP_LEN) {
751             log::warn("message length {} too short: must be at least {}", p_pkt->len,
752                       AVRC_OP_SUB_UNIT_INFO_RSP_LEN);
753             drop = true;
754             p_drop_msg = "SUB_UNIT_INFO_RSP too short";
755             break;
756           }
757           p_data += AVRC_AVC_HDR_SIZE; /* 3 bytes: ctype, subunit*, opcode */
758           msg.sub.page = (*p_data++ >> AVRC_SUB_PAGE_SHIFT) & AVRC_SUB_PAGE_MASK;
759           xx = 0;
760           while (*p_data != AVRC_CMD_OPRND_PAD && xx < AVRC_SUB_TYPE_LEN) {
761             msg.sub.subunit_type[xx] = *p_data++ >> AVRC_SUBTYPE_SHIFT;
762             if (msg.sub.subunit_type[xx] == AVRC_SUB_PANEL) {
763               msg.sub.panel = true;
764             }
765             xx++;
766           }
767         }
768         break;
769 
770       case AVRC_OP_VENDOR: {
771         p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
772         p_begin = p_data;
773         if (p_pkt->len < AVRC_VENDOR_HDR_SIZE) /* 6 = ctype, subunit*, opcode & CO_ID */
774         {
775           if (cr == AVCT_CMD) {
776             reject = true;
777           } else {
778             drop = true;
779           }
780           break;
781         }
782         p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*,
783                                         opcode */
784         AVRC_BE_STREAM_TO_CO_ID(p_msg->company_id, p_data);
785         p_msg->p_vendor_data = p_data;
786         p_msg->vendor_len = p_pkt->len - (p_data - p_begin);
787 
788         uint8_t drop_code = 0;
789         if (p_msg->company_id == AVRC_CO_METADATA) {
790           /* Validate length for metadata message */
791           if (p_pkt->len < (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE)) {
792             if (cr == AVCT_CMD) {
793               reject = true;
794             } else {
795               drop = true;
796             }
797             break;
798           }
799 
800           /* Check+handle fragmented messages */
801           drop_code = avrc_proc_far_msg(handle, label, cr, &p_pkt, p_msg);
802           if (drop_code > 0) {
803             drop = true;
804           }
805         }
806         if (drop_code > 0) {
807           if (drop_code != 4) {
808             do_free = false;
809           }
810           switch (drop_code) {
811             case 1:
812               p_drop_msg = "sent_frag";
813               break;
814             case 2:
815               p_drop_msg = "req_cont";
816               break;
817             case 3:
818               p_drop_msg = "sent_frag3";
819               break;
820             case 4:
821               p_drop_msg = "sent_frag_free";
822               break;
823             default:
824               p_drop_msg = "sent_fragd";
825           }
826         }
827         /* If vendor response received, and did not ask for continuation */
828         /* then check queue for addition commands to send */
829         if ((cr == AVCT_RSP) && (drop_code != 2)) {
830           avrc_send_next_vendor_cmd(handle);
831         }
832       } break;
833 
834       case AVRC_OP_PASS_THRU:
835         if (p_pkt->len < 5) /* 3 bytes: ctype, subunit*, opcode & op_id & len */
836         {
837           if (cr == AVCT_CMD) {
838             reject = true;
839           } else {
840             drop = true;
841           }
842           break;
843         }
844         p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*,
845                                         opcode */
846         msg.pass.op_id = (AVRC_PASS_OP_ID_MASK & *p_data);
847         if (AVRC_PASS_STATE_MASK & *p_data) {
848           msg.pass.state = true;
849         } else {
850           msg.pass.state = false;
851         }
852         p_data++;
853         msg.pass.pass_len = *p_data++;
854         if (msg.pass.pass_len != p_pkt->len - 5) {
855           msg.pass.pass_len = p_pkt->len - 5;
856         }
857         if (msg.pass.pass_len) {
858           msg.pass.p_pass_data = p_data;
859         } else {
860           msg.pass.p_pass_data = NULL;
861         }
862         break;
863 
864       case AVRC_OP_BROWSE:
865         /* If browse response received, then check queue for addition commands
866          * to send */
867         if (cr == AVCT_RSP) {
868           avrc_send_next_vendor_cmd(handle);
869         }
870         break;
871 
872       default:
873         if ((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) {
874           /* reject unsupported opcode */
875           reject = true;
876         }
877         drop = true;
878         break;
879     }
880   } else /* drop the event */
881   {
882     if (opcode != AVRC_OP_BROWSE) {
883       drop = true;
884     }
885   }
886 
887   if (reject) {
888     /* reject unsupported opcode */
889     p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_REJ_MSG_LEN);
890     p_rsp_data = avrc_get_data_ptr(p_rsp);
891     *p_rsp_data = AVRC_RSP_REJ;
892     p_drop_msg = "rejected";
893     cr = AVCT_RSP;
894     drop = true;
895   }
896 
897   if (p_rsp) {
898     /* set to send response right away */
899     AVCT_MsgReq(handle, label, cr, p_rsp);
900     drop = true;
901   }
902 
903   if (!drop) {
904     msg.hdr.opcode = opcode;
905     avrc_cb.ccb[handle].msg_cback.Run(handle, label, opcode, &msg);
906   } else {
907     log::warn("{} msg handle:{}, control:{}, cr:{}, opcode:x{:x}", p_drop_msg, handle,
908               avrc_cb.ccb[handle].control, cr, opcode);
909   }
910 
911   if (opcode == AVRC_OP_BROWSE && msg.browse.p_browse_pkt == NULL) {
912     do_free = false;
913   }
914 
915   if (do_free) {
916     osi_free(p_pkt);
917   }
918 }
919 
920 /******************************************************************************
921  *
922  * Function         avrc_pass_msg
923  *
924  * Description      Compose a PASS THROUGH command according to p_msg
925  *
926  *                  Input Parameters:
927  *                      p_msg: Pointer to PASS THROUGH message structure.
928  *
929  *                  Output Parameters:
930  *                      None.
931  *
932  * Returns          pointer to a valid GKI buffer if successful.
933  *                  NULL if p_msg is NULL.
934  *
935  *****************************************************************************/
avrc_pass_msg(tAVRC_MSG_PASS * p_msg)936 static BT_HDR* avrc_pass_msg(tAVRC_MSG_PASS* p_msg) {
937   log::assert_that(p_msg != NULL, "assert failed: p_msg != NULL");
938   log::assert_that(AVRC_CMD_BUF_SIZE > (AVRC_MIN_CMD_LEN + p_msg->pass_len),
939                    "assert failed: AVRC_CMD_BUF_SIZE > (AVRC_MIN_CMD_LEN + "
940                    "p_msg->pass_len)");
941 
942   BT_HDR* p_cmd = (BT_HDR*)osi_calloc(AVRC_CMD_BUF_SIZE);
943   p_cmd->offset = AVCT_MSG_OFFSET;
944   p_cmd->layer_specific = AVCT_DATA_CTRL;
945 
946   uint8_t* p_data = (uint8_t*)(p_cmd + 1) + p_cmd->offset;
947   *p_data++ = (p_msg->hdr.ctype & AVRC_CTYPE_MASK);
948   *p_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); /* Panel subunit & id=0 */
949   *p_data++ = AVRC_OP_PASS_THRU;
950   *p_data = (AVRC_PASS_OP_ID_MASK & p_msg->op_id);
951   if (p_msg->state) {
952     *p_data |= AVRC_PASS_STATE_MASK;
953   }
954   p_data++;
955 
956   if (p_msg->op_id == AVRC_ID_VENDOR) {
957     *p_data++ = p_msg->pass_len;
958     if (p_msg->pass_len && p_msg->p_pass_data) {
959       memcpy(p_data, p_msg->p_pass_data, p_msg->pass_len);
960       p_data += p_msg->pass_len;
961     }
962   } else {
963     /* set msg len to 0 for other op_id */
964     *p_data++ = 0;
965   }
966   p_cmd->len = (uint16_t)(p_data - (uint8_t*)(p_cmd + 1) - p_cmd->offset);
967 
968   return p_cmd;
969 }
970 
971 /******************************************************************************
972  *
973  * Function         ARVC_GetControlProfileVersion
974  *
975  * Description      Get the AVRCP profile version
976  *
977  * Returns          The AVRCP control profile version
978  *
979  *****************************************************************************/
AVRC_GetControlProfileVersion()980 uint16_t AVRC_GetControlProfileVersion() {
981   char volume_disabled[PROPERTY_VALUE_MAX] = {0};
982   osi_property_get("persist.bluetooth.disableabsvol", volume_disabled, "false");
983 
984   uint16_t profile_version = AVRC_REV_1_3;
985   char avrcp_version[PROPERTY_VALUE_MAX] = {0};
986   osi_property_get(AVRC_CONTROL_VERSION_PROPERTY, avrcp_version,
987                    strncmp(volume_disabled, "true", 4) == 0 ? AVRC_1_3_STRING : AVRC_1_4_STRING);
988 
989   if (!strncmp(AVRC_1_6_STRING, avrcp_version, sizeof(AVRC_1_6_STRING))) {
990     profile_version = AVRC_REV_1_6;
991   } else if (!strncmp(AVRC_1_5_STRING, avrcp_version, sizeof(AVRC_1_5_STRING))) {
992     profile_version = AVRC_REV_1_5;
993   } else if (!strncmp(AVRC_1_4_STRING, avrcp_version, sizeof(AVRC_1_4_STRING))) {
994     profile_version = AVRC_REV_1_4;
995   }
996 
997   return profile_version;
998 }
999 
1000 /******************************************************************************
1001  *
1002  * Function         ARVC_GetProfileVersion
1003  *
1004  * Description      Get the user assigned AVRCP profile version
1005  *
1006  * Returns          The AVRCP profile version
1007  *
1008  *****************************************************************************/
AVRC_GetProfileVersion()1009 uint16_t AVRC_GetProfileVersion() {
1010   uint16_t profile_version = AVRC_REV_1_4;
1011   char avrcp_version[PROPERTY_VALUE_MAX] = {0};
1012   osi_property_get(AVRC_VERSION_PROPERTY, avrcp_version, AVRC_DEFAULT_VERSION);
1013 
1014   if (!strncmp(AVRC_1_6_STRING, avrcp_version, sizeof(AVRC_1_6_STRING))) {
1015     profile_version = AVRC_REV_1_6;
1016   } else if (!strncmp(AVRC_1_5_STRING, avrcp_version, sizeof(AVRC_1_5_STRING))) {
1017     profile_version = AVRC_REV_1_5;
1018   } else if (!strncmp(AVRC_1_3_STRING, avrcp_version, sizeof(AVRC_1_3_STRING))) {
1019     profile_version = AVRC_REV_1_3;
1020   }
1021 
1022   return profile_version;
1023 }
1024 
1025 /******************************************************************************
1026  *
1027  * Function         AVRC_Open
1028  *
1029  * Description      This function is called to open a connection to AVCTP.
1030  *                  The connection can be either an initiator or acceptor, as
1031  *                  determined by the p_ccb->stream parameter.
1032  *                  The connection can be a target, a controller or for both
1033  *                  role, as determined by the p_ccb->control parameter.
1034  *                  By definition, a target connection is an acceptor connection
1035  *                  that waits for an incoming AVCTP connection from the peer.
1036  *                  The connection remains available to the application until
1037  *                  the application closes it by calling AVRC_Close().  The
1038  *                  application does not need to reopen the connection after an
1039  *                  AVRC_CLOSE_IND_EVT is received.
1040  *
1041  *                  Input Parameters:
1042  *                      p_ccb->company_id: Company Identifier.
1043  *
1044  *                      p_ccb->p_ctrl_cback:  Pointer to control callback
1045  *                                            function.
1046  *
1047  *                      p_ccb->p_msg_cback:  Pointer to message callback
1048  *                                            function.
1049  *
1050  *                      p_ccb->conn: AVCTP connection role.  This is set to
1051  *                      AVCTP_INT for initiator connections and AVCTP_ACP
1052  *                      for acceptor connections.
1053  *
1054  *                      p_ccb->control: Control role.  This is set to
1055  *                      AVRC_CT_TARGET for target connections, AVRC_CT_CONTROL
1056  *                      for control connections or
1057  *                      (AVRC_CT_TARGET|AVRC_CT_CONTROL)
1058  *                      for connections that support both roles.
1059  *
1060  *                      peer_addr: BD address of peer device.  This value is
1061  *                      only used for initiator connections; for acceptor
1062  *                      connections it can be set to NULL.
1063  *
1064  *                  Output Parameters:
1065  *                      p_handle: Pointer to handle.  This parameter is only
1066  *                                valid if AVRC_SUCCESS is returned.
1067  *
1068  * Returns          AVRC_SUCCESS if successful.
1069  *                  AVRC_NO_RESOURCES if there are not enough resources to open
1070  *                  the connection.
1071  *
1072  *****************************************************************************/
AVRC_Open(uint8_t * p_handle,tAVRC_CONN_CB * p_ccb,const RawAddress & peer_addr)1073 uint16_t AVRC_Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, const RawAddress& peer_addr) {
1074   tAVCT_CC cc = {
1075           .p_ctrl_cback = avrc_ctrl_cback,         /* Control callback */
1076           .p_msg_cback = avrc_msg_cback,           /* Message callback */
1077           .pid = UUID_SERVCLASS_AV_REMOTE_CONTROL, /* Profile ID */
1078           .role = p_ccb->conn,                     /* Initiator/acceptor role */
1079           .control = p_ccb->control,               /* Control role (Control/Target) */
1080   };
1081 
1082   uint16_t status = AVCT_CreateConn(p_handle, &cc, peer_addr);
1083   if (status == AVCT_SUCCESS) {
1084     avrc_cb.ccb[*p_handle] = *p_ccb;
1085     memset(&avrc_cb.ccb_int[*p_handle], 0, sizeof(tAVRC_CONN_INT_CB));
1086     memset(&avrc_cb.fcb[*p_handle], 0, sizeof(tAVRC_FRAG_CB));
1087     memset(&avrc_cb.rcb[*p_handle], 0, sizeof(tAVRC_RASM_CB));
1088     avrc_cb.ccb_int[*p_handle].tle = alarm_new("avrcp.commandTimer");
1089     avrc_cb.ccb_int[*p_handle].cmd_q = fixed_queue_new(SIZE_MAX);
1090   }
1091   log::verbose("role: {}, control:0x{:x} status:{}, handle:{}", avct_role_text(cc.role), cc.control,
1092                status, *p_handle);
1093 
1094   return status;
1095 }
1096 
1097 /******************************************************************************
1098  *
1099  * Function         AVRC_Close
1100  *
1101  * Description      Close a connection opened with AVRC_Open().
1102  *                  This function is called when the
1103  *                  application is no longer using a connection.
1104  *
1105  *                  Input Parameters:
1106  *                      handle: Handle of this connection.
1107  *
1108  *                  Output Parameters:
1109  *                      None.
1110  *
1111  * Returns          AVRC_SUCCESS if successful.
1112  *                  AVRC_BAD_HANDLE if handle is invalid.
1113  *
1114  *****************************************************************************/
AVRC_Close(uint8_t handle)1115 uint16_t AVRC_Close(uint8_t handle) {
1116   log::verbose("handle:{}", handle);
1117   avrc_flush_cmd_q(handle);
1118   return AVCT_RemoveConn(handle);
1119 }
1120 
1121 /******************************************************************************
1122  *
1123  * Function         AVRC_OpenBrowse
1124  *
1125  * Description      This function is called to open a browsing connection to
1126  *                  AVCTP. The connection can be either an initiator or
1127  *                  acceptor, as determined by the p_conn_role.
1128  *                  The handle is returned by a previous call to AVRC_Open.
1129  *
1130  * Returns          AVRC_SUCCESS if successful.
1131  *                  AVRC_NO_RESOURCES if there are not enough resources to open
1132  *                  the connection.
1133  *
1134  *****************************************************************************/
AVRC_OpenBrowse(uint8_t handle,tAVCT_ROLE conn_role)1135 uint16_t AVRC_OpenBrowse(uint8_t handle, tAVCT_ROLE conn_role) {
1136   return AVCT_CreateBrowse(handle, conn_role);
1137 }
1138 
1139 /******************************************************************************
1140  *
1141  * Function         AVRC_CloseBrowse
1142  *
1143  * Description      Close a connection opened with AVRC_OpenBrowse().
1144  *                  This function is called when the
1145  *                  application is no longer using a connection.
1146  *
1147  * Returns          AVRC_SUCCESS if successful.
1148  *                  AVRC_BAD_HANDLE if handle is invalid.
1149  *
1150  *****************************************************************************/
AVRC_CloseBrowse(uint8_t handle)1151 uint16_t AVRC_CloseBrowse(uint8_t handle) { return AVCT_RemoveBrowse(handle); }
1152 
1153 /******************************************************************************
1154  *
1155  * Function         AVRC_MsgReq
1156  *
1157  * Description      This function is used to send the AVRCP byte stream in p_pkt
1158  *                  down to AVCTP.
1159  *
1160  *                  It is expected that p_pkt->offset is at least
1161  *                  AVCT_MSG_OFFSET
1162  *                  p_pkt->layer_specific is AVCT_DATA_CTRL or AVCT_DATA_BROWSE
1163  *                  p_pkt->event is AVRC_OP_VENDOR, AVRC_OP_PASS_THRU or
1164  *                  AVRC_OP_BROWSE
1165  *                  The above BT_HDR settings are set by the AVRC_Bld*
1166  *                  functions.
1167  *
1168  * Returns          AVRC_SUCCESS if successful.
1169  *                  AVRC_BAD_HANDLE if handle is invalid.
1170  *
1171  *****************************************************************************/
1172 /* legacy and new avrcp send the different packet format for VENDOR op */
AVRC_MsgReq(uint8_t handle,uint8_t label,uint8_t ctype,BT_HDR * p_pkt,bool is_new_avrcp)1173 uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, BT_HDR* p_pkt,
1174                      bool is_new_avrcp) {
1175   uint8_t* p_data;
1176   uint8_t cr = AVCT_CMD;
1177   bool chk_frag = true;
1178   uint8_t* p_start = NULL;
1179   tAVRC_FRAG_CB* p_fcb;
1180   uint16_t len;
1181   uint16_t status;
1182   uint8_t msg_mask = 0;
1183   uint16_t peer_mtu;
1184 
1185   if (!p_pkt) {
1186     return AVRC_BAD_PARAM;
1187   }
1188 
1189   log::verbose("handle = {} label = {} ctype = {} len = {}", handle, label, ctype, p_pkt->len);
1190   /* Handle for AVRCP fragment */
1191   if (btif_av_src_sink_coexist_enabled()) {
1192     is_new_avrcp = osi_property_get_bool("bluetooth.profile.avrcp.target.enabled", false);
1193   }
1194   if (ctype >= AVRC_RSP_NOT_IMPL) {
1195     cr = AVCT_RSP;
1196   }
1197 
1198   if (p_pkt->event == AVRC_OP_VENDOR) {
1199     if (is_new_avrcp) {
1200       p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset + AVRC_VENDOR_HDR_SIZE;
1201     } else {
1202       /* add AVRCP Vendor Dependent headers */
1203       p_start = ((uint8_t*)(p_pkt + 1) + p_pkt->offset);
1204       p_pkt->offset -= AVRC_VENDOR_HDR_SIZE;
1205       p_pkt->len += AVRC_VENDOR_HDR_SIZE;
1206       p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
1207       *p_data++ = (ctype & AVRC_CTYPE_MASK);
1208       *p_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT);
1209       *p_data++ = AVRC_OP_VENDOR;
1210       AVRC_CO_ID_TO_BE_STREAM(p_data, AVRC_CO_METADATA);
1211 
1212       /* Check if this is a AVRC_PDU_REQUEST_CONTINUATION_RSP */
1213       if (cr == AVCT_CMD) {
1214         msg_mask |= AVRC_MSG_MASK_IS_VENDOR_CMD;
1215 
1216         if ((*p_start == AVRC_PDU_REQUEST_CONTINUATION_RSP) ||
1217             (*p_start == AVRC_PDU_ABORT_CONTINUATION_RSP)) {
1218           msg_mask |= AVRC_MSG_MASK_IS_CONTINUATION_RSP;
1219         }
1220       }
1221     }
1222   } else if (p_pkt->event == AVRC_OP_PASS_THRU) {
1223     /* add AVRCP Pass Through headers */
1224     p_start = ((uint8_t*)(p_pkt + 1) + p_pkt->offset);
1225     p_pkt->offset -= AVRC_PASS_THRU_SIZE;
1226     p_pkt->len += AVRC_PASS_THRU_SIZE;
1227     p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
1228     *p_data++ = (ctype & AVRC_CTYPE_MASK);
1229     *p_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT);
1230     *p_data++ = AVRC_OP_PASS_THRU; /* opcode */
1231     *p_data++ = AVRC_ID_VENDOR;    /* operation id */
1232     *p_data++ = 5;                 /* operation data len */
1233     AVRC_CO_ID_TO_BE_STREAM(p_data, AVRC_CO_METADATA);
1234   } else {
1235     chk_frag = false;
1236     if (p_pkt->layer_specific == AVCT_DATA_BROWSE) {
1237       peer_mtu = AVCT_GetBrowseMtu(handle);
1238     } else {
1239       peer_mtu = AVCT_GetPeerMtu(handle);
1240     }
1241     if (p_pkt->len > (peer_mtu - AVCT_HDR_LEN_SINGLE)) {
1242       log::error("bigger than peer mtu (p_pkt->len({}) > peer_mtu({}-{}))", p_pkt->len, peer_mtu,
1243                  AVCT_HDR_LEN_SINGLE);
1244       osi_free(p_pkt);
1245       return AVRC_MSG_TOO_BIG;
1246     }
1247   }
1248 
1249   /* abandon previous fragments */
1250   p_fcb = &avrc_cb.fcb[handle];
1251 
1252   if (p_fcb == NULL) {
1253     log::error("p_fcb is NULL");
1254     osi_free(p_pkt);
1255     return AVRC_NOT_OPEN;
1256   }
1257 
1258   if (p_fcb->frag_enabled) {
1259     p_fcb->frag_enabled = false;
1260   }
1261 
1262   osi_free_and_reset((void**)&p_fcb->p_fmsg);
1263 
1264   /* AVRCP spec has not defined any control channel commands that needs
1265    * fragmentation at this level
1266    * check for fragmentation only on the response */
1267   if ((cr == AVCT_RSP) && (chk_frag)) {
1268     if (p_pkt->len > AVRC_MAX_CTRL_DATA_LEN) {
1269       int offset_len = MAX(AVCT_MSG_OFFSET, p_pkt->offset);
1270       BT_HDR* p_pkt_new = (BT_HDR*)osi_calloc(AVRC_PACKET_LEN + offset_len + BT_HDR_SIZE);
1271       if (p_start != NULL) {
1272         p_fcb->frag_enabled = true;
1273         p_fcb->p_fmsg = p_pkt;
1274         p_fcb->frag_pdu = *p_start;
1275         p_pkt = p_pkt_new;
1276         p_pkt_new = p_fcb->p_fmsg;
1277         p_pkt->len = AVRC_MAX_CTRL_DATA_LEN;
1278         p_pkt->offset = p_pkt_new->offset;
1279         p_pkt->layer_specific = p_pkt_new->layer_specific;
1280         p_pkt->event = p_pkt_new->event;
1281         p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
1282         p_start -= AVRC_VENDOR_HDR_SIZE;
1283         memcpy(p_data, p_start, AVRC_MAX_CTRL_DATA_LEN);
1284         /* use AVRC start packet type */
1285         p_data += AVRC_VENDOR_HDR_SIZE;
1286         p_data++; /* pdu */
1287         *p_data++ = AVRC_PKT_START;
1288 
1289         /* 4 pdu, pkt_type & len */
1290         len = (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE);
1291         UINT16_TO_BE_STREAM(p_data, len);
1292 
1293         /* prepare the left over for as an end fragment */
1294         avrc_prep_end_frag(handle);
1295         log::verbose("p_pkt len:{}/{}, next len:{}", p_pkt->len, len, p_fcb->p_fmsg->len);
1296       } else {
1297         /* TODO: Is this "else" block valid? Remove it? */
1298         log::error("no buffers for fragmentation");
1299         osi_free(p_pkt);
1300         return AVRC_NO_RESOURCES;
1301       }
1302     }
1303   } else if ((p_pkt->event == AVRC_OP_VENDOR) && (cr == AVCT_CMD) &&
1304              (avrc_cb.ccb_int[handle].flags & AVRC_CB_FLAGS_RSP_PENDING) &&
1305              !(msg_mask & AVRC_MSG_MASK_IS_CONTINUATION_RSP)) {
1306     /* If we are sending a vendor specific command, and a response is pending,
1307      * then enqueue the command until the response has been received.
1308      * This is to interop with TGs that abort sending responses whenever a new
1309      * command
1310      * is received (exception is continuation request command
1311      * must sent that to get additional response frags) */
1312     log::verbose("AVRC: Enqueuing command 0x{} (handle=0x{:02x}, label=0x{:02x})",
1313                  std::format_ptr(p_pkt), handle, label);
1314 
1315     /* label in BT_HDR (will need this later when the command is dequeued) */
1316     p_pkt->layer_specific = (label << 8) | (p_pkt->layer_specific & 0xFF);
1317 
1318     /* Enqueue the command */
1319     fixed_queue_enqueue(avrc_cb.ccb_int[handle].cmd_q, p_pkt);
1320     return AVRC_SUCCESS;
1321   }
1322 
1323   /* Send the message */
1324   status = AVCT_MsgReq(handle, label, cr, p_pkt);
1325   if ((status == AVCT_SUCCESS) && (cr == AVCT_CMD)) {
1326     /* If a command was successfully sent, indicate that a response is pending
1327      */
1328     avrc_cb.ccb_int[handle].flags |= AVRC_CB_FLAGS_RSP_PENDING;
1329 
1330     /* Start command timer to wait for response */
1331     avrc_start_cmd_timer(handle, label, msg_mask);
1332   }
1333 
1334   return status;
1335 }
1336 
1337 /******************************************************************************
1338  *
1339  * Function         AVRC_PassCmd
1340  *
1341  * Description      Send a PASS THROUGH command to the peer device.  This
1342  *                  function can only be called for controller role connections.
1343  *                  Any response message from the peer is passed back through
1344  *                  the tAVRC_MSG_CBACK callback function.
1345  *
1346  *                  Input Parameters:
1347  *                      handle: Handle of this connection.
1348  *
1349  *                      label: Transaction label.
1350  *
1351  *                      p_msg: Pointer to PASS THROUGH message structure.
1352  *
1353  *                  Output Parameters:
1354  *                      None.
1355  *
1356  * Returns          AVRC_SUCCESS if successful.
1357  *                  AVRC_BAD_HANDLE if handle is invalid.
1358  *
1359  *****************************************************************************/
AVRC_PassCmd(uint8_t handle,uint8_t label,tAVRC_MSG_PASS * p_msg)1360 uint16_t AVRC_PassCmd(uint8_t handle, uint8_t label, tAVRC_MSG_PASS* p_msg) {
1361   BT_HDR* p_buf;
1362   uint16_t status = AVRC_NO_RESOURCES;
1363   if (!p_msg) {
1364     return AVRC_BAD_PARAM;
1365   }
1366 
1367   p_msg->hdr.ctype = AVRC_CMD_CTRL;
1368   p_buf = avrc_pass_msg(p_msg);
1369   if (p_buf) {
1370     status = AVCT_MsgReq(handle, label, AVCT_CMD, p_buf);
1371     if (status == AVCT_SUCCESS) {
1372       /* Start command timer to wait for response */
1373       avrc_start_cmd_timer(handle, label, 0);
1374     }
1375   }
1376   return status;
1377 }
1378 
1379 /******************************************************************************
1380  *
1381  * Function         AVRC_PassRsp
1382  *
1383  * Description      Send a PASS THROUGH response to the peer device.  This
1384  *                  function can only be called for target role connections.
1385  *                  This function must be called when a PASS THROUGH command
1386  *                  message is received from the peer through the
1387  *                  tAVRC_MSG_CBACK callback function.
1388  *
1389  *                  Input Parameters:
1390  *                      handle: Handle of this connection.
1391  *
1392  *                      label: Transaction label.  Must be the same value as
1393  *                      passed with the command message in the callback
1394  *                      function.
1395  *
1396  *                      p_msg: Pointer to PASS THROUGH message structure.
1397  *
1398  *                  Output Parameters:
1399  *                      None.
1400  *
1401  * Returns          AVRC_SUCCESS if successful.
1402  *                  AVRC_BAD_HANDLE if handle is invalid.
1403  *
1404  *****************************************************************************/
AVRC_PassRsp(uint8_t handle,uint8_t label,tAVRC_MSG_PASS * p_msg)1405 uint16_t AVRC_PassRsp(uint8_t handle, uint8_t label, tAVRC_MSG_PASS* p_msg) {
1406   BT_HDR* p_buf;
1407   if (!p_msg) {
1408     return AVRC_BAD_PARAM;
1409   }
1410 
1411   p_buf = avrc_pass_msg(p_msg);
1412   if (p_buf) {
1413     return AVCT_MsgReq(handle, label, AVCT_RSP, p_buf);
1414   }
1415   return AVRC_NO_RESOURCES;
1416 }
1417 
1418 /******************************************************************************
1419  *
1420  * Function         AVRC_SaveControllerVersion
1421  *
1422  * Description      Save AVRC controller version of peer device into bt_config.
1423  *                  This version is used to send same AVRC target version to
1424  *                  peer device to avoid version mismatch IOP issue.
1425  *
1426  *                  Input Parameters:
1427  *                      bdaddr: BD address of peer device.
1428  *
1429  *                      version: AVRC controller version of peer device.
1430  *
1431  *                  Output Parameters:
1432  *                      None.
1433  *
1434  * Returns          Nothing
1435  *
1436  *****************************************************************************/
AVRC_SaveControllerVersion(const RawAddress & bdaddr,uint16_t new_version)1437 void AVRC_SaveControllerVersion(const RawAddress& bdaddr, uint16_t new_version) {
1438   // store AVRC controller version into BT config
1439   uint16_t old_version = 0;
1440   size_t version_value_size = sizeof(old_version);
1441   if (btif_config_get_bin(bdaddr.ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION,
1442                           (uint8_t*)&old_version, &version_value_size) &&
1443       new_version == old_version) {
1444     log::info("AVRC controller version same as cached config");
1445   } else if (btif_config_set_bin(bdaddr.ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION,
1446                                  (const uint8_t*)&new_version, sizeof(new_version))) {
1447     log::info("store AVRC controller version {:x} for {} into config.", new_version, bdaddr);
1448   } else {
1449     log::warn("Failed to store AVRC controller version for {}", bdaddr);
1450   }
1451 }
1452 
AVRC_UpdateCcb(RawAddress * addr,uint32_t company_id)1453 void AVRC_UpdateCcb(RawAddress* addr, uint32_t company_id) {
1454   for (uint8_t i = 0; i < AVCT_NUM_CONN; i++) {
1455     log::info("handle:{}, update cback:0x{:0x}", i, company_id);
1456     if (avrc_cb.ccb[i].company_id == company_id) {
1457       avrc_cb.ccb[i].ctrl_cback.Run(i, AVRC_CLOSE_IND_EVT, 0, addr);
1458     }
1459   }
1460 }
1461