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