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