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