xref: /btstack/src/classic/avrcp.c (revision 4d7cf3906f0a6495795144050e0c02f6e1f39095)
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/sdp_client.h"
51 #include "classic/sdp_util.h"
52 #include "classic/avrcp.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 } avrcp_sdp_query_context_t;
65 
66 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
67 
68 static const char * avrcp_default_controller_service_name = "BTstack AVRCP Controller Service";
69 static const char * avrcp_default_controller_service_provider_name = "BTstack AVRCP Controller Service Provider";
70 static const char * avrcp_defaul_target_service_name = "BTstack AVRCP Target Service";
71 static const char * avrcp_default_target_service_provider_name = "BTstack AVRCP Target Service Provider";
72 
73 static const char * avrcp_subunit_type_name[] = {
74         "MONITOR", "AUDIO", "PRINTER", "DISC", "TAPE_RECORDER_PLAYER", "TUNER",
75         "CA", "CAMERA", "RESERVED", "PANEL", "BULLETIN_BOARD", "CAMERA_STORAGE",
76         "VENDOR_UNIQUE", "RESERVED_FOR_ALL_SUBUNIT_TYPES",
77         "EXTENDED_TO_NEXT_BYTE", "UNIT", "ERROR"
78 };
79 
80 // default subunit info: single PANEL subunit
81 static const uint8_t avrcp_default_subunit_info[] = { AVRCP_SUBUNIT_TYPE_PANEL << 3};
82 
83 // globals
84 static bool avrcp_l2cap_service_registered = false;
85 
86 // connections
87 static uint16_t                 avrcp_cid_counter;
88 static btstack_linked_list_t    avrcp_connections;
89 
90 // higher layer callbacks
91 static btstack_packet_handler_t avrcp_callback;
92 static btstack_packet_handler_t avrcp_controller_packet_handler;
93 static btstack_packet_handler_t avrcp_target_packet_handler;
94 
95 // sdp query
96 static btstack_context_callback_registration_t avrcp_sdp_query_registration;
97 static avrcp_sdp_query_context_t               avrcp_sdp_query_context;
98 static uint8_t                                 avrcp_sdp_query_attribute_value[45];
99 static const unsigned int                      avrcp_sdp_query_attribute_value_buffer_size = sizeof(avrcp_sdp_query_attribute_value);
100 
101 
102 const char * avrcp_subunit2str(uint16_t index){
103     if (index <= 11) return avrcp_subunit_type_name[index];
104     if ((index >= 0x1C) && (index <= 0x1F)) return avrcp_subunit_type_name[index - 0x10];
105     return avrcp_subunit_type_name[16];
106 }
107 
108 static const char * avrcp_event_name[] = {
109     "ERROR", "PLAYBACK_STATUS_CHANGED",
110     "TRACK_CHANGED", "TRACK_REACHED_END", "TRACK_REACHED_START",
111     "PLAYBACK_POS_CHANGED", "BATT_STATUS_CHANGED", "SYSTEM_STATUS_CHANGED",
112     "PLAYER_APPLICATION_SETTING_CHANGED", "NOW_PLAYING_CONTENT_CHANGED",
113     "AVAILABLE_PLAYERS_CHANGED", "ADDRESSED_PLAYER_CHANGED", "UIDS_CHANGED", "VOLUME_CHANGED"
114 };
115 const char * avrcp_event2str(uint16_t index){
116     if (index <= 0x0d) return avrcp_event_name[index];
117     return avrcp_event_name[0];
118 }
119 
120 static const char * avrcp_operation_name[] = {
121     "SKIP", NULL, NULL, NULL, NULL,
122     "VOLUME_UP", "VOLUME_DOWN", "MUTE", "PLAY", "STOP", "PAUSE", NULL,
123     "REWIND", "FAST_FORWARD", NULL, "FORWARD", "BACKWARD" // 0x4C
124 };
125 
126 const char * avrcp_operation2str(uint8_t operation_id){
127     char * name = NULL;
128     if ((operation_id >= AVRCP_OPERATION_ID_SKIP) && (operation_id <= AVRCP_OPERATION_ID_BACKWARD)){
129         name = (char *)avrcp_operation_name[operation_id - AVRCP_OPERATION_ID_SKIP];
130     }
131     if (name == NULL){
132         static char buffer[13];
133         snprintf(buffer, sizeof(buffer), "Unknown 0x%02x", operation_id);
134         buffer[sizeof(buffer)-1] = 0;
135         return buffer;
136     } else {
137         return name;
138     }
139 }
140 
141 static const char * avrcp_media_attribute_id_name[] = {
142     "NONE", "TITLE", "ARTIST", "ALBUM", "TRACK", "TOTAL TRACKS", "GENRE", "SONG LENGTH"
143 };
144 const char * avrcp_attribute2str(uint8_t index){
145     if ((index >= 1) && (index <= 7)) return avrcp_media_attribute_id_name[index];
146     return avrcp_media_attribute_id_name[0];
147 }
148 
149 static const char * avrcp_play_status_name[] = {
150     "STOPPED", "PLAYING", "PAUSED", "FORWARD SEEK", "REVERSE SEEK",
151     "ERROR" // 0xFF
152 };
153 const char * avrcp_play_status2str(uint8_t index){
154     if ((index >= 1) && (index <= 4)) return avrcp_play_status_name[index];
155     return avrcp_play_status_name[5];
156 }
157 
158 static const char * avrcp_ctype_name[] = {
159     "CONTROL",
160     "STATUS",
161     "SPECIFIC_INQUIRY",
162     "NOTIFY",
163     "GENERAL_INQUIRY",
164     "RESERVED5",
165     "RESERVED6",
166     "RESERVED7",
167     "NOT IMPLEMENTED IN REMOTE",
168     "ACCEPTED BY REMOTE",
169     "REJECTED BY REMOTE",
170     "IN_TRANSITION",
171     "IMPLEMENTED_STABLE",
172     "CHANGED_STABLE",
173     "RESERVED",
174     "INTERIM"
175 };
176 const char * avrcp_ctype2str(uint8_t index){
177     if (index < sizeof(avrcp_ctype_name)){
178         return avrcp_ctype_name[index];
179     }
180     return "NONE";
181 }
182 
183 static const char * avrcp_shuffle_mode_name[] = {
184     "SHUFFLE OFF",
185     "SHUFFLE ALL TRACKS",
186     "SHUFFLE GROUP"
187 };
188 
189 const char * avrcp_shuffle2str(uint8_t index){
190     if ((index >= 1) && (index <= 3)) return avrcp_shuffle_mode_name[index-1];
191     return "NONE";
192 }
193 
194 static const char * avrcp_repeat_mode_name[] = {
195     "REPEAT OFF",
196     "REPEAT SINGLE TRACK",
197     "REPEAT ALL TRACKS",
198     "REPEAT GROUP"
199 };
200 
201 const char * avrcp_repeat2str(uint8_t index){
202     if ((index >= 1) && (index <= 4)) return avrcp_repeat_mode_name[index-1];
203     return "NONE";
204 }
205 
206 btstack_linked_list_t avrcp_get_connections(void){
207     return avrcp_connections;
208 }
209 
210 uint8_t avrcp_cmd_opcode(uint8_t *packet, uint16_t size){
211     uint8_t cmd_opcode_index = 5;
212     if (cmd_opcode_index > size) return AVRCP_CMD_OPCODE_UNDEFINED;
213     return packet[cmd_opcode_index];
214 }
215 
216 void avrcp_create_sdp_record(uint8_t controller, uint8_t * service, uint32_t service_record_handle, uint8_t browsing, uint16_t supported_features,
217     const char * service_name, const char * service_provider_name){
218     uint8_t* attribute;
219     de_create_sequence(service);
220 
221     // 0x0000 "Service Record Handle"
222     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
223     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
224 
225     // 0x0001 "Service Class ID List"
226     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
227     attribute = de_push_sequence(service);
228     {
229         if (controller){
230             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL);
231             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_CONTROLLER);
232         } else {
233             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_TARGET);
234         }
235     }
236     de_pop_sequence(service, attribute);
237 
238     // 0x0004 "Protocol Descriptor List"
239     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
240     attribute = de_push_sequence(service);
241     {
242         uint8_t* l2cpProtocol = de_push_sequence(attribute);
243         {
244             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
245             de_add_number(l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PSM_AVCTP);
246         }
247         de_pop_sequence(attribute, l2cpProtocol);
248 
249         uint8_t* avctpProtocol = de_push_sequence(attribute);
250         {
251             de_add_number(avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // avctpProtocol_service
252             de_add_number(avctpProtocol,  DE_UINT, DE_SIZE_16,  0x0104);    // version
253         }
254         de_pop_sequence(attribute, avctpProtocol);
255     }
256     de_pop_sequence(service, attribute);
257 
258     // 0x0005 "Public Browse Group"
259     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
260     attribute = de_push_sequence(service);
261     {
262         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
263     }
264     de_pop_sequence(service, attribute);
265 
266     // 0x0009 "Bluetooth Profile Descriptor List"
267     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
268     attribute = de_push_sequence(service);
269     {
270         uint8_t *avrcProfile = de_push_sequence(attribute);
271         {
272             de_add_number(avrcProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL);
273             de_add_number(avrcProfile,  DE_UINT, DE_SIZE_16, 0x0106);
274         }
275         de_pop_sequence(attribute, avrcProfile);
276     }
277     de_pop_sequence(service, attribute);
278 
279     // 0x000d "Additional Bluetooth Profile Descriptor List"
280     if (browsing){
281         de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS);
282         attribute = de_push_sequence(service);
283         {
284             uint8_t * des = de_push_sequence(attribute);
285             {
286                 uint8_t* browsing_l2cpProtocol = de_push_sequence(des);
287                 {
288                     de_add_number(browsing_l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
289                     de_add_number(browsing_l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PSM_AVCTP_BROWSING);
290                 }
291                 de_pop_sequence(des, browsing_l2cpProtocol);
292 
293                 uint8_t* browsing_avctpProtocol = de_push_sequence(des);
294                 {
295                     de_add_number(browsing_avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // browsing_avctpProtocol_service
296                     de_add_number(browsing_avctpProtocol,  DE_UINT, DE_SIZE_16, 0x0104);                   // version
297                 }
298                 de_pop_sequence(des, browsing_avctpProtocol);
299             }
300             de_pop_sequence(attribute, des);
301         }
302         de_pop_sequence(service, attribute);
303     }
304 
305 
306     // 0x0100 "Service Name"
307     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
308     if (service_name){
309         de_add_data(service,  DE_STRING, strlen(service_name), (uint8_t *) service_name);
310     } else {
311         if (controller){
312             de_add_data(service, DE_STRING, strlen(avrcp_default_controller_service_name), (uint8_t *) avrcp_default_controller_service_name);
313         } else {
314             de_add_data(service, DE_STRING, strlen(avrcp_defaul_target_service_name), (uint8_t *) avrcp_defaul_target_service_name);
315         }
316     }
317 
318     // 0x0100 "Provider Name"
319     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0102);
320     if (service_provider_name){
321         de_add_data(service,  DE_STRING, strlen(service_provider_name), (uint8_t *) service_provider_name);
322     } else {
323         if (controller){
324             de_add_data(service, DE_STRING, strlen(avrcp_default_controller_service_provider_name), (uint8_t *) avrcp_default_controller_service_provider_name);
325         } else {
326             de_add_data(service, DE_STRING, strlen(avrcp_default_target_service_provider_name), (uint8_t *) avrcp_default_target_service_provider_name);
327         }
328     }
329 
330     // 0x0311 "Supported Features"
331     de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);
332     de_add_number(service, DE_UINT, DE_SIZE_16, supported_features);
333 }
334 
335 static uint16_t avctp_get_header_offset(avctp_packet_type_t avctp_packet_type) {
336     uint16_t offset; // AVCTP message: header (1), num_packets (1), pid (2)
337     switch (avctp_packet_type){
338         case AVCTP_SINGLE_PACKET:
339         case AVCTP_START_PACKET:
340             offset = 4;
341             break;
342         default:
343             offset = 1;
344             break;
345     }
346     return offset;
347 }
348 
349 static uint16_t avctp_get_message_offset(avrcp_command_opcode_t command_opcode, avctp_packet_type_t avctp_packet_type) {
350     switch (avctp_packet_type){
351         case AVCTP_SINGLE_PACKET:
352         case AVCTP_START_PACKET:
353             break;
354         default:
355             return 0;
356     }
357 
358     uint16_t offset = 3; // AVRCP message: cmd type (1), subunit (1), opcode (1)
359     switch (command_opcode){
360         case AVRCP_CMD_OPCODE_VENDOR_DEPENDENT:
361             offset += 7; // AVRCP message:  company (3), pdu id(1), AVRCP packet type (1), param_len (2)
362             break;
363         case AVRCP_CMD_OPCODE_PASS_THROUGH:
364             offset += 3;  // AVRCP message: operation id (1), param_len (2)
365             break;
366         default:
367             break;
368     }
369     return offset;
370 }
371 
372 static uint16_t avctp_get_max_payload_size(uint16_t l2cap_cid, avrcp_command_opcode_t command_opcode, avctp_packet_type_t avctp_packet_type){
373     uint16_t max_frame_size = btstack_min(l2cap_get_remote_mtu_for_local_cid(l2cap_cid), AVRCP_MAX_AV_C_MESSAGE_FRAME_SIZE);
374     uint16_t offset = avctp_get_header_offset(avctp_packet_type) + avctp_get_message_offset(command_opcode, avctp_packet_type);
375 
376     btstack_assert( max_frame_size >= offset);
377     return (max_frame_size - offset);
378 }
379 
380 
381 avctp_packet_type_t avctp_get_packet_type(avrcp_connection_t * connection, uint16_t * max_payload_size){
382     if (connection->data_offset == 0){
383         *max_payload_size = avctp_get_max_payload_size(connection->l2cap_signaling_cid, connection->command_opcode, AVCTP_SINGLE_PACKET);
384         if (*max_payload_size >= connection->data_len){
385             return AVCTP_SINGLE_PACKET;
386         } else {
387             return AVCTP_START_PACKET;
388         }
389     } else {
390         *max_payload_size = avctp_get_max_payload_size(connection->l2cap_signaling_cid, connection->command_opcode, AVCTP_CONTINUE_PACKET);
391         if ((connection->data_len - connection->data_offset) > *max_payload_size){
392              return AVCTP_CONTINUE_PACKET;
393         } else {
394             return AVCTP_END_PACKET;
395         }
396     }
397 }
398 
399 avrcp_connection_t * avrcp_get_connection_for_bd_addr_for_role(avrcp_role_t role, bd_addr_t addr){
400     btstack_linked_list_iterator_t it;
401     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
402     while (btstack_linked_list_iterator_has_next(&it)){
403         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
404         if (connection->role != role) continue;
405         if (memcmp(addr, connection->remote_addr, 6) != 0) continue;
406         return connection;
407     }
408     return NULL;
409 }
410 
411 avrcp_connection_t * avrcp_get_connection_for_l2cap_signaling_cid_for_role(avrcp_role_t role, uint16_t l2cap_cid){
412     btstack_linked_list_iterator_t it;
413     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
414     while (btstack_linked_list_iterator_has_next(&it)){
415         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
416         if (connection->role != role) continue;
417         if (connection->l2cap_signaling_cid != l2cap_cid) continue;
418         return connection;
419     }
420     return NULL;
421 }
422 
423 avrcp_connection_t * avrcp_get_connection_for_avrcp_cid_for_role(avrcp_role_t role, uint16_t avrcp_cid){
424     btstack_linked_list_iterator_t it;
425     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
426     while (btstack_linked_list_iterator_has_next(&it)){
427         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
428         if (connection->role != role) continue;
429         if (connection->avrcp_cid != avrcp_cid) continue;
430         return connection;
431     }
432     return NULL;
433 }
434 
435 avrcp_connection_t * avrcp_get_connection_for_browsing_cid_for_role(avrcp_role_t role, uint16_t browsing_cid){
436     btstack_linked_list_iterator_t it;
437     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
438     while (btstack_linked_list_iterator_has_next(&it)){
439         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
440         if (connection->role != role) continue;
441         if (connection->avrcp_browsing_cid != browsing_cid) continue;
442         return connection;
443     }
444     return NULL;
445 }
446 
447 avrcp_connection_t * avrcp_get_connection_for_browsing_l2cap_cid_for_role(avrcp_role_t role, uint16_t browsing_l2cap_cid){
448     btstack_linked_list_iterator_t it;
449     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
450     while (btstack_linked_list_iterator_has_next(&it)){
451         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
452         if (connection->role != role) continue;
453         if (connection->browsing_connection &&  (connection->browsing_connection->l2cap_browsing_cid != browsing_l2cap_cid)) continue;
454         return connection;
455     }
456     return NULL;
457 }
458 
459 avrcp_browsing_connection_t * avrcp_get_browsing_connection_for_l2cap_cid_for_role(avrcp_role_t role, uint16_t l2cap_cid){
460     btstack_linked_list_iterator_t it;
461     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
462     while (btstack_linked_list_iterator_has_next(&it)){
463         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
464         if (connection->role != role) continue;
465         if (connection->browsing_connection && (connection->browsing_connection->l2cap_browsing_cid != l2cap_cid)) continue;
466         return connection->browsing_connection;
467     }
468     return NULL;
469 }
470 
471 void avrcp_request_can_send_now(avrcp_connection_t * connection, uint16_t l2cap_cid){
472     connection->wait_to_send = true;
473     l2cap_request_can_send_now_event(l2cap_cid);
474 }
475 
476 uint16_t avrcp_get_next_cid(avrcp_role_t role){
477     do {
478         if (avrcp_cid_counter == 0xffff) {
479             avrcp_cid_counter = 1;
480         } else {
481             avrcp_cid_counter++;
482         }
483     } while (avrcp_get_connection_for_avrcp_cid_for_role(role, avrcp_cid_counter) !=  NULL) ;
484     return avrcp_cid_counter;
485 }
486 
487 static avrcp_connection_t * avrcp_create_connection(avrcp_role_t role, bd_addr_t remote_addr){
488     avrcp_connection_t * connection = btstack_memory_avrcp_connection_get();
489     if (!connection){
490         log_error("Not enough memory to create connection for role %d", role);
491         return NULL;
492     }
493 
494     connection->state = AVCTP_CONNECTION_IDLE;
495     connection->role = role;
496 
497     connection->transaction_id = 0xFF;
498     connection->transaction_id_counter = 0;
499 
500     connection->max_num_fragments = 0xFF;
501 
502     // setup default unit / subunit info
503     connection->company_id = 0xffffff;
504     connection->unit_type = AVRCP_SUBUNIT_TYPE_PANEL;
505     connection->subunit_info_data_size = sizeof(avrcp_default_subunit_info);
506     connection->subunit_info_data = avrcp_default_subunit_info;
507 
508     log_info("avrcp_create_connection, role %d", role);
509     (void)memcpy(connection->remote_addr, remote_addr, 6);
510     btstack_linked_list_add(&avrcp_connections, (btstack_linked_item_t *) connection);
511     return connection;
512 }
513 
514 static void avrcp_finalize_connection(avrcp_connection_t * connection){
515     btstack_run_loop_remove_timer(&connection->retry_timer);
516     btstack_linked_list_remove(&avrcp_connections, (btstack_linked_item_t*) connection);
517     btstack_memory_avrcp_connection_free(connection);
518 }
519 
520 static void avrcp_emit_connection_established(uint16_t avrcp_cid, bd_addr_t addr, hci_con_handle_t con_handle, uint8_t status){
521     btstack_assert(avrcp_callback != NULL);
522 
523     uint8_t event[14];
524     int pos = 0;
525     event[pos++] = HCI_EVENT_AVRCP_META;
526     event[pos++] = sizeof(event) - 2;
527     event[pos++] = AVRCP_SUBEVENT_CONNECTION_ESTABLISHED;
528     event[pos++] = status;
529     little_endian_store_16(event, pos, avrcp_cid);
530     pos += 2;
531     reverse_bd_addr(addr,&event[pos]);
532     pos += 6;
533     little_endian_store_16(event, pos, con_handle);
534     pos += 2;
535     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
536 }
537 
538 static void avrcp_emit_connection_closed(uint16_t avrcp_cid){
539     btstack_assert(avrcp_callback != NULL);
540 
541     uint8_t event[5];
542     int pos = 0;
543     event[pos++] = HCI_EVENT_AVRCP_META;
544     event[pos++] = sizeof(event) - 2;
545     event[pos++] = AVRCP_SUBEVENT_CONNECTION_RELEASED;
546     little_endian_store_16(event, pos, avrcp_cid);
547     pos += 2;
548     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
549 }
550 
551 uint16_t avrcp_sdp_query_browsing_l2cap_psm(void){
552     return avrcp_sdp_query_context.browsing_l2cap_psm;
553 }
554 
555 void avrcp_handle_sdp_client_query_attribute_value(uint8_t *packet){
556     des_iterator_t des_list_it;
557     des_iterator_t prot_it;
558 
559     // Handle new SDP record
560     if (sdp_event_query_attribute_byte_get_record_id(packet) != avrcp_sdp_query_context.record_id) {
561         avrcp_sdp_query_context.record_id = sdp_event_query_attribute_byte_get_record_id(packet);
562         avrcp_sdp_query_context.parse_sdp_record = 0;
563         // log_info("SDP Record: Nr: %d", record_id);
564     }
565 
566     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= avrcp_sdp_query_attribute_value_buffer_size) {
567         avrcp_sdp_query_attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
568 
569         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
570             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
571                 case BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST:
572                     if (de_get_element_type(avrcp_sdp_query_attribute_value) != DE_DES) break;
573                     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)) {
574                         uint8_t * element = des_iterator_get_element(&des_list_it);
575                         if (de_get_element_type(element) != DE_UUID) continue;
576                         uint32_t uuid = de_get_uuid32(element);
577                         switch (uuid){
578                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_TARGET:
579                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL:
580                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_CONTROLLER:
581                                 avrcp_sdp_query_context.parse_sdp_record = 1;
582                                 break;
583                             default:
584                                 break;
585                         }
586                     }
587                     break;
588 
589                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST: {
590                     if (!avrcp_sdp_query_context.parse_sdp_record) break;
591                     // log_info("SDP Attribute: 0x%04x", sdp_event_query_attribute_byte_get_attribute_id(packet));
592                     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)) {
593                         uint8_t       *des_element;
594                         uint8_t       *element;
595                         uint32_t       uuid;
596 
597                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
598 
599                         des_element = des_iterator_get_element(&des_list_it);
600                         des_iterator_init(&prot_it, des_element);
601                         element = des_iterator_get_element(&prot_it);
602 
603                         if (de_get_element_type(element) != DE_UUID) continue;
604 
605                         uuid = de_get_uuid32(element);
606                         des_iterator_next(&prot_it);
607                         switch (uuid){
608                             case BLUETOOTH_PROTOCOL_L2CAP:
609                                 if (!des_iterator_has_more(&prot_it)) continue;
610                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &avrcp_sdp_query_context.avrcp_l2cap_psm);
611                                 break;
612                             case BLUETOOTH_PROTOCOL_AVCTP:
613                                 if (!des_iterator_has_more(&prot_it)) continue;
614                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &avrcp_sdp_query_context.avrcp_version);
615                                 break;
616                             default:
617                                 break;
618                         }
619                     }
620                 }
621                     break;
622                 case BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS: {
623                     // log_info("SDP Attribute: 0x%04x", sdp_event_query_attribute_byte_get_attribute_id(packet));
624                     if (!avrcp_sdp_query_context.parse_sdp_record) break;
625                     if (de_get_element_type(avrcp_sdp_query_attribute_value) != DE_DES) break;
626 
627                     des_iterator_t des_list_0_it;
628                     uint8_t       *element_0;
629 
630                     des_iterator_init(&des_list_0_it, avrcp_sdp_query_attribute_value);
631                     element_0 = des_iterator_get_element(&des_list_0_it);
632 
633                     for (des_iterator_init(&des_list_it, element_0); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
634                         uint8_t       *des_element;
635                         uint8_t       *element;
636                         uint32_t       uuid;
637 
638                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
639 
640                         des_element = des_iterator_get_element(&des_list_it);
641                         des_iterator_init(&prot_it, des_element);
642                         element = des_iterator_get_element(&prot_it);
643 
644                         if (de_get_element_type(element) != DE_UUID) continue;
645 
646                         uuid = de_get_uuid32(element);
647                         des_iterator_next(&prot_it);
648                         switch (uuid){
649                             case BLUETOOTH_PROTOCOL_L2CAP:
650                                 if (!des_iterator_has_more(&prot_it)) continue;
651                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &avrcp_sdp_query_context.browsing_l2cap_psm);
652                                 break;
653                             case BLUETOOTH_PROTOCOL_AVCTP:
654                                 if (!des_iterator_has_more(&prot_it)) continue;
655                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &avrcp_sdp_query_context.browsing_version);
656                                 break;
657                             default:
658                                 break;
659                         }
660                     }
661                 }
662                     break;
663                 default:
664                     break;
665             }
666         }
667     } else {
668         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));
669     }
670 }
671 
672 static void avrcp_handle_sdp_query_failed(avrcp_connection_t * connection, uint8_t status){
673     if (connection == NULL) return;
674     log_info("AVRCP: SDP query failed with status 0x%02x.", status);
675     avrcp_emit_connection_established(connection->avrcp_cid, connection->remote_addr, connection->con_handle, status);
676     avrcp_finalize_connection(connection);
677 }
678 
679 static void avrcp_handle_sdp_query_succeeded(avrcp_connection_t * connection){
680     if (connection == NULL) return;
681     connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
682     connection->avrcp_l2cap_psm = avrcp_sdp_query_context.avrcp_l2cap_psm;
683     connection->browsing_version = avrcp_sdp_query_context.browsing_version;
684     connection->browsing_l2cap_psm = avrcp_sdp_query_context.browsing_l2cap_psm;
685 }
686 
687 static void avrcp_handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
688     UNUSED(packet_type);
689     UNUSED(channel);
690     UNUSED(size);
691 
692     bool state_ok = true;
693     avrcp_connection_t * avrcp_target_connection = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_TARGET, avrcp_sdp_query_context.avrcp_cid);
694     if (!avrcp_target_connection || avrcp_target_connection->state != AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE) {
695         state_ok = false;
696     }
697     avrcp_connection_t * avrcp_controller_connection = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_sdp_query_context.avrcp_cid);
698     if (!avrcp_controller_connection || avrcp_controller_connection->state != AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE) {
699         state_ok = false;
700     }
701     if (!state_ok){
702         // something wrong, nevertheless, start next sdp query if this one is complete
703         if (hci_event_packet_get_type(packet) == SDP_EVENT_QUERY_COMPLETE){
704             (void) sdp_client_register_query_callback(&avrcp_sdp_query_registration);
705         }
706         return;
707     }
708 
709     uint8_t status;
710 
711     switch (hci_event_packet_get_type(packet)){
712         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
713             avrcp_handle_sdp_client_query_attribute_value(packet);
714             return;
715 
716         case SDP_EVENT_QUERY_COMPLETE:
717             status = sdp_event_query_complete_get_status(packet);
718 
719             if (status != ERROR_CODE_SUCCESS){
720                 avrcp_handle_sdp_query_failed(avrcp_controller_connection, status);
721                 avrcp_handle_sdp_query_failed(avrcp_target_connection, status);
722                 break;
723             }
724 
725             if (!avrcp_sdp_query_context.avrcp_l2cap_psm){
726                 avrcp_handle_sdp_query_failed(avrcp_controller_connection, SDP_SERVICE_NOT_FOUND);
727                 avrcp_handle_sdp_query_failed(avrcp_target_connection, SDP_SERVICE_NOT_FOUND);
728                 break;
729             }
730 
731             avrcp_handle_sdp_query_succeeded(avrcp_controller_connection);
732             avrcp_handle_sdp_query_succeeded(avrcp_target_connection);
733 
734             l2cap_create_channel(&avrcp_packet_handler, avrcp_target_connection->remote_addr, avrcp_sdp_query_context.avrcp_l2cap_psm, l2cap_max_mtu(), NULL);
735             break;
736 
737         default:
738             return;
739     }
740 
741     // register the SDP Query request to check if there is another connection waiting for the query
742     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
743     (void) sdp_client_register_query_callback(&avrcp_sdp_query_registration);
744 }
745 
746 
747 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){
748     if (connection == NULL){
749         connection = avrcp_create_connection(role, event_addr);
750     }
751     if (connection) {
752         connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
753         connection->l2cap_signaling_cid = local_cid;
754         connection->avrcp_cid = avrcp_cid;
755         connection->con_handle = con_handle;
756         btstack_run_loop_remove_timer(&connection->retry_timer);
757     }
758     return connection;
759 }
760 
761 static void avrcp_handle_open_connection(avrcp_connection_t * connection, hci_con_handle_t con_handle, uint16_t local_cid, uint16_t l2cap_mtu){
762     connection->l2cap_signaling_cid = local_cid;
763     connection->l2cap_mtu = l2cap_mtu;
764     connection->con_handle = con_handle;
765     connection->incoming_declined = false;
766     connection->song_length_ms = 0xFFFFFFFF;
767     connection->song_position_ms = 0xFFFFFFFF;
768     connection->playback_status = AVRCP_PLAYBACK_STATUS_STOPPED;
769     connection->state = AVCTP_CONNECTION_OPENED;
770 
771     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);
772 }
773 
774 static void avrcp_retry_timer_timeout_handler(btstack_timer_source_t * timer){
775     uint16_t avrcp_cid = (uint16_t)(uintptr_t) btstack_run_loop_get_timer_context(timer);
776     avrcp_connection_t * connection_controller = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_cid);
777     if (connection_controller == NULL) return;
778     avrcp_connection_t * connection_target = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_TARGET, avrcp_cid);
779     if (connection_target == NULL) return;
780 
781     if (connection_controller->state == AVCTP_CONNECTION_W2_L2CAP_RETRY){
782         connection_controller->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
783         connection_target->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
784         l2cap_create_channel(&avrcp_packet_handler, connection_controller->remote_addr, connection_controller->avrcp_l2cap_psm, l2cap_max_mtu(), NULL);
785     }
786 }
787 
788 static void avrcp_retry_timer_start(avrcp_connection_t * connection){
789     btstack_run_loop_set_timer_handler(&connection->retry_timer, avrcp_retry_timer_timeout_handler);
790     btstack_run_loop_set_timer_context(&connection->retry_timer, (void *)(uintptr_t)connection->avrcp_cid);
791 
792     // add some jitter/randomness to reconnect delay
793     uint32_t timeout = 100 + (btstack_run_loop_get_time_ms() & 0x7F);
794     btstack_run_loop_set_timer(&connection->retry_timer, timeout);
795 
796     btstack_run_loop_add_timer(&connection->retry_timer);
797 }
798 
799 static avrcp_frame_type_t avrcp_get_frame_type(uint8_t header){
800     return (avrcp_frame_type_t)((header & 0x02) >> 1);
801 }
802 
803 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
804     UNUSED(channel);
805     UNUSED(size);
806     bd_addr_t event_addr;
807     uint16_t local_cid;
808     uint16_t l2cap_mtu;
809     uint8_t  status;
810     bool decline_connection;
811     bool outoing_active;
812     hci_con_handle_t con_handle;
813 
814     avrcp_connection_t * connection_controller;
815     avrcp_connection_t * connection_target;
816     bool can_send;
817 
818     switch (packet_type) {
819         case HCI_EVENT_PACKET:
820             switch (hci_event_packet_get_type(packet)) {
821 
822                 case L2CAP_EVENT_INCOMING_CONNECTION:
823                     btstack_assert(avrcp_controller_packet_handler != NULL);
824                     btstack_assert(avrcp_target_packet_handler != NULL);
825 
826                     l2cap_event_incoming_connection_get_address(packet, event_addr);
827                     local_cid = l2cap_event_incoming_connection_get_local_cid(packet);
828                     con_handle = l2cap_event_incoming_connection_get_handle(packet);
829 
830                     outoing_active = false;
831                     connection_target = avrcp_get_connection_for_bd_addr_for_role(AVRCP_TARGET, event_addr);
832                     if (connection_target != NULL){
833                         if (connection_target->state == AVCTP_CONNECTION_W4_L2CAP_CONNECTED){
834                             outoing_active = true;
835                             connection_target->incoming_declined = true;
836                         }
837                     }
838 
839                     connection_controller = avrcp_get_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
840                     if (connection_controller != NULL){
841                         if (connection_controller->state == AVCTP_CONNECTION_W4_L2CAP_CONNECTED) {
842                             outoing_active = true;
843                             connection_controller->incoming_declined = true;
844                         }
845                     }
846 
847                     decline_connection = outoing_active;
848                     if (decline_connection == false){
849                         uint16_t avrcp_cid;
850                         if ((connection_controller == NULL) || (connection_target == NULL)){
851                             avrcp_cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
852                         } else {
853                             avrcp_cid = connection_controller->avrcp_cid;
854                         }
855                         // create two connection objects (both)
856                         connection_target     = avrcp_handle_incoming_connection_for_role(AVRCP_TARGET, connection_target, event_addr, con_handle, local_cid, avrcp_cid);
857                         connection_controller = avrcp_handle_incoming_connection_for_role(AVRCP_CONTROLLER, connection_controller, event_addr, con_handle, local_cid, avrcp_cid);
858                         if ((connection_target == NULL) || (connection_controller == NULL)){
859                             decline_connection = true;
860                             if (connection_target) {
861                                 avrcp_finalize_connection(connection_target);
862                             }
863                             if (connection_controller) {
864                                 avrcp_finalize_connection(connection_controller);
865                             }
866                         }
867                     }
868                     if (decline_connection){
869                         l2cap_decline_connection(local_cid);
870                     } else {
871                         log_info("AVRCP: L2CAP_EVENT_INCOMING_CONNECTION local cid 0x%02x, state %d", local_cid, connection_controller->state);
872                         l2cap_accept_connection(local_cid);
873                     }
874                     break;
875 
876                 case L2CAP_EVENT_CHANNEL_OPENED:
877                     l2cap_event_channel_opened_get_address(packet, event_addr);
878                     status = l2cap_event_channel_opened_get_status(packet);
879                     local_cid = l2cap_event_channel_opened_get_local_cid(packet);
880                     l2cap_mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
881                     con_handle = l2cap_event_channel_opened_get_handle(packet);
882 
883                     connection_controller = avrcp_get_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
884                     connection_target = avrcp_get_connection_for_bd_addr_for_role(AVRCP_TARGET, event_addr);
885 
886                     // incoming: structs are already created in L2CAP_EVENT_INCOMING_CONNECTION
887                     // outgoing: structs are cteated in avrcp_connect()
888                     if ((connection_controller == NULL) || (connection_target == NULL)) {
889                         break;
890                     }
891 
892                     switch (status){
893                         case ERROR_CODE_SUCCESS:
894                             avrcp_handle_open_connection(connection_target, con_handle, local_cid, l2cap_mtu);
895                             avrcp_handle_open_connection(connection_controller, con_handle, local_cid, l2cap_mtu);
896                             avrcp_emit_connection_established(connection_controller->avrcp_cid, event_addr, con_handle, status);
897                             return;
898                         case L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES:
899                             if (connection_controller->incoming_declined == true){
900                                 log_info("Incoming connection was declined, and the outgoing failed");
901                                 connection_controller->state = AVCTP_CONNECTION_W2_L2CAP_RETRY;
902                                 connection_controller->incoming_declined = false;
903                                 connection_target->state = AVCTP_CONNECTION_W2_L2CAP_RETRY;
904                                 connection_target->incoming_declined = false;
905                                 avrcp_retry_timer_start(connection_controller);
906                                 return;
907                             }
908                             break;
909                         default:
910                             break;
911                     }
912                     log_info("L2CAP connection to connection %s failed. status code 0x%02x", bd_addr_to_str(event_addr), status);
913                     avrcp_emit_connection_established(connection_controller->avrcp_cid, event_addr, con_handle, status);
914                     avrcp_finalize_connection(connection_controller);
915                     avrcp_finalize_connection(connection_target);
916 
917                     break;
918 
919                 case L2CAP_EVENT_CHANNEL_CLOSED:
920                     local_cid = l2cap_event_channel_closed_get_local_cid(packet);
921 
922                     connection_controller = avrcp_get_connection_for_l2cap_signaling_cid_for_role(AVRCP_CONTROLLER, local_cid);
923                     connection_target = avrcp_get_connection_for_l2cap_signaling_cid_for_role(AVRCP_TARGET, local_cid);
924                     if ((connection_controller == NULL) || (connection_target == NULL)) {
925                         break;
926                     }
927                     avrcp_emit_connection_closed(connection_controller->avrcp_cid);
928                     avrcp_finalize_connection(connection_controller);
929                     avrcp_finalize_connection(connection_target);
930                     break;
931 
932                 case L2CAP_EVENT_CAN_SEND_NOW:
933                     local_cid = l2cap_event_can_send_now_get_local_cid(packet);
934                     can_send = true;
935 
936                     connection_target = avrcp_get_connection_for_l2cap_signaling_cid_for_role(AVRCP_TARGET, local_cid);
937                     if ((connection_target != NULL) && connection_target->wait_to_send){
938                         connection_target->wait_to_send = false;
939                         (*avrcp_target_packet_handler)(HCI_EVENT_PACKET, channel, packet, size);
940                         can_send = false;
941                     }
942 
943                     connection_controller = avrcp_get_connection_for_l2cap_signaling_cid_for_role(AVRCP_CONTROLLER, local_cid);
944                     if ((connection_controller != NULL) && connection_controller->wait_to_send){
945                         if (can_send){
946                             connection_controller->wait_to_send = false;
947                             (*avrcp_controller_packet_handler)(HCI_EVENT_PACKET, channel, packet, size);
948                         } else {
949                             l2cap_request_can_send_now_event(local_cid);
950                         }
951                     }
952                     break;
953 
954                 default:
955                     break;
956             }
957             break;
958 
959         case L2CAP_DATA_PACKET:
960             switch (avrcp_get_frame_type(packet[0])){
961                 case AVRCP_RESPONSE_FRAME:
962                     (*avrcp_controller_packet_handler)(packet_type, channel, packet, size);
963                     break;
964                 case AVRCP_COMMAND_FRAME:
965                 default:    // make compiler happy
966                     (*avrcp_target_packet_handler)(packet_type, channel, packet, size);
967                     break;
968             }
969             break;
970 
971         default:
972             break;
973     }
974 }
975 
976 uint8_t avrcp_disconnect(uint16_t avrcp_cid){
977     avrcp_connection_t * connection_controller = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_cid);
978     if (!connection_controller){
979         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
980     }
981     avrcp_connection_t * connection_target = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_TARGET, avrcp_cid);
982     if (!connection_target){
983         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
984     }
985     if (connection_controller->browsing_connection){
986         l2cap_disconnect(connection_controller->browsing_connection->l2cap_browsing_cid);
987     }
988     l2cap_disconnect(connection_controller->l2cap_signaling_cid);
989     return ERROR_CODE_SUCCESS;
990 }
991 
992 static void avrcp_handle_start_sdp_client_query(void * context){
993     UNUSED(context);
994 
995     btstack_linked_list_iterator_t it;
996     btstack_linked_list_iterator_init(&it, &avrcp_connections);
997     while (btstack_linked_list_iterator_has_next(&it)){
998         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
999 
1000         if (connection->state != AVCTP_CONNECTION_W2_SEND_SDP_QUERY) continue;
1001         connection->state = AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE;
1002 
1003         // prevent triggering SDP query twice (for each role once)
1004         avrcp_connection_t * connection_with_opposite_role;
1005         switch (connection->role){
1006             case AVRCP_CONTROLLER:
1007                 connection_with_opposite_role = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_TARGET, connection->avrcp_cid);
1008                 break;
1009             case AVRCP_TARGET:
1010                 connection_with_opposite_role = avrcp_get_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, connection->avrcp_cid);
1011                 break;
1012             default:
1013                 btstack_assert(false);
1014                 return;
1015         }
1016         connection_with_opposite_role->state = AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE;
1017 
1018         avrcp_sdp_query_context.avrcp_l2cap_psm = 0;
1019         avrcp_sdp_query_context.avrcp_version  = 0;
1020         avrcp_sdp_query_context.avrcp_cid = connection->avrcp_cid;
1021         sdp_client_query_uuid16(&avrcp_handle_sdp_client_query_result, (uint8_t *) connection->remote_addr, BLUETOOTH_PROTOCOL_AVCTP);
1022         return;
1023     }
1024 }
1025 
1026 uint8_t avrcp_connect(bd_addr_t remote_addr, uint16_t * avrcp_cid){
1027     btstack_assert(avrcp_controller_packet_handler != NULL);
1028     btstack_assert(avrcp_target_packet_handler != NULL);
1029 
1030     avrcp_connection_t * connection_controller = avrcp_get_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, remote_addr);
1031     if (connection_controller){
1032         return ERROR_CODE_COMMAND_DISALLOWED;
1033     }
1034     avrcp_connection_t * connection_target = avrcp_get_connection_for_bd_addr_for_role(AVRCP_TARGET, remote_addr);
1035     if (connection_target){
1036         return ERROR_CODE_COMMAND_DISALLOWED;
1037     }
1038 
1039     uint16_t cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
1040 
1041     connection_controller = avrcp_create_connection(AVRCP_CONTROLLER, remote_addr);
1042     if (!connection_controller) return BTSTACK_MEMORY_ALLOC_FAILED;
1043 
1044     connection_target = avrcp_create_connection(AVRCP_TARGET, remote_addr);
1045     if (!connection_target){
1046         avrcp_finalize_connection(connection_controller);
1047         return BTSTACK_MEMORY_ALLOC_FAILED;
1048     }
1049 
1050     if (avrcp_cid != NULL){
1051         *avrcp_cid = cid;
1052     }
1053 
1054     connection_controller->state = AVCTP_CONNECTION_W2_SEND_SDP_QUERY;
1055     connection_controller->avrcp_cid = cid;
1056 
1057     connection_target->state     = AVCTP_CONNECTION_W2_SEND_SDP_QUERY;
1058     connection_target->avrcp_cid = cid;
1059 
1060     avrcp_sdp_query_registration.callback = &avrcp_handle_start_sdp_client_query;
1061     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1062     (void) sdp_client_register_query_callback(&avrcp_sdp_query_registration);
1063     return ERROR_CODE_SUCCESS;
1064 }
1065 
1066 void avrcp_init(void){
1067     avrcp_connections = NULL;
1068     if (avrcp_l2cap_service_registered) return;
1069 
1070     int status = l2cap_register_service(&avrcp_packet_handler, BLUETOOTH_PSM_AVCTP, 0xffff, gap_get_security_level());
1071     if (status != ERROR_CODE_SUCCESS) return;
1072     avrcp_l2cap_service_registered = true;
1073 }
1074 
1075 void avrcp_deinit(void){
1076     avrcp_l2cap_service_registered = false;
1077 
1078     avrcp_cid_counter = 0;
1079     avrcp_connections = NULL;
1080 
1081     avrcp_callback = NULL;
1082     avrcp_controller_packet_handler = NULL;
1083     avrcp_target_packet_handler = NULL;
1084 
1085     (void) memset(&avrcp_sdp_query_registration, 0, sizeof(avrcp_sdp_query_registration));
1086     (void) memset(&avrcp_sdp_query_context, 0, sizeof(avrcp_sdp_query_context_t));
1087     (void) memset(avrcp_sdp_query_attribute_value, 0, sizeof(avrcp_sdp_query_attribute_value));
1088 }
1089 
1090 void avrcp_register_controller_packet_handler(btstack_packet_handler_t callback){
1091     avrcp_controller_packet_handler = callback;
1092 }
1093 
1094 void avrcp_register_target_packet_handler(btstack_packet_handler_t callback){
1095     avrcp_target_packet_handler = callback;
1096 }
1097 
1098 void avrcp_register_packet_handler(btstack_packet_handler_t callback){
1099     btstack_assert(callback != NULL);
1100     avrcp_callback = callback;
1101 }
1102 
1103 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1104 #define FUZZ_CID 0x44
1105 #define FUZZ_CON_HANDLE 0x0001
1106 static bd_addr_t remote_addr = { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33 };
1107 void avrcp_init_fuzz(void){
1108     // setup avrcp connections for cid
1109     avrcp_connection_t * connection_controller = avrcp_create_connection(AVRCP_CONTROLLER, remote_addr);
1110     avrcp_connection_t * connection_target     = avrcp_create_connection(AVRCP_TARGET, remote_addr);
1111     avrcp_handle_open_connection(connection_controller, FUZZ_CON_HANDLE, FUZZ_CID, 999);
1112     avrcp_handle_open_connection(connection_target, FUZZ_CON_HANDLE, FUZZ_CID, 999);
1113 }
1114 void avrcp_packet_handler_fuzz(uint8_t *packet, uint16_t size){
1115     avrcp_packet_handler(L2CAP_DATA_PACKET, FUZZ_CID, packet, size);
1116 }
1117 #endif