xref: /btstack/src/classic/avrcp.c (revision 08a78038ba366a6a2a2df8fea05d5123880fdff2)
1 /*
2  * Copyright (C) 2016 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "avrcp.c"
39 
40 #include <stdint.h>
41 #include <string.h>
42 // snprintf
43 #include <stdio.h>
44 
45 #include "bluetooth_psm.h"
46 #include "bluetooth_sdp.h"
47 #include "btstack_debug.h"
48 #include "btstack_event.h"
49 #include "btstack_memory.h"
50 #include "classic/avrcp.h"
51 #include "classic/sdp_client.h"
52 #include "classic/sdp_util.h"
53 
54 
55 typedef struct {
56     uint8_t  parse_sdp_record;
57     uint32_t record_id;
58     uint16_t avrcp_cid;
59     uint16_t avrcp_l2cap_psm;
60     uint16_t avrcp_version;
61 
62     uint16_t browsing_l2cap_psm;
63     uint16_t browsing_version;
64     uint16_t cover_art_l2cap_psm;
65 } avrcp_sdp_query_context_t;
66 
67 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
68 static void avrcp_start_next_sdp_query(void);
69 
70 static const char * avrcp_default_controller_service_name = "AVRCP Controller";
71 static const char * avrcp_default_controller_service_provider_name = "BlueKitchen";
72 static const char * avrcp_default_target_service_name = "AVRCP Target";
73 static const char * avrcp_default_target_service_provider_name = "BlueKitchen";
74 
75 static const char * avrcp_subunit_type_name[] = {
76         "MONITOR", "AUDIO", "PRINTER", "DISC", "TAPE_RECORDER_PLAYER", "TUNER",
77         "CA", "CAMERA", "RESERVED", "PANEL", "BULLETIN_BOARD", "CAMERA_STORAGE",
78         "VENDOR_UNIQUE", "RESERVED_FOR_ALL_SUBUNIT_TYPES",
79         "EXTENDED_TO_NEXT_BYTE", "UNIT", "ERROR"
80 };
81 
82 // default subunit info: single PANEL subunit
83 static const uint8_t avrcp_default_subunit_info[] = { AVRCP_SUBUNIT_TYPE_PANEL << 3};
84 
85 // globals
86 static bool avrcp_l2cap_service_registered = false;
87 
88 // connections
89 static uint16_t                 avrcp_cid_counter;
90 static btstack_linked_list_t    avrcp_connections;
91 
92 // higher layer callbacks
93 static btstack_packet_handler_t avrcp_callback;
94 static btstack_packet_handler_t avrcp_controller_packet_handler;
95 static btstack_packet_handler_t avrcp_target_packet_handler;
96 
97 // sdp query
98 static btstack_context_callback_registration_t avrcp_sdp_query_registration;
99 static avrcp_sdp_query_context_t               avrcp_sdp_query_context;
100 static uint8_t                                 avrcp_sdp_query_attribute_value[45];
101 static const unsigned int                      avrcp_sdp_query_attribute_value_buffer_size = sizeof(avrcp_sdp_query_attribute_value);
102 
103 static void (*avrcp_browsing_sdp_query_complete_handler)(avrcp_connection_t * connection, uint8_t status);
104 #ifdef ENABLE_AVRCP_COVER_ART
105 static void (*avrcp_cover_art_sdp_query_complete_handler)(avrcp_connection_t * connection, uint8_t status);
106 #endif
107 
108 const char * avrcp_subunit2str(uint16_t index){
109     if (index <= 11) return avrcp_subunit_type_name[index];
110     if ((index >= 0x1C) && (index <= 0x1F)) return avrcp_subunit_type_name[index - 0x10];
111     return avrcp_subunit_type_name[16];
112 }
113 
114 static const char * avrcp_event_name[] = {
115     "ERROR", "PLAYBACK_STATUS_CHANGED",
116     "TRACK_CHANGED", "TRACK_REACHED_END", "TRACK_REACHED_START",
117     "PLAYBACK_POS_CHANGED", "BATT_STATUS_CHANGED", "SYSTEM_STATUS_CHANGED",
118     "PLAYER_APPLICATION_SETTING_CHANGED", "NOW_PLAYING_CONTENT_CHANGED",
119     "AVAILABLE_PLAYERS_CHANGED", "ADDRESSED_PLAYER_CHANGED", "UIDS_CHANGED", "VOLUME_CHANGED"
120 };
121 const char * avrcp_event2str(uint16_t index){
122     if (index <= 0x0d) return avrcp_event_name[index];
123     return avrcp_event_name[0];
124 }
125 
126 static const char * avrcp_operation_name[] = {
127     "SKIP", NULL, NULL, NULL, NULL,
128     "VOLUME_UP", "VOLUME_DOWN", "MUTE", "PLAY", "STOP", "PAUSE", NULL,
129     "REWIND", "FAST_FORWARD", NULL, "FORWARD", "BACKWARD" // 0x4C
130 };
131 
132 const char * avrcp_operation2str(uint8_t operation_id){
133     char * name = NULL;
134     if ((operation_id >= AVRCP_OPERATION_ID_SKIP) && (operation_id <= AVRCP_OPERATION_ID_BACKWARD)){
135         name = (char *)avrcp_operation_name[operation_id - AVRCP_OPERATION_ID_SKIP];
136     }
137     if (name == NULL){
138         static char buffer[13];
139         snprintf(buffer, sizeof(buffer), "Unknown 0x%02x", operation_id);
140         buffer[sizeof(buffer)-1] = 0;
141         return buffer;
142     } else {
143         return name;
144     }
145 }
146 
147 static const char * avrcp_media_attribute_id_name[] = {
148     "NONE", "TITLE", "ARTIST", "ALBUM", "TRACK", "TOTAL TRACKS", "GENRE", "SONG LENGTH"
149 };
150 const char * avrcp_attribute2str(uint8_t index){
151     if (index > 7){
152         index = 0;
153     }
154     return avrcp_media_attribute_id_name[0];
155 }
156 
157 static const char * avrcp_play_status_name[] = {
158     "STOPPED", "PLAYING", "PAUSED", "FORWARD SEEK", "REVERSE SEEK",
159     "ERROR" // 0xFF
160 };
161 const char * avrcp_play_status2str(uint8_t index){
162     if (index > 4){
163         index = 5;
164     }
165     return avrcp_play_status_name[index];
166 }
167 
168 static const char * avrcp_ctype_name[] = {
169     "CONTROL",
170     "STATUS",
171     "SPECIFIC_INQUIRY",
172     "NOTIFY",
173     "GENERAL_INQUIRY",
174     "RESERVED5",
175     "RESERVED6",
176     "RESERVED7",
177     "NOT IMPLEMENTED IN REMOTE",
178     "ACCEPTED BY REMOTE",
179     "REJECTED BY REMOTE",
180     "IN_TRANSITION",
181     "IMPLEMENTED_STABLE",
182     "CHANGED_STABLE",
183     "RESERVED",
184     "INTERIM"
185 };
186 static const uint16_t avrcp_ctype_name_num = 16;
187 
188 const char * avrcp_ctype2str(uint8_t index){
189     if (index < avrcp_ctype_name_num){
190         return avrcp_ctype_name[index];
191     }
192     return "NONE";
193 }
194 
195 static const char * avrcp_shuffle_mode_name[] = {
196     "SHUFFLE OFF",
197     "SHUFFLE ALL TRACKS",
198     "SHUFFLE GROUP"
199 };
200 
201 const char * avrcp_shuffle2str(uint8_t index){
202     if ((index >= 1) && (index <= 3)) return avrcp_shuffle_mode_name[index-1];
203     return "NONE";
204 }
205 
206 static const char * avrcp_repeat_mode_name[] = {
207     "REPEAT OFF",
208     "REPEAT SINGLE TRACK",
209     "REPEAT ALL TRACKS",
210     "REPEAT GROUP"
211 };
212 
213 const char * avrcp_repeat2str(uint8_t index){
214     if ((index >= 1) && (index <= 4)) return avrcp_repeat_mode_name[index-1];
215     return "NONE";
216 }
217 
218 static const char * notification_name[] = {
219     "INVALID_INDEX",
220     "PLAYBACK_STATUS_CHANGED",
221     "TRACK_CHANGED",
222     "TRACK_REACHED_END",
223     "TRACK_REACHED_START",
224     "PLAYBACK_POS_CHANGED",
225     "BATT_STATUS_CHANGED",
226     "SYSTEM_STATUS_CHANGED",
227     "PLAYER_APPLICATION_SETTING_CHANGED",
228     "NOW_PLAYING_CONTENT_CHANGED",
229     "AVAILABLE_PLAYERS_CHANGED",
230     "ADDRESSED_PLAYER_CHANGED",
231     "UIDS_CHANGED",
232     "VOLUME_CHANGED",
233     "MAX_VALUE"
234 };
235 
236 const char * avrcp_notification2str(avrcp_notification_event_id_t index){
237     if ((index >= AVRCP_NOTIFICATION_EVENT_FIRST_INDEX) && (index <= AVRCP_NOTIFICATION_EVENT_LAST_INDEX)){
238         return notification_name[index];
239     }
240     return notification_name[0];
241 }
242 
243 btstack_linked_list_t avrcp_get_connections(void){
244     return avrcp_connections;
245 }
246 
247 uint8_t avrcp_cmd_opcode(uint8_t *packet, uint16_t size){
248     uint8_t cmd_opcode_index = 5;
249     if (cmd_opcode_index > size) return AVRCP_CMD_OPCODE_UNDEFINED;
250     return packet[cmd_opcode_index];
251 }
252 
253 void avrcp_create_sdp_record(bool controller, uint8_t * service, uint32_t service_record_handle, uint8_t browsing, uint16_t supported_features,
254                              const char * service_name, const char * service_provider_name){
255     uint8_t* attribute;
256     de_create_sequence(service);
257 
258     // 0x0000 "Service Record Handle"
259     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
260     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
261 
262     // 0x0001 "Service Class ID List"
263     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
264     attribute = de_push_sequence(service);
265     {
266         if (controller){
267             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL);
268             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_CONTROLLER);
269         } else {
270             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_TARGET);
271         }
272     }
273     de_pop_sequence(service, attribute);
274 
275     // 0x0004 "Protocol Descriptor List"
276     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
277     attribute = de_push_sequence(service);
278     {
279         uint8_t* l2cpProtocol = de_push_sequence(attribute);
280         {
281             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
282             de_add_number(l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PSM_AVCTP);
283         }
284         de_pop_sequence(attribute, l2cpProtocol);
285 
286         uint8_t* avctpProtocol = de_push_sequence(attribute);
287         {
288             de_add_number(avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // avctpProtocol_service
289             de_add_number(avctpProtocol,  DE_UINT, DE_SIZE_16,  0x0104);    // version
290         }
291         de_pop_sequence(attribute, avctpProtocol);
292     }
293     de_pop_sequence(service, attribute);
294 
295     // 0x0005 "Public Browse Group"
296     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
297     attribute = de_push_sequence(service);
298     {
299         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
300     }
301     de_pop_sequence(service, attribute);
302 
303     // 0x0009 "Bluetooth Profile Descriptor List"
304     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
305     attribute = de_push_sequence(service);
306     {
307         uint8_t *avrcProfile = de_push_sequence(attribute);
308         {
309             de_add_number(avrcProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL);
310             de_add_number(avrcProfile,  DE_UINT, DE_SIZE_16, 0x0106);
311         }
312         de_pop_sequence(attribute, avrcProfile);
313     }
314     de_pop_sequence(service, attribute);
315 
316     // 0x000d "Additional Bluetooth Profile Descriptor List"
317     if (browsing){
318         de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS);
319         attribute = de_push_sequence(service);
320         {
321             uint8_t * des = de_push_sequence(attribute);
322             {
323                 uint8_t* browsing_l2cpProtocol = de_push_sequence(des);
324                 {
325                     de_add_number(browsing_l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
326                     de_add_number(browsing_l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PSM_AVCTP_BROWSING);
327                 }
328                 de_pop_sequence(des, browsing_l2cpProtocol);
329 
330                 uint8_t* browsing_avctpProtocol = de_push_sequence(des);
331                 {
332                     de_add_number(browsing_avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // browsing_avctpProtocol_service
333                     de_add_number(browsing_avctpProtocol,  DE_UINT, DE_SIZE_16, 0x0104);                   // version
334                 }
335                 de_pop_sequence(des, browsing_avctpProtocol);
336             }
337             de_pop_sequence(attribute, des);
338         }
339         de_pop_sequence(service, attribute);
340     }
341 
342 
343     // 0x0100 "Service Name"
344     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
345     if (service_name){
346         de_add_data(service,  DE_STRING, (uint16_t) strlen(service_name), (uint8_t *) service_name);
347     } else {
348         if (controller){
349             de_add_data(service, DE_STRING, (uint16_t) strlen(avrcp_default_controller_service_name), (uint8_t *) avrcp_default_controller_service_name);
350         } else {
351             de_add_data(service, DE_STRING, (uint16_t) strlen(avrcp_default_target_service_name), (uint8_t *) avrcp_default_target_service_name);
352         }
353     }
354 
355     // 0x0100 "Provider Name"
356     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0102);
357     if (service_provider_name){
358         de_add_data(service,  DE_STRING, (uint16_t) strlen(service_provider_name), (uint8_t *) service_provider_name);
359     } else {
360         if (controller){
361             de_add_data(service, DE_STRING, (uint16_t) strlen(avrcp_default_controller_service_provider_name), (uint8_t *) avrcp_default_controller_service_provider_name);
362         } else {
363             de_add_data(service, DE_STRING, (uint16_t) strlen(avrcp_default_target_service_provider_name), (uint8_t *) avrcp_default_target_service_provider_name);
364         }
365     }
366 
367     // 0x0311 "Supported Features"
368     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SUPPORTED_FEATURES);
369     de_add_number(service, DE_UINT, DE_SIZE_16, supported_features);
370 }
371 
372 uint16_t avctp_get_num_bytes_for_header(avctp_packet_type_t avctp_packet_type) {
373     switch (avctp_packet_type){
374         case AVCTP_SINGLE_PACKET:
375             // AVCTP message: transport header (1), pid (2)
376             return 3;
377         case AVCTP_START_PACKET:
378             // AVCTP message: transport header (1), num_packets (1), pid (2)
379             return 4;
380         default:
381             // AVCTP message: transport header (1)
382             return 1;
383     }
384 }
385 
386 uint16_t avrcp_get_num_bytes_for_header(avrcp_command_opcode_t command_opcode, avctp_packet_type_t avctp_packet_type) {
387     switch (avctp_packet_type){
388         case AVCTP_SINGLE_PACKET:
389         case AVCTP_START_PACKET:
390             break;
391         default:
392             return 0;
393     }
394 
395     uint16_t offset = 3; // AVRCP message: cmd type (1), subunit (1), opcode (1)
396     switch (command_opcode){
397         case AVRCP_CMD_OPCODE_VENDOR_DEPENDENT:
398             offset += 7; // AVRCP message:  company (3), pdu id(1), AVRCP packet type (1), param_len (2)
399             break;
400         case AVRCP_CMD_OPCODE_PASS_THROUGH:
401             offset += 3;  // AVRCP message: operation id (1), param_len (2)
402             break;
403         default:
404             break;
405     }
406     return offset;
407 }
408 
409 static uint16_t avrcp_get_num_free_bytes_for_payload(uint16_t l2cap_mtu, avrcp_command_opcode_t command_opcode, avctp_packet_type_t avctp_packet_type){
410     uint16_t max_frame_size = btstack_min(l2cap_mtu, AVRCP_MAX_AV_C_MESSAGE_FRAME_SIZE);
411     uint16_t payload_offset = avctp_get_num_bytes_for_header(avctp_packet_type) +
412                               avrcp_get_num_bytes_for_header(command_opcode, avctp_packet_type);
413 
414     btstack_assert(max_frame_size >= payload_offset);
415     return (max_frame_size - payload_offset);
416 }
417 
418 
419 avctp_packet_type_t avctp_get_packet_type(avrcp_connection_t * connection, uint16_t * max_payload_size){
420     if (connection->l2cap_mtu >= AVRCP_MAX_AV_C_MESSAGE_FRAME_SIZE){
421         return AVCTP_SINGLE_PACKET;
422     }
423 
424     if (connection->data_offset == 0){
425         uint16_t max_payload_size_for_single_packet = avrcp_get_num_free_bytes_for_payload(connection->l2cap_mtu,
426                                                                  connection->command_opcode,
427                                                                  AVCTP_SINGLE_PACKET);
428         if (max_payload_size_for_single_packet >= connection->data_len){
429             *max_payload_size = max_payload_size_for_single_packet;
430             return AVCTP_SINGLE_PACKET;
431         } else {
432             uint16_t max_payload_size_for_start_packet = max_payload_size_for_single_packet - 1;
433             *max_payload_size = max_payload_size_for_start_packet;
434             return AVCTP_START_PACKET;
435         }
436     } else {
437         // both packet types have the same single byte AVCTP header
438         *max_payload_size = avrcp_get_num_free_bytes_for_payload(connection->l2cap_mtu,
439                                                                  connection->command_opcode,
440                                                                  AVCTP_CONTINUE_PACKET);
441         if ((connection->data_len - connection->data_offset) > *max_payload_size){
442             return AVCTP_CONTINUE_PACKET;
443         } else {
444             return AVCTP_END_PACKET;
445         }
446     }
447 }
448 
449 avrcp_packet_type_t avrcp_get_packet_type(avrcp_connection_t * connection){
450     switch (connection->avctp_packet_type) {
451         case AVCTP_SINGLE_PACKET:
452         case AVCTP_START_PACKET:
453             break;
454         default:
455             return connection->avrcp_packet_type;
456     }
457 
458     uint16_t payload_offset = avctp_get_num_bytes_for_header(connection->avctp_packet_type) +
459                               avrcp_get_num_bytes_for_header(connection->command_opcode, connection->avctp_packet_type);
460     uint16_t bytes_to_send = (connection->data_len - connection->data_offset) + payload_offset;
461 
462     if (connection->data_offset == 0){
463         if (bytes_to_send <= AVRCP_MAX_AV_C_MESSAGE_FRAME_SIZE){
464             return AVRCP_SINGLE_PACKET;
465         } else {
466             return AVRCP_START_PACKET;
467         }
468     } else {
469         if (bytes_to_send > AVRCP_MAX_AV_C_MESSAGE_FRAME_SIZE){
470             return AVRCP_CONTINUE_PACKET;
471         } else {
472             return AVRCP_END_PACKET;
473         }
474     }
475 }
476 
477 avrcp_connection_t * avrcp_get_connection_for_bd_addr_for_role(avrcp_role_t role, bd_addr_t addr){
478     btstack_linked_list_iterator_t it;
479     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
480     while (btstack_linked_list_iterator_has_next(&it)){
481         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
482         if (connection->role != role) continue;
483         if (memcmp(addr, connection->remote_addr, 6) != 0) continue;
484         return connection;
485     }
486     return NULL;
487 }
488 
489 avrcp_connection_t * avrcp_get_connection_for_l2cap_signaling_cid_for_role(avrcp_role_t role, uint16_t l2cap_cid){
490     btstack_linked_list_iterator_t it;
491     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
492     while (btstack_linked_list_iterator_has_next(&it)){
493         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
494         if (connection->role != role) continue;
495         if (connection->l2cap_signaling_cid != l2cap_cid) continue;
496         return connection;
497     }
498     return NULL;
499 }
500 
501 avrcp_connection_t * avrcp_get_connection_for_avrcp_cid_for_role(avrcp_role_t role, uint16_t avrcp_cid){
502     btstack_linked_list_iterator_t it;
503     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
504     while (btstack_linked_list_iterator_has_next(&it)){
505         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
506         if (connection->role != role) continue;
507         if (connection->avrcp_cid != avrcp_cid) continue;
508         return connection;
509     }
510     return NULL;
511 }
512 
513 avrcp_connection_t * avrcp_get_connection_for_browsing_cid_for_role(avrcp_role_t role, uint16_t browsing_cid){
514     btstack_linked_list_iterator_t it;
515     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
516     while (btstack_linked_list_iterator_has_next(&it)){
517         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
518         if (connection->role != role) continue;
519         if (connection->avrcp_browsing_cid != browsing_cid) continue;
520         return connection;
521     }
522     return NULL;
523 }
524 
525 avrcp_connection_t * avrcp_get_connection_for_browsing_l2cap_cid_for_role(avrcp_role_t role, uint16_t browsing_l2cap_cid){
526     btstack_linked_list_iterator_t it;
527     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
528     while (btstack_linked_list_iterator_has_next(&it)){
529         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
530         if (connection->role != role) continue;
531         if (connection->browsing_connection &&  (connection->browsing_connection->l2cap_browsing_cid != browsing_l2cap_cid)) continue;
532         return connection;
533     }
534     return NULL;
535 }
536 
537 avrcp_browsing_connection_t * avrcp_get_browsing_connection_for_l2cap_cid_for_role(avrcp_role_t role, uint16_t l2cap_cid){
538     btstack_linked_list_iterator_t it;
539     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
540     while (btstack_linked_list_iterator_has_next(&it)){
541         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
542         if (connection->role != role) continue;
543         if (connection->browsing_connection && (connection->browsing_connection->l2cap_browsing_cid != l2cap_cid)) continue;
544         return connection->browsing_connection;
545     }
546     return NULL;
547 }
548 
549 void avrcp_request_can_send_now(avrcp_connection_t * connection, uint16_t l2cap_cid){
550     connection->wait_to_send = true;
551     l2cap_request_can_send_now_event(l2cap_cid);
552 }
553 
554 uint16_t avrcp_get_next_cid(avrcp_role_t role){
555     do {
556         if (avrcp_cid_counter == 0xffff) {
557             avrcp_cid_counter = 1;
558         } else {
559             avrcp_cid_counter++;
560         }
561     } while (avrcp_get_connection_for_avrcp_cid_for_role(role, avrcp_cid_counter) !=  NULL) ;
562     return avrcp_cid_counter;
563 }
564 
565 static avrcp_connection_t * avrcp_create_connection(avrcp_role_t role, bd_addr_t remote_addr){
566     avrcp_connection_t * connection = btstack_memory_avrcp_connection_get();
567     if (!connection){
568         log_error("Not enough memory to create connection for role %d", role);
569         return NULL;
570     }
571 
572     connection->state = AVCTP_CONNECTION_IDLE;
573     connection->role = role;
574 
575     connection->transaction_id = 0xFF;
576     connection->transaction_id_counter = 0;
577 
578     connection->controller_max_num_fragments = 0xFF;
579 
580     // setup default unit / subunit info
581     connection->company_id = 0xffffff;
582     connection->target_unit_type = AVRCP_SUBUNIT_TYPE_PANEL;
583     connection->target_subunit_info_data_size = sizeof(avrcp_default_subunit_info);
584     connection->target_subunit_info_data = avrcp_default_subunit_info;
585 
586     log_info("avrcp_create_connection, role %d", role);
587     (void)memcpy(connection->remote_addr, remote_addr, 6);
588     btstack_linked_list_add(&avrcp_connections, (btstack_linked_item_t *) connection);
589     return connection;
590 }
591 
592 static void avrcp_finalize_connection(avrcp_connection_t * connection){
593     btstack_run_loop_remove_timer(&connection->retry_timer);
594     btstack_run_loop_remove_timer(&connection->controller_press_and_hold_cmd_timer);
595     btstack_linked_list_remove(&avrcp_connections, (btstack_linked_item_t*) connection);
596     btstack_memory_avrcp_connection_free(connection);
597 }
598 
599 static void avrcp_emit_connection_established(uint16_t avrcp_cid, bd_addr_t addr, hci_con_handle_t con_handle, uint8_t status){
600     btstack_assert(avrcp_callback != NULL);
601 
602     uint8_t event[14];
603     int pos = 0;
604     event[pos++] = HCI_EVENT_AVRCP_META;
605     event[pos++] = sizeof(event) - 2;
606     event[pos++] = AVRCP_SUBEVENT_CONNECTION_ESTABLISHED;
607     event[pos++] = status;
608     little_endian_store_16(event, pos, avrcp_cid);
609     pos += 2;
610     reverse_bd_addr(addr,&event[pos]);
611     pos += 6;
612     little_endian_store_16(event, pos, con_handle);
613     pos += 2;
614     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
615 }
616 
617 static void avrcp_emit_connection_closed(uint16_t avrcp_cid){
618     btstack_assert(avrcp_callback != NULL);
619 
620     uint8_t event[5];
621     int pos = 0;
622     event[pos++] = HCI_EVENT_AVRCP_META;
623     event[pos++] = sizeof(event) - 2;
624     event[pos++] = AVRCP_SUBEVENT_CONNECTION_RELEASED;
625     little_endian_store_16(event, pos, avrcp_cid);
626     pos += 2;
627     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
628 }
629 
630 uint16_t avrcp_sdp_query_browsing_l2cap_psm(void){
631     return avrcp_sdp_query_context.browsing_l2cap_psm;
632 }
633 
634 void avrcp_handle_sdp_client_query_attribute_value(uint8_t *packet){
635     des_iterator_t des_list_it;
636 
637     des_iterator_t additional_protocol_descriptor_list_it;
638     des_iterator_t protocol_descriptor_list_it;
639     des_iterator_t protocol_it;
640     uint8_t protocol_descriptor_id;
641 
642     // Handle new SDP record
643     if (sdp_event_query_attribute_byte_get_record_id(packet) != avrcp_sdp_query_context.record_id) {
644         avrcp_sdp_query_context.record_id = sdp_event_query_attribute_byte_get_record_id(packet);
645         avrcp_sdp_query_context.parse_sdp_record = 0;
646         // log_info("SDP Record: Nr: %d", record_id);
647     }
648 
649     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= avrcp_sdp_query_attribute_value_buffer_size) {
650         avrcp_sdp_query_attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
651 
652         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
653             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
654                 case BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST:
655                     if (de_get_element_type(avrcp_sdp_query_attribute_value) != DE_DES) break;
656                     for (des_iterator_init(&des_list_it, avrcp_sdp_query_attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
657                         uint8_t * element = des_iterator_get_element(&des_list_it);
658                         if (de_get_element_type(element) != DE_UUID) continue;
659                         uint32_t uuid = de_get_uuid32(element);
660                         switch (uuid){
661                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_TARGET:
662                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL:
663                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_CONTROLLER:
664                                 avrcp_sdp_query_context.parse_sdp_record = 1;
665                                 break;
666                             default:
667                                 break;
668                         }
669                     }
670                     break;
671 
672                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
673                     if (!avrcp_sdp_query_context.parse_sdp_record) break;
674 
675                     for (des_iterator_init(&protocol_descriptor_list_it, avrcp_sdp_query_attribute_value); des_iterator_has_more(&protocol_descriptor_list_it); des_iterator_next(&protocol_descriptor_list_it)) {
676 
677                         if (des_iterator_get_type(&protocol_descriptor_list_it) != DE_DES) continue;
678                         uint8_t * protocol_descriptor_list_element = des_iterator_get_element(&protocol_descriptor_list_it);
679 
680                         des_iterator_init(&protocol_it, protocol_descriptor_list_element);
681                         uint8_t * protocol_element = des_iterator_get_element(&protocol_it);
682 
683                         if (de_get_element_type(protocol_element) != DE_UUID) continue;
684 
685                         uint32_t uuid = de_get_uuid32(protocol_element);
686                         des_iterator_next(&protocol_it);
687                         switch (uuid){
688                             case BLUETOOTH_PROTOCOL_L2CAP:
689                                 if (!des_iterator_has_more(&protocol_it)) continue;
690                                 de_element_get_uint16(des_iterator_get_element(&protocol_it), &avrcp_sdp_query_context.avrcp_l2cap_psm);
691                                 break;
692                             case BLUETOOTH_PROTOCOL_AVCTP:
693                                 if (!des_iterator_has_more(&protocol_it)) continue;
694                                 de_element_get_uint16(des_iterator_get_element(&protocol_it), &avrcp_sdp_query_context.avrcp_version);
695                                 break;
696                             default:
697                                 break;
698                         }
699                     }
700                     break;
701 
702                 case BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS:
703                     if (!avrcp_sdp_query_context.parse_sdp_record) break;
704 
705                     protocol_descriptor_id = 0;
706 
707                     for ( des_iterator_init(&additional_protocol_descriptor_list_it, avrcp_sdp_query_attribute_value);
708                           des_iterator_has_more(&additional_protocol_descriptor_list_it);
709                           des_iterator_next(&additional_protocol_descriptor_list_it)) {
710 
711                         if (des_iterator_get_type(&additional_protocol_descriptor_list_it) != DE_DES) continue;
712                         uint8_t *additional_protocol_descriptor_element = des_iterator_get_element(&additional_protocol_descriptor_list_it);
713 
714                         for ( des_iterator_init(&protocol_descriptor_list_it,additional_protocol_descriptor_element);
715                               des_iterator_has_more(&protocol_descriptor_list_it);
716                               des_iterator_next(&protocol_descriptor_list_it)) {
717 
718                             if (des_iterator_get_type(&protocol_descriptor_list_it) != DE_DES) continue;
719 
720                             uint8_t * protocol_descriptor_list_element = des_iterator_get_element(&protocol_descriptor_list_it);
721 
722                             des_iterator_init(&protocol_it, protocol_descriptor_list_element);
723                             uint8_t * protocol_element = des_iterator_get_element(&protocol_it);
724 
725                             if (de_get_element_type(protocol_element) != DE_UUID) continue;
726 
727                             uint32_t uuid = de_get_uuid32(protocol_element);
728                             des_iterator_next(&protocol_it);
729                             switch (uuid) {
730                                 case BLUETOOTH_PROTOCOL_L2CAP:
731                                     if (!des_iterator_has_more(&protocol_it)) continue;
732                                     switch (protocol_descriptor_id) {
733                                         case 0:
734                                             de_element_get_uint16(des_iterator_get_element(&protocol_it),
735                                                                   &avrcp_sdp_query_context.browsing_l2cap_psm);
736                                             break;
737                                         case 1:
738                                             de_element_get_uint16(des_iterator_get_element(&protocol_it),
739                                                                   &avrcp_sdp_query_context.cover_art_l2cap_psm);
740                                             break;
741                                         default:
742                                             break;
743                                     }
744                                     break;
745                                 case BLUETOOTH_PROTOCOL_AVCTP:
746                                     if (!des_iterator_has_more(&protocol_it)) continue;
747                                     de_element_get_uint16(des_iterator_get_element(&protocol_it),
748                                                           &avrcp_sdp_query_context.browsing_version);
749                                     break;
750                                 default:
751                                     break;
752                             }
753                         }
754                         protocol_descriptor_id++;
755                     }
756                     break;
757 
758                 default:
759                     break;
760             }
761         }
762     } else {
763         log_error("SDP attribute value buffer size exceeded: available %d, required %d", avrcp_sdp_query_attribute_value_buffer_size, sdp_event_query_attribute_byte_get_attribute_length(packet));
764     }
765 }
766 
767 static void avrcp_signaling_handle_sdp_query_complete(avrcp_connection_t * connection, uint8_t status){
768 
769     // l2cap available?
770     if (status == ERROR_CODE_SUCCESS){
771         if (avrcp_sdp_query_context.avrcp_l2cap_psm == 0){
772             status = SDP_SERVICE_NOT_FOUND;
773         }
774     }
775 
776     if (status == ERROR_CODE_SUCCESS){
777         // ready to connect
778         connection->state = AVCTP_CONNECTION_W2_L2CAP_CONNECT;
779 
780         // check if both events have been handled
781         avrcp_connection_t * connection_with_opposite_role;
782         switch (connection->role){
783             case AVRCP_CONTROLLER:
784                 connection_with_opposite_role = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_TARGET, connection->avrcp_cid);
785                 break;
786             case AVRCP_TARGET:
787                 connection_with_opposite_role = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, connection->avrcp_cid);
788                 break;
789             default:
790                 btstack_assert(false);
791                 return;
792         }
793         if (connection_with_opposite_role->state == AVCTP_CONNECTION_W2_L2CAP_CONNECT){
794             connection->state                    = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
795             connection_with_opposite_role->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
796             l2cap_create_channel(&avrcp_packet_handler, connection->remote_addr, connection->avrcp_l2cap_psm, l2cap_max_mtu(), NULL);
797         }
798     } else {
799         log_info("AVRCP: SDP query failed with status 0x%02x.", status);
800         avrcp_emit_connection_established(connection->avrcp_cid, connection->remote_addr, connection->con_handle, status);
801         avrcp_finalize_connection(connection);
802     }
803 }
804 
805 static void avrcp_handle_sdp_query_completed(avrcp_connection_t * connection, uint8_t status){
806     btstack_assert(connection != NULL);
807 
808     // cache SDP result on success
809     if (status == ERROR_CODE_SUCCESS){
810         connection->avrcp_l2cap_psm = avrcp_sdp_query_context.avrcp_l2cap_psm;
811         connection->browsing_version = avrcp_sdp_query_context.browsing_version;
812         connection->browsing_l2cap_psm = avrcp_sdp_query_context.browsing_l2cap_psm;
813 #ifdef ENABLE_AVRCP_COVER_ART
814         connection->cover_art_psm = avrcp_sdp_query_context.cover_art_l2cap_psm;
815 #endif
816     }
817 
818     // SDP Signaling Query?
819     if (connection->state == AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE){
820         avrcp_signaling_handle_sdp_query_complete(connection, status);
821         return;
822     }
823     // Browsing SDP <- Browsing Connection <- Existing AVRCP Connection => it wasn't an SDP query for signaling
824     if (avrcp_browsing_sdp_query_complete_handler != NULL){
825         (*avrcp_browsing_sdp_query_complete_handler)(connection, status);
826     }
827 #ifdef ENABLE_AVRCP_COVER_ART
828     // Cover Art SDP <- Cover Art Connection <- Existing AVRCP Connection => it wasn't an SDP query for signaling
829     if (avrcp_cover_art_sdp_query_complete_handler != NULL){
830         (*avrcp_cover_art_sdp_query_complete_handler)(connection, status);
831     }
832 #endif
833 }
834 
835 static void avrcp_handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
836     UNUSED(packet_type);
837     UNUSED(channel);
838     UNUSED(size);
839 
840     avrcp_connection_t * avrcp_target_connection     = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_TARGET,     avrcp_sdp_query_context.avrcp_cid);
841     avrcp_connection_t * avrcp_controller_connection = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_sdp_query_context.avrcp_cid);
842     bool state_ok = (avrcp_target_connection != NULL) && (avrcp_controller_connection != NULL);
843 
844     if (!state_ok){
845         // something wrong, nevertheless, start next sdp query if this one is complete
846         if (hci_event_packet_get_type(packet) == SDP_EVENT_QUERY_COMPLETE){
847             avrcp_sdp_query_context.avrcp_cid = 0;
848             avrcp_start_next_sdp_query();
849         }
850         return;
851     }
852 
853     uint8_t status;
854 
855     switch (hci_event_packet_get_type(packet)){
856         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
857             avrcp_handle_sdp_client_query_attribute_value(packet);
858             return;
859 
860         case SDP_EVENT_QUERY_COMPLETE:
861             // handle result
862             status = sdp_event_query_complete_get_status(packet);
863             avrcp_handle_sdp_query_completed(avrcp_controller_connection, status);
864             avrcp_handle_sdp_query_completed(avrcp_target_connection, status);
865 
866             // query done, start next one
867             avrcp_sdp_query_context.avrcp_cid = 0;
868             avrcp_start_next_sdp_query();
869             break;
870 
871         default:
872             return;
873     }
874 
875 }
876 
877 static void avrcp_handle_start_sdp_client_query(void * context){
878     UNUSED(context);
879 
880     avrcp_connection_t * avrcp_target_connection     = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_TARGET,     avrcp_sdp_query_context.avrcp_cid);
881     avrcp_connection_t * avrcp_controller_connection = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_sdp_query_context.avrcp_cid);
882     bool state_ok = (avrcp_target_connection != NULL) && (avrcp_controller_connection != NULL);
883     if (state_ok == false){
884         // connection seems to got finalized in the meantime, just trigger next query
885         avrcp_start_next_sdp_query();
886         return;
887     }
888 
889     // prevent triggering SDP query twice (for each role once)
890     avrcp_target_connection->trigger_sdp_query = false;
891     avrcp_controller_connection->trigger_sdp_query = false;
892 
893     sdp_client_query_uuid16(&avrcp_handle_sdp_client_query_result, avrcp_target_connection->remote_addr, BLUETOOTH_PROTOCOL_AVCTP);
894 }
895 
896 static void avrcp_start_next_sdp_query(void) {
897     if (avrcp_sdp_query_context.avrcp_cid != 0) {
898         return;
899     }
900     btstack_linked_list_iterator_t it;
901     btstack_linked_list_iterator_init(&it, &avrcp_connections);
902     while (btstack_linked_list_iterator_has_next(&it)){
903         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
904         if (connection->trigger_sdp_query == false) continue;
905 
906         // we're ready => setup avrcp_sdp_query_context and request sdp query
907         avrcp_sdp_query_context.avrcp_cid = connection->avrcp_cid;
908         avrcp_sdp_query_context.avrcp_l2cap_psm = 0;
909         avrcp_sdp_query_context.avrcp_version  = 0;
910         avrcp_sdp_query_registration.callback = &avrcp_handle_start_sdp_client_query;
911         uint8_t status = sdp_client_register_query_callback(&avrcp_sdp_query_registration);
912         btstack_assert(status == ERROR_CODE_SUCCESS);
913         UNUSED(status);
914         break;
915     }
916 }
917 
918 static avrcp_connection_t * avrcp_handle_incoming_connection_for_role(avrcp_role_t role, avrcp_connection_t * connection, bd_addr_t event_addr, hci_con_handle_t con_handle, uint16_t local_cid, uint16_t avrcp_cid){
919     if (connection == NULL){
920         connection = avrcp_create_connection(role, event_addr);
921     }
922     if (connection) {
923         connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
924         connection->l2cap_signaling_cid = local_cid;
925         connection->avrcp_cid = avrcp_cid;
926         connection->con_handle = con_handle;
927         btstack_run_loop_remove_timer(&connection->retry_timer);
928     }
929     return connection;
930 }
931 
932 static void avrcp_handle_open_connection(avrcp_connection_t * connection, hci_con_handle_t con_handle, uint16_t local_cid, uint16_t l2cap_mtu){
933     connection->l2cap_signaling_cid = local_cid;
934     connection->l2cap_mtu = l2cap_mtu;
935     connection->con_handle = con_handle;
936     connection->incoming_declined = false;
937     connection->target_song_length_ms = 0xFFFFFFFF;
938     connection->target_song_position_ms = 0xFFFFFFFF;
939     memset(connection->target_track_id, 0xFF, 8);
940     connection->target_track_selected = false;
941     connection->target_track_changed = false;
942     connection->target_playback_status = AVRCP_PLAYBACK_STATUS_STOPPED;
943     connection->state = AVCTP_CONNECTION_OPENED;
944 
945     log_info("L2CAP_EVENT_CHANNEL_OPENED avrcp_cid 0x%02x, l2cap_signaling_cid 0x%02x, role %d, state %d", connection->avrcp_cid, connection->l2cap_signaling_cid, connection->role, connection->state);
946 }
947 
948 static void avrcp_retry_timer_timeout_handler(btstack_timer_source_t * timer){
949     uint16_t avrcp_cid = (uint16_t)(uintptr_t) btstack_run_loop_get_timer_context(timer);
950     avrcp_connection_t * connection_controller = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_cid);
951     if (connection_controller == NULL) return;
952     avrcp_connection_t * connection_target = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_TARGET, avrcp_cid);
953     if (connection_target == NULL) return;
954 
955     if (connection_controller->state == AVCTP_CONNECTION_W2_L2CAP_RETRY){
956         connection_controller->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
957         connection_target->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
958         l2cap_create_channel(&avrcp_packet_handler, connection_controller->remote_addr, connection_controller->avrcp_l2cap_psm, l2cap_max_mtu(), NULL);
959     }
960 }
961 
962 static void avrcp_retry_timer_start(avrcp_connection_t * connection){
963     btstack_run_loop_set_timer_handler(&connection->retry_timer, avrcp_retry_timer_timeout_handler);
964     btstack_run_loop_set_timer_context(&connection->retry_timer, (void *)(uintptr_t)connection->avrcp_cid);
965 
966     // add some jitter/randomness to reconnect delay
967     uint32_t timeout = 100 + (btstack_run_loop_get_time_ms() & 0x7F);
968     btstack_run_loop_set_timer(&connection->retry_timer, timeout);
969 
970     btstack_run_loop_add_timer(&connection->retry_timer);
971 }
972 
973 static avrcp_frame_type_t avrcp_get_frame_type(uint8_t header){
974     return (avrcp_frame_type_t)((header & 0x02) >> 1);
975 }
976 
977 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
978     UNUSED(channel);
979     UNUSED(size);
980     bd_addr_t event_addr;
981     uint16_t local_cid;
982     uint16_t l2cap_mtu;
983     uint8_t  status;
984     bool decline_connection;
985     bool outoing_active;
986     bool connection_already_established;
987     hci_con_handle_t con_handle;
988 
989     avrcp_connection_t * connection_controller;
990     avrcp_connection_t * connection_target;
991     bool can_send;
992 
993     switch (packet_type) {
994         case HCI_EVENT_PACKET:
995             switch (hci_event_packet_get_type(packet)) {
996 
997                 case L2CAP_EVENT_INCOMING_CONNECTION:
998                     btstack_assert(avrcp_controller_packet_handler != NULL);
999                     btstack_assert(avrcp_target_packet_handler != NULL);
1000 
1001                     l2cap_event_incoming_connection_get_address(packet, event_addr);
1002                     local_cid = l2cap_event_incoming_connection_get_local_cid(packet);
1003                     con_handle = l2cap_event_incoming_connection_get_handle(packet);
1004 
1005                     outoing_active = false;
1006                     connection_already_established = false;
1007 
1008                     connection_target = avrcp_get_connection_for_bd_addr_for_role(AVRCP_TARGET, event_addr);
1009                     if (connection_target != NULL){
1010                         if (connection_target->state == AVCTP_CONNECTION_W4_L2CAP_CONNECTED){
1011                             outoing_active = true;
1012                             connection_target->incoming_declined = true;
1013                         }
1014                         if (connection_target->state >= AVCTP_CONNECTION_OPENED){
1015                             connection_already_established = true;
1016                         }
1017                     }
1018 
1019                     connection_controller = avrcp_get_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
1020                     if (connection_controller != NULL){
1021                         if (connection_controller->state == AVCTP_CONNECTION_W4_L2CAP_CONNECTED) {
1022                             outoing_active = true;
1023                             connection_controller->incoming_declined = true;
1024                         }
1025                         if (connection_controller->state >= AVCTP_CONNECTION_OPENED){
1026                             connection_already_established = true;
1027                         }
1028                     }
1029 
1030                     decline_connection = outoing_active || connection_already_established;
1031                     if (decline_connection == false){
1032                         uint16_t avrcp_cid;
1033                         if ((connection_controller == NULL) || (connection_target == NULL)){
1034                             avrcp_cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
1035                         } else {
1036                             avrcp_cid = connection_controller->avrcp_cid;
1037                         }
1038                         // create two connection objects (both)
1039                         connection_target     = avrcp_handle_incoming_connection_for_role(AVRCP_TARGET, connection_target, event_addr, con_handle, local_cid, avrcp_cid);
1040                         connection_controller = avrcp_handle_incoming_connection_for_role(AVRCP_CONTROLLER, connection_controller, event_addr, con_handle, local_cid, avrcp_cid);
1041                         if ((connection_target == NULL) || (connection_controller == NULL)){
1042                             decline_connection = true;
1043                             if (connection_target) {
1044                                 avrcp_finalize_connection(connection_target);
1045                             }
1046                             if (connection_controller) {
1047                                 avrcp_finalize_connection(connection_controller);
1048                             }
1049                         }
1050                     }
1051                     if (decline_connection){
1052                         log_info("Decline connection 0x%04x: outgoing active %u, connection already established: %u", local_cid, outoing_active, connection_already_established);
1053                         l2cap_decline_connection(local_cid);
1054                     } else {
1055                         log_info("AVRCP: L2CAP_EVENT_INCOMING_CONNECTION local cid 0x%04x, state %d", local_cid, connection_controller->state);
1056                         l2cap_accept_connection(local_cid);
1057                     }
1058                     break;
1059 
1060                 case L2CAP_EVENT_CHANNEL_OPENED:
1061                     l2cap_event_channel_opened_get_address(packet, event_addr);
1062                     status = l2cap_event_channel_opened_get_status(packet);
1063                     local_cid = l2cap_event_channel_opened_get_local_cid(packet);
1064                     l2cap_mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
1065                     con_handle = l2cap_event_channel_opened_get_handle(packet);
1066 
1067                     connection_controller = avrcp_get_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
1068                     connection_target = avrcp_get_connection_for_bd_addr_for_role(AVRCP_TARGET, event_addr);
1069 
1070                     // incoming: structs are already created in L2CAP_EVENT_INCOMING_CONNECTION
1071                     // outgoing: structs are cteated in avrcp_connect()
1072                     if ((connection_controller == NULL) || (connection_target == NULL)) {
1073                         break;
1074                     }
1075 
1076                     switch (status){
1077                         case ERROR_CODE_SUCCESS:
1078                             avrcp_handle_open_connection(connection_target, con_handle, local_cid, l2cap_mtu);
1079                             avrcp_handle_open_connection(connection_controller, con_handle, local_cid, l2cap_mtu);
1080                             avrcp_emit_connection_established(connection_controller->avrcp_cid, event_addr, con_handle, status);
1081                             return;
1082                         case L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES:
1083                             if (connection_controller->incoming_declined == true){
1084                                 log_info("Incoming connection was declined, and the outgoing failed");
1085                                 connection_controller->state = AVCTP_CONNECTION_W2_L2CAP_RETRY;
1086                                 connection_controller->incoming_declined = false;
1087                                 connection_target->state = AVCTP_CONNECTION_W2_L2CAP_RETRY;
1088                                 connection_target->incoming_declined = false;
1089                                 avrcp_retry_timer_start(connection_controller);
1090                                 return;
1091                             }
1092                             break;
1093                         default:
1094                             break;
1095                     }
1096                     log_info("L2CAP connection to connection %s failed. status code 0x%02x", bd_addr_to_str(event_addr), status);
1097                     avrcp_emit_connection_established(connection_controller->avrcp_cid, event_addr, con_handle, status);
1098                     avrcp_finalize_connection(connection_controller);
1099                     avrcp_finalize_connection(connection_target);
1100 
1101                     break;
1102 
1103                 case L2CAP_EVENT_CHANNEL_CLOSED:
1104                     local_cid = l2cap_event_channel_closed_get_local_cid(packet);
1105 
1106                     connection_controller = avrcp_get_connection_for_l2cap_signaling_cid_for_role(AVRCP_CONTROLLER, local_cid);
1107                     connection_target = avrcp_get_connection_for_l2cap_signaling_cid_for_role(AVRCP_TARGET, local_cid);
1108                     if ((connection_controller == NULL) || (connection_target == NULL)) {
1109                         break;
1110                     }
1111                     avrcp_emit_connection_closed(connection_controller->avrcp_cid);
1112                     avrcp_finalize_connection(connection_controller);
1113                     avrcp_finalize_connection(connection_target);
1114                     break;
1115 
1116                 case L2CAP_EVENT_CAN_SEND_NOW:
1117                     local_cid = l2cap_event_can_send_now_get_local_cid(packet);
1118                     can_send = true;
1119 
1120                     connection_target = avrcp_get_connection_for_l2cap_signaling_cid_for_role(AVRCP_TARGET, local_cid);
1121                     if ((connection_target != NULL) && connection_target->wait_to_send){
1122                         connection_target->wait_to_send = false;
1123                         (*avrcp_target_packet_handler)(HCI_EVENT_PACKET, channel, packet, size);
1124                         can_send = false;
1125                     }
1126 
1127                     connection_controller = avrcp_get_connection_for_l2cap_signaling_cid_for_role(AVRCP_CONTROLLER, local_cid);
1128                     if ((connection_controller != NULL) && connection_controller->wait_to_send){
1129                         if (can_send){
1130                             connection_controller->wait_to_send = false;
1131                             (*avrcp_controller_packet_handler)(HCI_EVENT_PACKET, channel, packet, size);
1132                         } else {
1133                             l2cap_request_can_send_now_event(local_cid);
1134                         }
1135                     }
1136                     break;
1137 
1138                 default:
1139                     break;
1140             }
1141             break;
1142 
1143         case L2CAP_DATA_PACKET:
1144             switch (avrcp_get_frame_type(packet[0])){
1145                 case AVRCP_RESPONSE_FRAME:
1146                     (*avrcp_controller_packet_handler)(packet_type, channel, packet, size);
1147                     break;
1148                 case AVRCP_COMMAND_FRAME:
1149                 default:    // make compiler happy
1150                     (*avrcp_target_packet_handler)(packet_type, channel, packet, size);
1151                     break;
1152             }
1153             break;
1154 
1155         default:
1156             break;
1157     }
1158 }
1159 
1160 void avrcp_init(void){
1161     avrcp_connections = NULL;
1162     if (avrcp_l2cap_service_registered) return;
1163 
1164     int status = l2cap_register_service(&avrcp_packet_handler, BLUETOOTH_PSM_AVCTP, 0xffff, gap_get_security_level());
1165     if (status != ERROR_CODE_SUCCESS) return;
1166     avrcp_l2cap_service_registered = true;
1167 }
1168 
1169 void avrcp_register_controller_packet_handler(btstack_packet_handler_t callback){
1170     // note: called by avrcp_controller_init
1171     avrcp_controller_packet_handler = callback;
1172 }
1173 
1174 void avrcp_register_target_packet_handler(btstack_packet_handler_t callback){
1175     // note: called by avrcp_target_init
1176     avrcp_target_packet_handler = callback;
1177 }
1178 
1179 void avrcp_register_packet_handler(btstack_packet_handler_t callback){
1180     btstack_assert(callback != NULL);
1181     avrcp_callback = callback;
1182 }
1183 
1184 void avrcp_register_browsing_sdp_query_complete_handler(void (*callback)(avrcp_connection_t * connection, uint8_t status)){
1185     btstack_assert(callback != NULL);
1186     avrcp_browsing_sdp_query_complete_handler = callback;
1187 }
1188 
1189 #ifdef ENABLE_AVRCP_COVER_ART
1190 void avrcp_register_cover_art_sdp_query_complete_handler(void (*callback)(avrcp_connection_t * connection, uint8_t status)){
1191     btstack_assert(callback != NULL);
1192     avrcp_cover_art_sdp_query_complete_handler = callback;
1193 }
1194 #endif
1195 
1196 void avrcp_trigger_sdp_query(avrcp_connection_t *connection_controller, avrcp_connection_t *connection_target) {
1197     connection_controller->trigger_sdp_query = true;
1198     connection_target->trigger_sdp_query     = true;
1199 
1200     avrcp_start_next_sdp_query();
1201 }
1202 
1203 uint8_t avrcp_connect(bd_addr_t remote_addr, uint16_t * avrcp_cid){
1204     btstack_assert(avrcp_controller_packet_handler != NULL);
1205     btstack_assert(avrcp_target_packet_handler != NULL);
1206 
1207     avrcp_connection_t * connection_controller = avrcp_get_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, remote_addr);
1208     bool setup_active = false;
1209     if (connection_controller){
1210         // allow to call avrcp_connect after signaling connection was triggered remotely
1211         // @note this also allows to call avrcp_connect again before SLC is complete
1212         if (connection_controller->state < AVCTP_CONNECTION_OPENED){
1213             setup_active = true;
1214         } else {
1215             return ERROR_CODE_COMMAND_DISALLOWED;
1216         }
1217     }
1218     avrcp_connection_t * connection_target = avrcp_get_connection_for_bd_addr_for_role(AVRCP_TARGET, remote_addr);
1219     if (connection_target){
1220         if (connection_target->state < AVCTP_CONNECTION_OPENED){
1221             setup_active = true;
1222         } else {
1223             return ERROR_CODE_COMMAND_DISALLOWED;
1224         }
1225     }
1226     if (setup_active){
1227         return ERROR_CODE_SUCCESS;
1228     }
1229 
1230     uint16_t cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
1231 
1232     connection_controller = avrcp_create_connection(AVRCP_CONTROLLER, remote_addr);
1233     if (!connection_controller) return BTSTACK_MEMORY_ALLOC_FAILED;
1234 
1235     connection_target = avrcp_create_connection(AVRCP_TARGET, remote_addr);
1236     if (!connection_target){
1237         avrcp_finalize_connection(connection_controller);
1238         return BTSTACK_MEMORY_ALLOC_FAILED;
1239     }
1240 
1241     if (avrcp_cid != NULL){
1242         *avrcp_cid = cid;
1243     }
1244 
1245     connection_controller->avrcp_cid = cid;
1246     connection_target->avrcp_cid     = cid;
1247 
1248     connection_controller->state = AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE;
1249     connection_target->state     = AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE;
1250 
1251     avrcp_trigger_sdp_query(connection_controller, connection_target);
1252 
1253     return ERROR_CODE_SUCCESS;
1254 }
1255 
1256 uint8_t avrcp_disconnect(uint16_t avrcp_cid){
1257     avrcp_connection_t * connection_controller = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_cid);
1258     if (!connection_controller){
1259         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1260     }
1261     avrcp_connection_t * connection_target = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_TARGET, avrcp_cid);
1262     if (!connection_target){
1263         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1264     }
1265     if (connection_controller->browsing_connection){
1266         l2cap_disconnect(connection_controller->browsing_connection->l2cap_browsing_cid);
1267     }
1268     l2cap_disconnect(connection_controller->l2cap_signaling_cid);
1269     return ERROR_CODE_SUCCESS;
1270 }
1271 
1272 void avrcp_deinit(void){
1273     avrcp_l2cap_service_registered = false;
1274 
1275     avrcp_cid_counter = 0;
1276     avrcp_connections = NULL;
1277 
1278     avrcp_callback = NULL;
1279     avrcp_controller_packet_handler = NULL;
1280     avrcp_target_packet_handler = NULL;
1281 
1282     (void) memset(&avrcp_sdp_query_registration, 0, sizeof(avrcp_sdp_query_registration));
1283     (void) memset(&avrcp_sdp_query_context, 0, sizeof(avrcp_sdp_query_context_t));
1284     (void) memset(avrcp_sdp_query_attribute_value, 0, sizeof(avrcp_sdp_query_attribute_value));
1285 }
1286 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1287 #define FUZZ_CID 0x44
1288 #define FUZZ_CON_HANDLE 0x0001
1289 static bd_addr_t remote_addr = { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33 };
1290 void avrcp_init_fuzz(void){
1291     // setup avrcp connections for cid
1292     avrcp_connection_t * connection_controller = avrcp_create_connection(AVRCP_CONTROLLER, remote_addr);
1293     avrcp_connection_t * connection_target     = avrcp_create_connection(AVRCP_TARGET, remote_addr);
1294     avrcp_handle_open_connection(connection_controller, FUZZ_CON_HANDLE, FUZZ_CID, 999);
1295     avrcp_handle_open_connection(connection_target, FUZZ_CON_HANDLE, FUZZ_CID, 999);
1296 }
1297 void avrcp_packet_handler_fuzz(uint8_t *packet, uint16_t size){
1298     avrcp_packet_handler(L2CAP_DATA_PACKET, FUZZ_CID, packet, size);
1299 }
1300 #endif
1301