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