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