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