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