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