xref: /btstack/src/classic/avrcp.c (revision 8ee7c9dadd27719c0c89757fa8a8c2a93e6fa0c0)
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 MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "avrcp.c"
39 
40 #include <stdint.h>
41 #include <string.h>
42 
43 #include "bluetooth_psm.h"
44 #include "bluetooth_sdp.h"
45 #include "btstack_debug.h"
46 #include "btstack_event.h"
47 #include "btstack_memory.h"
48 #include "classic/sdp_client.h"
49 #include "classic/sdp_util.h"
50 #include "classic/avrcp.h"
51 #include "classic/avrcp_controller.h"
52 
53 #define PSM_AVCTP_BROWSING              0x001b
54 
55 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
56 static void avrcp_browsing_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
57 
58 static const char * default_avrcp_controller_service_name = "BTstack AVRCP Controller Service";
59 static const char * default_avrcp_controller_service_provider_name = "BTstack AVRCP Controller Service Provider";
60 static const char * default_avrcp_target_service_name = "BTstack AVRCP Target Service";
61 static const char * default_avrcp_target_service_provider_name = "BTstack AVRCP Target Service Provider";
62 
63 static uint16_t  avrcp_cid_counter = 0;
64 
65 static avrcp_context_t * sdp_query_context;
66 static avrcp_context_t avrcp_context;
67 
68 static btstack_packet_handler_t avrcp_callback;
69 static btstack_packet_handler_t avrcp_browsing_callback;
70 
71 static uint8_t   attribute_value[45];
72 static const unsigned int attribute_value_buffer_size = sizeof(attribute_value);
73 
74 static btstack_linked_list_t connections;
75 static btstack_packet_handler_t avrcp_controller_packet_handler;
76 static btstack_packet_handler_t avrcp_target_packet_handler;
77 static bool l2cap_service_registered = false;
78 
79 static bool l2cap_browsing_service_registered = false;
80 static btstack_packet_handler_t avrcp_browsing_controller_packet_handler;
81 static btstack_packet_handler_t avrcp_browsing_target_packet_handler;
82 
83 static const char * avrcp_subunit_type_name[] = {
84     "MONITOR", "AUDIO", "PRINTER", "DISC", "TAPE_RECORDER_PLAYER", "TUNER",
85     "CA", "CAMERA", "RESERVED", "PANEL", "BULLETIN_BOARD", "CAMERA_STORAGE",
86     "VENDOR_UNIQUE", "RESERVED_FOR_ALL_SUBUNIT_TYPES",
87     "EXTENDED_TO_NEXT_BYTE", "UNIT", "ERROR"
88 };
89 
90 const char * avrcp_subunit2str(uint16_t index){
91     if (index <= 11) return avrcp_subunit_type_name[index];
92     if ((index >= 0x1C) && (index <= 0x1F)) return avrcp_subunit_type_name[index - 0x10];
93     return avrcp_subunit_type_name[16];
94 }
95 
96 static const char * avrcp_event_name[] = {
97     "ERROR", "PLAYBACK_STATUS_CHANGED",
98     "TRACK_CHANGED", "TRACK_REACHED_END", "TRACK_REACHED_START",
99     "PLAYBACK_POS_CHANGED", "BATT_STATUS_CHANGED", "SYSTEM_STATUS_CHANGED",
100     "PLAYER_APPLICATION_SETTING_CHANGED", "NOW_PLAYING_CONTENT_CHANGED",
101     "AVAILABLE_PLAYERS_CHANGED", "ADDRESSED_PLAYER_CHANGED", "UIDS_CHANGED", "VOLUME_CHANGED"
102 };
103 const char * avrcp_event2str(uint16_t index){
104     if (index <= 0x0d) return avrcp_event_name[index];
105     return avrcp_event_name[0];
106 }
107 
108 static const char * avrcp_operation_name[] = {
109     "NOT SUPPORTED", // 0x3B
110     "SKIP", "NOT SUPPORTED", "NOT SUPPORTED", "NOT SUPPORTED", "NOT SUPPORTED",
111     "VOLUME_UP", "VOLUME_DOWN", "MUTE", "PLAY", "STOP", "PAUSE", "NOT SUPPORTED",
112     "REWIND", "FAST_FORWARD", "NOT SUPPORTED", "FORWARD", "BACKWARD" // 0x4C
113 };
114 const char * avrcp_operation2str(uint8_t index){
115     if ((index >= 0x3B) && (index <= 0x4C)) return avrcp_operation_name[index - 0x3B];
116     return avrcp_operation_name[0];
117 }
118 
119 static const char * avrcp_media_attribute_id_name[] = {
120     "NONE", "TITLE", "ARTIST", "ALBUM", "TRACK", "TOTAL TRACKS", "GENRE", "SONG LENGTH"
121 };
122 const char * avrcp_attribute2str(uint8_t index){
123     if ((index >= 1) && (index <= 7)) return avrcp_media_attribute_id_name[index];
124     return avrcp_media_attribute_id_name[0];
125 }
126 
127 static const char * avrcp_play_status_name[] = {
128     "STOPPED", "PLAYING", "PAUSED", "FORWARD SEEK", "REVERSE SEEK",
129     "ERROR" // 0xFF
130 };
131 const char * avrcp_play_status2str(uint8_t index){
132     if ((index >= 1) && (index <= 4)) return avrcp_play_status_name[index];
133     return avrcp_play_status_name[5];
134 }
135 
136 static const char * avrcp_ctype_name[] = {
137     "CONTROL",
138     "STATUS",
139     "SPECIFIC_INQUIRY",
140     "NOTIFY",
141     "GENERAL_INQUIRY",
142     "RESERVED5",
143     "RESERVED6",
144     "RESERVED7",
145     "NOT IMPLEMENTED IN REMOTE",
146     "ACCEPTED BY REMOTE",
147     "REJECTED BY REMOTE",
148     "IN_TRANSITION",
149     "IMPLEMENTED_STABLE",
150     "CHANGED_STABLE",
151     "RESERVED",
152     "INTERIM"
153 };
154 const char * avrcp_ctype2str(uint8_t index){
155     if (index < sizeof(avrcp_ctype_name)){
156         return avrcp_ctype_name[index];
157     }
158     return "NONE";
159 }
160 
161 static const char * avrcp_shuffle_mode_name[] = {
162     "SHUFFLE OFF",
163     "SHUFFLE ALL TRACKS",
164     "SHUFFLE GROUP"
165 };
166 
167 const char * avrcp_shuffle2str(uint8_t index){
168     if ((index >= 1) && (index <= 3)) return avrcp_shuffle_mode_name[index-1];
169     return "NONE";
170 }
171 
172 static const char * avrcp_repeat_mode_name[] = {
173     "REPEAT OFF",
174     "REPEAT SINGLE TRACK",
175     "REPEAT ALL TRACKS",
176     "REPEAT GROUP"
177 };
178 
179 const char * avrcp_repeat2str(uint8_t index){
180     if ((index >= 1) && (index <= 4)) return avrcp_repeat_mode_name[index-1];
181     return "NONE";
182 }
183 
184 uint8_t avrcp_cmd_opcode(uint8_t *packet, uint16_t size){
185     uint8_t cmd_opcode_index = 5;
186     if (cmd_opcode_index > size) return AVRCP_CMD_OPCODE_UNDEFINED;
187     return packet[cmd_opcode_index];
188 }
189 
190 void avrcp_create_sdp_record(uint8_t controller, uint8_t * service, uint32_t service_record_handle, uint8_t browsing, uint16_t supported_features,
191     const char * service_name, const char * service_provider_name){
192     uint8_t* attribute;
193     de_create_sequence(service);
194 
195     // 0x0000 "Service Record Handle"
196     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
197     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
198 
199     // 0x0001 "Service Class ID List"
200     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
201     attribute = de_push_sequence(service);
202     {
203         if (controller){
204             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL);
205             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_CONTROLLER);
206         } else {
207             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_TARGET);
208         }
209     }
210     de_pop_sequence(service, attribute);
211 
212     // 0x0004 "Protocol Descriptor List"
213     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
214     attribute = de_push_sequence(service);
215     {
216         uint8_t* l2cpProtocol = de_push_sequence(attribute);
217         {
218             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
219             de_add_number(l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PSM_AVCTP);
220         }
221         de_pop_sequence(attribute, l2cpProtocol);
222 
223         uint8_t* avctpProtocol = de_push_sequence(attribute);
224         {
225             de_add_number(avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // avctpProtocol_service
226             de_add_number(avctpProtocol,  DE_UINT, DE_SIZE_16,  0x0103);    // version
227         }
228         de_pop_sequence(attribute, avctpProtocol);
229     }
230     de_pop_sequence(service, attribute);
231 
232     // 0x0005 "Public Browse Group"
233     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
234     attribute = de_push_sequence(service);
235     {
236         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
237     }
238     de_pop_sequence(service, attribute);
239 
240     // 0x0009 "Bluetooth Profile Descriptor List"
241     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
242     attribute = de_push_sequence(service);
243     {
244         uint8_t *avrcProfile = de_push_sequence(attribute);
245         {
246             de_add_number(avrcProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL);
247             de_add_number(avrcProfile,  DE_UINT, DE_SIZE_16, 0x0105);
248         }
249         de_pop_sequence(attribute, avrcProfile);
250     }
251     de_pop_sequence(service, attribute);
252 
253     // 0x000d "Additional Bluetooth Profile Descriptor List"
254     if (browsing){
255         de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS);
256         attribute = de_push_sequence(service);
257         {
258             uint8_t * des = de_push_sequence(attribute);
259             {
260                 uint8_t* browsing_l2cpProtocol = de_push_sequence(des);
261                 {
262                     de_add_number(browsing_l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
263                     de_add_number(browsing_l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PSM_AVCTP_BROWSING);
264                 }
265                 de_pop_sequence(des, browsing_l2cpProtocol);
266 
267                 uint8_t* browsing_avctpProtocol = de_push_sequence(des);
268                 {
269                     de_add_number(browsing_avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // browsing_avctpProtocol_service
270                     de_add_number(browsing_avctpProtocol,  DE_UINT, DE_SIZE_16,  0x0103);    // version
271                 }
272                 de_pop_sequence(des, browsing_avctpProtocol);
273             }
274             de_pop_sequence(attribute, des);
275         }
276         de_pop_sequence(service, attribute);
277     }
278 
279 
280     // 0x0100 "Service Name"
281     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
282     if (service_name){
283         de_add_data(service,  DE_STRING, strlen(service_name), (uint8_t *) service_name);
284     } else {
285         if (controller){
286             de_add_data(service,  DE_STRING, strlen(default_avrcp_controller_service_name), (uint8_t *) default_avrcp_controller_service_name);
287         } else {
288             de_add_data(service,  DE_STRING, strlen(default_avrcp_target_service_name), (uint8_t *) default_avrcp_target_service_name);
289         }
290     }
291 
292     // 0x0100 "Provider Name"
293     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0102);
294     if (service_provider_name){
295         de_add_data(service,  DE_STRING, strlen(service_provider_name), (uint8_t *) service_provider_name);
296     } else {
297         if (controller){
298             de_add_data(service,  DE_STRING, strlen(default_avrcp_controller_service_provider_name), (uint8_t *) default_avrcp_controller_service_provider_name);
299         } else {
300             de_add_data(service,  DE_STRING, strlen(default_avrcp_target_service_provider_name), (uint8_t *) default_avrcp_target_service_provider_name);
301         }
302     }
303 
304     // 0x0311 "Supported Features"
305     de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);
306     de_add_number(service, DE_UINT, DE_SIZE_16, supported_features);
307 }
308 
309 avrcp_connection_t * get_avrcp_connection_for_bd_addr_for_role(avrcp_role_t role, bd_addr_t addr){
310     btstack_linked_list_iterator_t it;
311     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
312     while (btstack_linked_list_iterator_has_next(&it)){
313         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
314         if (connection->role != role) continue;
315         if (memcmp(addr, connection->remote_addr, 6) != 0) continue;
316         return connection;
317     }
318     return NULL;
319 }
320 
321 avrcp_connection_t * get_avrcp_connection_for_l2cap_signaling_cid_for_role(avrcp_role_t role, uint16_t l2cap_cid){
322     btstack_linked_list_iterator_t it;
323     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
324     while (btstack_linked_list_iterator_has_next(&it)){
325         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
326         if (connection->role != role) continue;
327         if (connection->l2cap_signaling_cid != l2cap_cid) continue;
328         return connection;
329     }
330     return NULL;
331 }
332 
333 avrcp_connection_t * get_avrcp_connection_for_avrcp_cid_for_role(avrcp_role_t role, uint16_t avrcp_cid){
334     btstack_linked_list_iterator_t it;
335     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
336     while (btstack_linked_list_iterator_has_next(&it)){
337         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
338         if (connection->role != role) continue;
339         if (connection->avrcp_cid != avrcp_cid) continue;
340         return connection;
341     }
342     return NULL;
343 }
344 
345 avrcp_connection_t * get_avrcp_connection_for_browsing_cid_for_role(avrcp_role_t role, uint16_t browsing_cid){
346     btstack_linked_list_iterator_t it;
347     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
348     while (btstack_linked_list_iterator_has_next(&it)){
349         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
350         if (connection->role != role) continue;
351         if (connection->avrcp_browsing_cid != browsing_cid) continue;
352         return connection;
353     }
354     return NULL;
355 }
356 
357 avrcp_connection_t * get_avrcp_connection_for_browsing_l2cap_cid_for_role(avrcp_role_t role, uint16_t browsing_l2cap_cid){
358     btstack_linked_list_iterator_t it;
359     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
360     while (btstack_linked_list_iterator_has_next(&it)){
361         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
362         if (connection->role != role) continue;
363         if (connection->browsing_connection &&  (connection->browsing_connection->l2cap_browsing_cid != browsing_l2cap_cid)) continue;
364         return connection;
365     }
366     return NULL;
367 }
368 
369 avrcp_browsing_connection_t * get_avrcp_browsing_connection_for_l2cap_cid_for_role(avrcp_role_t role, uint16_t l2cap_cid){
370     btstack_linked_list_iterator_t it;
371     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
372     while (btstack_linked_list_iterator_has_next(&it)){
373         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
374         if (connection->role != role) continue;
375         if (connection->browsing_connection && (connection->browsing_connection->l2cap_browsing_cid != l2cap_cid)) continue;
376         return connection->browsing_connection;
377     }
378     return NULL;
379 }
380 
381 void avrcp_request_can_send_now(avrcp_connection_t * connection, uint16_t l2cap_cid){
382     // printf("AVRCP: avrcp_request_can_send_now, role %d\n", connection->role);
383     connection->wait_to_send = 1;
384     l2cap_request_can_send_now_event(l2cap_cid);
385 }
386 
387 void avrcp_browsing_request_can_send_now(avrcp_browsing_connection_t * connection, uint16_t l2cap_cid){
388     // printf("AVRCP: avrcp_request_can_send_now, role %d\n", connection->role);
389     connection->wait_to_send = 1;
390     l2cap_request_can_send_now_event(l2cap_cid);
391 }
392 
393 uint16_t avrcp_get_next_cid(avrcp_role_t role){
394     do {
395         if (avrcp_cid_counter == 0xffff) {
396             avrcp_cid_counter = 1;
397         } else {
398             avrcp_cid_counter++;
399         }
400     } while (get_avrcp_connection_for_avrcp_cid_for_role(role, avrcp_cid_counter) !=  NULL) ;
401     return avrcp_cid_counter;
402 }
403 
404 
405 static avrcp_connection_t * avrcp_create_connection(avrcp_role_t role, bd_addr_t remote_addr){
406     avrcp_connection_t * connection = btstack_memory_avrcp_connection_get();
407     if (!connection){
408         log_error("Not enough memory to create connection for role %d", role);
409         return NULL;
410     }
411 
412     connection->state = AVCTP_CONNECTION_IDLE;
413     connection->role = role;
414     connection->transaction_label = 0xFF;
415     connection->max_num_fragments = 0xFF;
416     log_info("avrcp_create_connection, role %d, avrcp cid 0x%02x", role, connection->avrcp_cid);
417     (void)memcpy(connection->remote_addr, remote_addr, 6);
418     btstack_linked_list_add(&connections, (btstack_linked_item_t *) connection);
419     return connection;
420 }
421 
422 static void avrcp_finalize_connection(avrcp_connection_t * connection){
423     btstack_run_loop_remove_timer(&connection->reconnect_timer);
424     btstack_linked_list_remove(&connections, (btstack_linked_item_t*) connection);
425     btstack_memory_avrcp_connection_free(connection);
426 }
427 
428 static void avrcp_emit_connection_established(uint16_t avrcp_cid, bd_addr_t addr, uint8_t status){
429     btstack_assert(avrcp_callback != NULL);
430 
431     uint8_t event[12];
432     int pos = 0;
433     event[pos++] = HCI_EVENT_AVRCP_META;
434     event[pos++] = sizeof(event) - 2;
435     event[pos++] = AVRCP_SUBEVENT_CONNECTION_ESTABLISHED;
436     event[pos++] = status;
437     reverse_bd_addr(addr,&event[pos]);
438     pos += 6;
439     little_endian_store_16(event, pos, avrcp_cid);
440     pos += 2;
441     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
442 }
443 
444 static void avrcp_emit_connection_closed(uint16_t avrcp_cid){
445     btstack_assert(avrcp_callback != NULL);
446 
447     uint8_t event[5];
448     int pos = 0;
449     event[pos++] = HCI_EVENT_AVRCP_META;
450     event[pos++] = sizeof(event) - 2;
451     event[pos++] = AVRCP_SUBEVENT_CONNECTION_RELEASED;
452     little_endian_store_16(event, pos, avrcp_cid);
453     pos += 2;
454     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
455 }
456 
457 static void avrcp_handle_sdp_client_query_attribute_value(uint8_t *packet){
458     des_iterator_t des_list_it;
459     des_iterator_t prot_it;
460 
461     // Handle new SDP record
462     if (sdp_event_query_attribute_byte_get_record_id(packet) != sdp_query_context->record_id) {
463         sdp_query_context->record_id = sdp_event_query_attribute_byte_get_record_id(packet);
464         sdp_query_context->parse_sdp_record = 0;
465         // log_info("SDP Record: Nr: %d", record_id);
466     }
467 
468     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= attribute_value_buffer_size) {
469         attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
470 
471         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
472             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
473                 case BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST:
474                     if (de_get_element_type(attribute_value) != DE_DES) break;
475                     for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
476                         uint8_t * element = des_iterator_get_element(&des_list_it);
477                         if (de_get_element_type(element) != DE_UUID) continue;
478                         uint32_t uuid = de_get_uuid32(element);
479                         switch (uuid){
480                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_TARGET:
481                                 if (sdp_query_context->role == AVRCP_CONTROLLER) {
482                                     sdp_query_context->parse_sdp_record = 1;
483                                     break;
484                                 }
485                                 break;
486                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL:
487                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_CONTROLLER:
488                                 if (sdp_query_context->role == AVRCP_TARGET) {
489                                     sdp_query_context->parse_sdp_record = 1;
490                                     break;
491                                 }
492                                 break;
493                             default:
494                                 break;
495                         }
496                     }
497                     break;
498 
499                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST: {
500                     if (!sdp_query_context->parse_sdp_record) break;
501                     // log_info("SDP Attribute: 0x%04x", sdp_event_query_attribute_byte_get_attribute_id(packet));
502                     for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
503                         uint8_t       *des_element;
504                         uint8_t       *element;
505                         uint32_t       uuid;
506 
507                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
508 
509                         des_element = des_iterator_get_element(&des_list_it);
510                         des_iterator_init(&prot_it, des_element);
511                         element = des_iterator_get_element(&prot_it);
512 
513                         if (de_get_element_type(element) != DE_UUID) continue;
514 
515                         uuid = de_get_uuid32(element);
516                         des_iterator_next(&prot_it);
517                         switch (uuid){
518                             case BLUETOOTH_PROTOCOL_L2CAP:
519                                 if (!des_iterator_has_more(&prot_it)) continue;
520                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_query_context->avrcp_l2cap_psm);
521                                 break;
522                             case BLUETOOTH_PROTOCOL_AVCTP:
523                                 if (!des_iterator_has_more(&prot_it)) continue;
524                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_query_context->avrcp_version);
525                                 break;
526                             default:
527                                 break;
528                         }
529                     }
530                 }
531                     break;
532                 case BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS: {
533                     // log_info("SDP Attribute: 0x%04x", sdp_event_query_attribute_byte_get_attribute_id(packet));
534                     if (!sdp_query_context->parse_sdp_record) break;
535                     if (de_get_element_type(attribute_value) != DE_DES) break;
536 
537                     des_iterator_t des_list_0_it;
538                     uint8_t       *element_0;
539 
540                     des_iterator_init(&des_list_0_it, attribute_value);
541                     element_0 = des_iterator_get_element(&des_list_0_it);
542 
543                     for (des_iterator_init(&des_list_it, element_0); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
544                         uint8_t       *des_element;
545                         uint8_t       *element;
546                         uint32_t       uuid;
547 
548                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
549 
550                         des_element = des_iterator_get_element(&des_list_it);
551                         des_iterator_init(&prot_it, des_element);
552                         element = des_iterator_get_element(&prot_it);
553 
554                         if (de_get_element_type(element) != DE_UUID) continue;
555 
556                         uuid = de_get_uuid32(element);
557                         des_iterator_next(&prot_it);
558                         switch (uuid){
559                             case BLUETOOTH_PROTOCOL_L2CAP:
560                                 if (!des_iterator_has_more(&prot_it)) continue;
561                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_query_context->browsing_l2cap_psm);
562                                 break;
563                             case BLUETOOTH_PROTOCOL_AVCTP:
564                                 if (!des_iterator_has_more(&prot_it)) continue;
565                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_query_context->browsing_version);
566                                 break;
567                             default:
568                                 break;
569                         }
570                     }
571                 }
572                     break;
573                 default:
574                     break;
575             }
576         }
577     } else {
578         log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, sdp_event_query_attribute_byte_get_attribute_length(packet));
579     }
580 }
581 
582 static void avrcp_handle_sdp_query_failed(avrcp_connection_t * connection, uint8_t status){
583     if (connection == NULL) return;
584     log_info("AVRCP: SDP query failed with status 0x%02x.", status);
585     avrcp_emit_connection_established(connection->avrcp_cid, connection->remote_addr, status);
586     avrcp_finalize_connection(connection);
587 }
588 
589 static void avrcp_handle_sdp_query_succeeded(avrcp_connection_t * connection){
590     if (connection == NULL) return;
591     connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
592     connection->avrcp_l2cap_psm = sdp_query_context->avrcp_l2cap_psm;
593     connection->browsing_version = sdp_query_context->browsing_version;
594     connection->browsing_l2cap_psm = sdp_query_context->browsing_l2cap_psm;
595 }
596 
597 static void avrcp_handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
598     UNUSED(packet_type);
599     UNUSED(channel);
600     UNUSED(size);
601 
602     avrcp_connection_t * avrcp_target_connection = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, sdp_query_context->remote_addr);
603     avrcp_connection_t * avrcp_controller_connection = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, sdp_query_context->remote_addr);
604 
605     uint8_t status;
606 
607     switch (hci_event_packet_get_type(packet)){
608         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
609             avrcp_handle_sdp_client_query_attribute_value(packet);
610             break;
611 
612         case SDP_EVENT_QUERY_COMPLETE:
613             status = sdp_event_query_complete_get_status(packet);
614 
615             if (status != ERROR_CODE_SUCCESS){
616                 avrcp_handle_sdp_query_failed(avrcp_controller_connection, status);
617                 avrcp_handle_sdp_query_failed(avrcp_target_connection, status);
618                 break;
619             }
620 
621             if (!sdp_query_context->avrcp_l2cap_psm){
622                 avrcp_handle_sdp_query_failed(avrcp_controller_connection, SDP_SERVICE_NOT_FOUND);
623                 avrcp_handle_sdp_query_failed(avrcp_target_connection, SDP_SERVICE_NOT_FOUND);
624                 break;
625             }
626 
627             avrcp_handle_sdp_query_succeeded(avrcp_controller_connection);
628             avrcp_handle_sdp_query_succeeded(avrcp_target_connection);
629 
630             l2cap_create_channel(&avrcp_packet_handler, sdp_query_context->remote_addr, sdp_query_context->avrcp_l2cap_psm, l2cap_max_mtu(), NULL);
631             break;
632 
633         default:
634             break;
635 
636     }
637 }
638 
639 
640 static avrcp_connection_t * avrcp_handle_incoming_connection_for_role(avrcp_role_t role, avrcp_connection_t * connection, bd_addr_t event_addr, uint16_t local_cid, uint16_t avrcp_cid){
641     if (connection == NULL){
642         connection = avrcp_create_connection(role, event_addr);
643     }
644     if (connection) {
645         connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
646         connection->l2cap_signaling_cid = local_cid;
647         connection->avrcp_cid = avrcp_cid;
648         btstack_run_loop_remove_timer(&connection->reconnect_timer);
649     }
650     return connection;
651 }
652 
653 static void avrcp_handle_open_connection_for_role( avrcp_connection_t * connection, uint16_t local_cid, uint16_t l2cap_mtu){
654     connection->l2cap_signaling_cid = local_cid;
655     connection->l2cap_mtu = l2cap_mtu;
656     connection->incoming_declined = false;
657     connection->song_length_ms = 0xFFFFFFFF;
658     connection->song_position_ms = 0xFFFFFFFF;
659     connection->playback_status = AVRCP_PLAYBACK_STATUS_ERROR;
660     connection->state = AVCTP_CONNECTION_OPENED;
661 
662     log_info("L2CAP_EVENT_CHANNEL_OPENED avrcp_cid 0x%02x, l2cap_signaling_cid 0x%02x, role %d", connection->avrcp_cid, connection->l2cap_signaling_cid, connection->role);
663 }
664 
665 static void avrcp_reconnect_timer_timeout_handler(btstack_timer_source_t * timer){
666     uint16_t avrcp_cid = (uint16_t)(uintptr_t) btstack_run_loop_get_timer_context(timer);
667     avrcp_connection_t * controller_connection = get_avrcp_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_cid);
668     if (controller_connection == NULL) return;
669     avrcp_connection_t * target_connection = get_avrcp_connection_for_avrcp_cid_for_role(AVRCP_TARGET, avrcp_cid);
670     if (target_connection == NULL) return;
671 
672     controller_connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
673     target_connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
674 
675     l2cap_create_channel(&avrcp_packet_handler, controller_connection->remote_addr, controller_connection->avrcp_l2cap_psm, l2cap_max_mtu(), NULL);
676 }
677 
678 static void avrcp_reconnect_timer_start(avrcp_connection_t * connection){
679     btstack_run_loop_set_timer_handler(&connection->reconnect_timer, avrcp_reconnect_timer_timeout_handler);
680     btstack_run_loop_set_timer_context(&connection->reconnect_timer, (void *)(uintptr_t)connection->avrcp_cid);
681 
682     // add some jitter/randomness to reconnect delay
683     uint32_t timeout = 100 + (btstack_run_loop_get_time_ms() & 0x7F);
684     btstack_run_loop_set_timer(&connection->reconnect_timer, timeout);
685 
686     btstack_run_loop_add_timer(&connection->reconnect_timer);
687 }
688 
689 static avrcp_frame_type_t avrcp_get_frame_type(uint8_t header){
690     return (avrcp_frame_type_t)((header & 0x02) >> 1);
691 }
692 
693 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
694     UNUSED(channel);
695     UNUSED(size);
696     bd_addr_t event_addr;
697     uint16_t local_cid;
698     uint16_t l2cap_mtu;
699     uint8_t  status;
700     bool decline_connection;
701     bool outoing_active;
702 
703     avrcp_connection_t * connection_controller;
704     avrcp_connection_t * connection_target;
705 
706     switch (packet_type) {
707         case HCI_EVENT_PACKET:
708             switch (hci_event_packet_get_type(packet)) {
709 
710                 case L2CAP_EVENT_INCOMING_CONNECTION:
711                     btstack_assert(avrcp_controller_packet_handler != NULL);
712                     btstack_assert(avrcp_target_packet_handler != NULL);
713 
714                     l2cap_event_incoming_connection_get_address(packet, event_addr);
715                     local_cid = l2cap_event_incoming_connection_get_local_cid(packet);
716                     outoing_active = false;
717 
718                     connection_target = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, event_addr);
719                     if (connection_target != NULL){
720                         if (connection_target->state == AVCTP_CONNECTION_W4_L2CAP_CONNECTED){
721                             outoing_active = true;
722                             connection_target->incoming_declined = true;
723                         }
724                     }
725 
726                     connection_controller = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
727                     if (connection_controller != NULL){
728                         if (connection_controller->state == AVCTP_CONNECTION_W4_L2CAP_CONNECTED) {
729                             outoing_active = true;
730                             connection_controller->incoming_declined = true;
731                         }
732                     }
733 
734                     decline_connection = outoing_active;
735                     if (decline_connection == false){
736                         uint16_t avrcp_cid;
737                         if ((connection_controller == NULL) || (connection_target == NULL)){
738                             avrcp_cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
739                         } else {
740                             avrcp_cid = connection_controller->avrcp_cid;
741                         }
742                         // create two connection objects (both)
743                         connection_target     = avrcp_handle_incoming_connection_for_role(AVRCP_TARGET, connection_target, event_addr, local_cid, avrcp_cid);
744                         connection_controller = avrcp_handle_incoming_connection_for_role(AVRCP_CONTROLLER, connection_controller, event_addr, local_cid, avrcp_cid);
745                         if ((connection_target == NULL) || (connection_controller == NULL)){
746                             decline_connection = true;
747                             if (connection_target) {
748                                 avrcp_finalize_connection(connection_target);
749                             }
750                             if (connection_controller) {
751                                 avrcp_finalize_connection(connection_controller);
752                             }
753                         }
754                     }
755                     if (decline_connection){
756                         l2cap_decline_connection(local_cid);
757                     } else {
758                         log_info("AVRCP: L2CAP_EVENT_INCOMING_CONNECTION avrcp_cid 0x%02x", local_cid);
759                         l2cap_accept_connection(local_cid);
760                     }
761                     break;
762 
763                 case L2CAP_EVENT_CHANNEL_OPENED:
764                     l2cap_event_channel_opened_get_address(packet, event_addr);
765                     status = l2cap_event_channel_opened_get_status(packet);
766                     local_cid = l2cap_event_channel_opened_get_local_cid(packet);
767                     l2cap_mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
768 
769                     connection_controller = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
770                     connection_target = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, event_addr);
771 
772                     // incoming: structs are already created in L2CAP_EVENT_INCOMING_CONNECTION
773                     // outgoing: structs are cteated in avrcp_connect()
774                     if ((connection_controller == NULL) || (connection_target == NULL)) {
775                         break;
776                     }
777 
778                     switch (status){
779                         case ERROR_CODE_SUCCESS:
780                             avrcp_handle_open_connection_for_role(connection_target, local_cid, l2cap_mtu);
781                             avrcp_handle_open_connection_for_role(connection_controller, local_cid, l2cap_mtu);
782                             avrcp_emit_connection_established(connection_controller->avrcp_cid, event_addr, status);
783                             return;
784                         case L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES:
785                             if (connection_controller->incoming_declined == true){
786                                 log_info("Incoming connection was declined, and the outgoing failed");
787                                 connection_controller->state = AVCTP_CONNECTION_W2_L2CAP_RECONNECT;
788                                 connection_controller->incoming_declined = false;
789                                 connection_target->state = AVCTP_CONNECTION_W2_L2CAP_RECONNECT;
790                                 connection_target->incoming_declined = false;
791                                 avrcp_reconnect_timer_start(connection_controller);
792                                 return;
793                             }
794                             break;
795                         default:
796                             break;
797                     }
798                     log_info("L2CAP connection to connection %s failed. status code 0x%02x", bd_addr_to_str(event_addr), status);
799                     avrcp_emit_connection_established(connection_controller->avrcp_cid, event_addr, status);
800                     avrcp_finalize_connection(connection_controller);
801                     avrcp_finalize_connection(connection_target);
802 
803                     break;
804 
805                 case L2CAP_EVENT_CHANNEL_CLOSED:
806                     local_cid = l2cap_event_channel_closed_get_local_cid(packet);
807 
808                     connection_controller = get_avrcp_connection_for_l2cap_signaling_cid_for_role(AVRCP_CONTROLLER, local_cid);
809                     connection_target = get_avrcp_connection_for_l2cap_signaling_cid_for_role(AVRCP_TARGET, local_cid);
810                     if ((connection_controller == NULL) || (connection_target == NULL)) {
811                         break;
812                     }
813                     avrcp_emit_connection_closed(connection_controller->avrcp_cid);
814                     avrcp_finalize_connection(connection_controller);
815 
816                     avrcp_emit_connection_closed(connection_target->avrcp_cid);
817                     avrcp_finalize_connection(connection_target);
818                     break;
819 
820                 case L2CAP_EVENT_CAN_SEND_NOW:
821                     local_cid = l2cap_event_can_send_now_get_local_cid(packet);
822 
823                     connection_target = get_avrcp_connection_for_l2cap_signaling_cid_for_role(AVRCP_TARGET, local_cid);
824                     if (connection_target && connection_target->wait_to_send){
825                         connection_target->wait_to_send = 0;
826                         (*avrcp_target_packet_handler)(HCI_EVENT_PACKET, channel, packet, size);
827                         break;
828                     }
829 
830                     connection_controller = get_avrcp_connection_for_l2cap_signaling_cid_for_role(AVRCP_CONTROLLER, local_cid);
831                     if (connection_controller && connection_controller->wait_to_send){
832                         connection_controller->wait_to_send = 0;
833                         (*avrcp_controller_packet_handler)(HCI_EVENT_PACKET, channel, packet, size);
834                         break;
835                     }
836                     break;
837 
838                 default:
839                     break;
840             }
841             break;
842 
843         case L2CAP_DATA_PACKET:
844             switch (avrcp_get_frame_type(packet[0])){
845                 case AVRCP_RESPONSE_FRAME:
846                     (*avrcp_controller_packet_handler)(packet_type, channel, packet, size);
847                     break;
848                 case AVRCP_COMMAND_FRAME:
849                 default:    // make compiler happy
850                     (*avrcp_target_packet_handler)(packet_type, channel, packet, size);
851                     break;
852             }
853             break;
854 
855         default:
856             break;
857     }
858 }
859 
860 uint8_t avrcp_disconnect(uint16_t avrcp_cid){
861     avrcp_connection_t * connection_controller = get_avrcp_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_cid);
862     if (!connection_controller){
863         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
864     }
865     avrcp_connection_t * connection_target = get_avrcp_connection_for_avrcp_cid_for_role(AVRCP_TARGET, avrcp_cid);
866     if (!connection_target){
867         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
868     }
869     if (connection_controller->browsing_connection){
870         l2cap_disconnect(connection_controller->browsing_connection->l2cap_browsing_cid, 0);
871     }
872     l2cap_disconnect(connection_controller->l2cap_signaling_cid, 0);
873     return ERROR_CODE_SUCCESS;
874 }
875 
876 uint8_t avrcp_connect(bd_addr_t remote_addr, uint16_t * avrcp_cid){
877     btstack_assert(avrcp_controller_packet_handler != NULL);
878     btstack_assert(avrcp_target_packet_handler != NULL);
879 
880     // TODO: implement delayed SDP query
881     if (sdp_client_ready() == 0){
882         return ERROR_CODE_COMMAND_DISALLOWED;
883     }
884 
885     avrcp_connection_t * connection_controller = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, remote_addr);
886     if (connection_controller){
887         return ERROR_CODE_COMMAND_DISALLOWED;
888     }
889     avrcp_connection_t * connection_target = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, remote_addr);
890     if (connection_target){
891         return ERROR_CODE_COMMAND_DISALLOWED;
892     }
893 
894     uint16_t cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
895 
896     connection_controller = avrcp_create_connection(AVRCP_CONTROLLER, remote_addr);
897     if (!connection_controller) return BTSTACK_MEMORY_ALLOC_FAILED;
898 
899     connection_target = avrcp_create_connection(AVRCP_TARGET, remote_addr);
900     if (!connection_target){
901         avrcp_finalize_connection(connection_controller);
902         return BTSTACK_MEMORY_ALLOC_FAILED;
903     }
904 
905     if (avrcp_cid != NULL){
906         *avrcp_cid = cid;
907     }
908 
909     connection_controller->state = AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE;
910     connection_controller->avrcp_cid = cid;
911 
912     connection_target->state     = AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE;
913     connection_target->avrcp_cid = cid;
914 
915     sdp_query_context = &avrcp_context;
916     sdp_query_context->avrcp_l2cap_psm = 0;
917     sdp_query_context->avrcp_version  = 0;
918     sdp_query_context->avrcp_cid = cid;
919     memcpy(sdp_query_context->remote_addr, remote_addr, 6);
920 
921     sdp_client_query_uuid16(&avrcp_handle_sdp_client_query_result, remote_addr, BLUETOOTH_PROTOCOL_AVCTP);
922     return ERROR_CODE_SUCCESS;
923 }
924 
925 void avrcp_init(void){
926     connections = NULL;
927     if (l2cap_service_registered) return;
928 
929     int status = l2cap_register_service(&avrcp_packet_handler, BLUETOOTH_PSM_AVCTP, 0xffff, gap_get_security_level());
930     if (status != ERROR_CODE_SUCCESS) return;
931     l2cap_service_registered = true;
932 }
933 
934 void avrcp_register_controller_packet_handler(btstack_packet_handler_t callback){
935     avrcp_controller_packet_handler = callback;
936 }
937 
938 void avrcp_register_target_packet_handler(btstack_packet_handler_t callback){
939     avrcp_target_packet_handler = callback;
940 }
941 
942 void avrcp_register_packet_handler(btstack_packet_handler_t callback){
943     btstack_assert(callback != NULL);
944     avrcp_callback = callback;
945 }
946 
947 // AVRCP Browsing Service functions
948 static void avrcp_browsing_finalize_connection(avrcp_connection_t * connection){
949     btstack_run_loop_remove_timer(&connection->browsing_connection->reconnect_timer);
950     btstack_memory_avrcp_browsing_connection_free(connection->browsing_connection);
951     connection->browsing_connection = NULL;
952 }
953 
954 static void avrcp_emit_browsing_connection_established(uint16_t browsing_cid, bd_addr_t addr, uint8_t status){
955     btstack_assert(avrcp_browsing_callback != NULL);
956 
957     uint8_t event[12];
958     int pos = 0;
959     event[pos++] = HCI_EVENT_AVRCP_META;
960     event[pos++] = sizeof(event) - 2;
961     event[pos++] = AVRCP_SUBEVENT_BROWSING_CONNECTION_ESTABLISHED;
962     event[pos++] = status;
963     reverse_bd_addr(addr,&event[pos]);
964     pos += 6;
965     little_endian_store_16(event, pos, browsing_cid);
966     pos += 2;
967     (*avrcp_browsing_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
968 }
969 
970 static void avrcp_emit_incoming_browsing_connection(uint16_t browsing_cid, bd_addr_t addr){
971     btstack_assert(avrcp_browsing_callback != NULL);
972 
973     uint8_t event[11];
974     int pos = 0;
975     event[pos++] = HCI_EVENT_AVRCP_META;
976     event[pos++] = sizeof(event) - 2;
977     event[pos++] = AVRCP_SUBEVENT_INCOMING_BROWSING_CONNECTION;
978     reverse_bd_addr(addr,&event[pos]);
979     pos += 6;
980     little_endian_store_16(event, pos, browsing_cid);
981     pos += 2;
982     (*avrcp_browsing_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
983 }
984 
985 static void avrcp_emit_browsing_connection_closed(uint16_t browsing_cid){
986     btstack_assert(avrcp_browsing_callback != NULL);
987 
988     uint8_t event[5];
989     int pos = 0;
990     event[pos++] = HCI_EVENT_AVRCP_META;
991     event[pos++] = sizeof(event) - 2;
992     event[pos++] = AVRCP_SUBEVENT_BROWSING_CONNECTION_RELEASED;
993     little_endian_store_16(event, pos, browsing_cid);
994     pos += 2;
995     (*avrcp_browsing_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
996 }
997 
998 
999 static avrcp_browsing_connection_t * avrcp_browsing_create_connection(avrcp_connection_t * avrcp_connection, uint16_t avrcp_browsing_cid){
1000     avrcp_browsing_connection_t * browsing_connection = btstack_memory_avrcp_browsing_connection_get();
1001     if (!browsing_connection){
1002         log_error("Not enough memory to create browsing connection");
1003         return NULL;
1004     }
1005     browsing_connection->state = AVCTP_CONNECTION_IDLE;
1006     browsing_connection->transaction_label = 0xFF;
1007 
1008     avrcp_connection->avrcp_browsing_cid = avrcp_browsing_cid;
1009     avrcp_connection->browsing_connection = browsing_connection;
1010 
1011     log_info("avrcp_browsing_create_connection, avrcp cid 0x%02x", avrcp_connection->avrcp_browsing_cid);
1012     return browsing_connection;
1013 }
1014 
1015 static void avrcp_browsing_configure_ertm(avrcp_browsing_connection_t * browsing_connection, uint8_t * ertm_buffer, uint32_t ertm_buffer_size, l2cap_ertm_config_t * ertm_config){
1016     browsing_connection->ertm_buffer = ertm_buffer;
1017     browsing_connection->ertm_buffer_size = ertm_buffer_size;
1018 
1019     if (ertm_buffer_size > 0) {
1020         (void)memcpy(&browsing_connection->ertm_config, ertm_config,
1021                  sizeof(l2cap_ertm_config_t));
1022         log_info("avrcp_browsing_configure_ertm");
1023     }
1024 }
1025 
1026 static avrcp_browsing_connection_t * avrcp_browsing_handle_incoming_connection(avrcp_connection_t * connection, uint16_t local_cid, uint16_t avrcp_browsing_cid){
1027     if (connection->browsing_connection == NULL){
1028         avrcp_browsing_create_connection(connection, avrcp_browsing_cid);
1029     }
1030     if (connection->browsing_connection) {
1031         connection->browsing_connection->l2cap_browsing_cid = local_cid;
1032         connection->browsing_connection->state = AVCTP_CONNECTION_W4_ERTM_CONFIGURATION;
1033         btstack_run_loop_remove_timer(&connection->browsing_connection->reconnect_timer);
1034     }
1035     return connection->browsing_connection;
1036 }
1037 
1038 static void avrcp_browsing_handle_open_connection_for_role( avrcp_connection_t * connection, uint16_t local_cid){
1039     connection->browsing_connection->l2cap_browsing_cid = local_cid;
1040     connection->browsing_connection->incoming_declined = false;
1041     connection->browsing_connection->state = AVCTP_CONNECTION_OPENED;
1042     log_info("L2CAP_EVENT_CHANNEL_OPENED browsing_avrcp_cid 0x%02x, l2cap_signaling_cid 0x%02x, role %d", connection->avrcp_cid, connection->l2cap_signaling_cid, connection->role);
1043 }
1044 
1045 static void avrcp_browsing_packet_handler_with_role(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, avrcp_role_t avrcp_role){
1046     UNUSED(channel);
1047     UNUSED(size);
1048     bd_addr_t event_addr;
1049     uint16_t local_cid;
1050     uint8_t  status;
1051     bool decline_connection;
1052     bool outoing_active;
1053 
1054     btstack_packet_handler_t browsing_callback;
1055     avrcp_connection_t * connection_controller;
1056     avrcp_connection_t * connection_target;
1057 
1058     switch (packet_type){
1059         case L2CAP_DATA_PACKET:
1060             switch (avrcp_get_frame_type(packet[0])){
1061                 case AVRCP_RESPONSE_FRAME:
1062                     (*avrcp_browsing_controller_packet_handler)(packet_type, channel, packet, size);
1063                     break;
1064                 case AVRCP_COMMAND_FRAME:
1065                 default:    // make compiler happy
1066                     (*avrcp_browsing_target_packet_handler)(packet_type, channel, packet, size);
1067                     break;
1068             }
1069             break;
1070         case HCI_EVENT_PACKET:
1071              switch (avrcp_role){
1072                 case AVRCP_CONTROLLER:
1073                     browsing_callback = avrcp_browsing_controller_packet_handler;
1074                     break;
1075                 case AVRCP_TARGET:
1076                 default:
1077                     browsing_callback = avrcp_browsing_target_packet_handler;
1078                     break;
1079             }
1080             btstack_assert(browsing_callback != NULL);
1081 
1082             switch (hci_event_packet_get_type(packet)) {
1083 
1084                 case L2CAP_EVENT_INCOMING_CONNECTION:
1085                     btstack_assert(avrcp_browsing_controller_packet_handler != NULL);
1086                     btstack_assert(avrcp_browsing_target_packet_handler != NULL);
1087 
1088                     l2cap_event_incoming_connection_get_address(packet, event_addr);
1089                     local_cid = l2cap_event_incoming_connection_get_local_cid(packet);
1090                     outoing_active = false;
1091 
1092                     connection_target = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, event_addr);
1093                     connection_controller = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
1094 
1095                     if (connection_target == NULL || connection_controller == NULL) {
1096                         l2cap_decline_connection(local_cid);
1097                         return;
1098                     }
1099 
1100                     if (connection_target->browsing_connection != NULL){
1101                         if (connection_target->browsing_connection->state == AVCTP_CONNECTION_W4_L2CAP_CONNECTED){
1102                             outoing_active = true;
1103                             connection_target->browsing_connection->incoming_declined = true;
1104                         }
1105                     }
1106 
1107                     if (connection_controller->browsing_connection != NULL){
1108                         if (connection_controller->browsing_connection->state == AVCTP_CONNECTION_W4_L2CAP_CONNECTED) {
1109                             outoing_active = true;
1110                             connection_controller->browsing_connection->incoming_declined = true;
1111                         }
1112                     }
1113 
1114                     decline_connection = outoing_active;
1115                     if (decline_connection == false){
1116                         uint16_t avrcp_browsing_cid;
1117                         if ((connection_controller->browsing_connection == NULL) || (connection_target->browsing_connection == NULL)){
1118                             avrcp_browsing_cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
1119                         } else {
1120                             avrcp_browsing_cid = connection_controller->avrcp_browsing_cid;
1121                         }
1122 
1123                         // create two connection objects (both)
1124                         connection_target->browsing_connection     = avrcp_browsing_handle_incoming_connection(connection_target, local_cid, avrcp_browsing_cid);
1125                         connection_controller->browsing_connection = avrcp_browsing_handle_incoming_connection(connection_controller, local_cid, avrcp_browsing_cid);
1126 
1127                         if ((connection_target->browsing_connection  == NULL) || (connection_controller->browsing_connection == NULL)){
1128                             decline_connection = true;
1129                             if (connection_target->browsing_connection) {
1130                                 avrcp_browsing_finalize_connection(connection_target);
1131                             }
1132                             if (connection_controller->browsing_connection) {
1133                                 avrcp_browsing_finalize_connection(connection_controller);
1134                             }
1135                         }
1136                     }
1137                     if (decline_connection){
1138                         l2cap_decline_connection(local_cid);
1139                     } else {
1140                         log_info("AVRCP: L2CAP_EVENT_INCOMING_CONNECTION browsing_avrcp_cid 0x%02x", connection_controller->avrcp_browsing_cid);
1141                         avrcp_emit_incoming_browsing_connection(connection_controller->avrcp_browsing_cid, event_addr);
1142                     }
1143                     break;
1144 
1145                 case L2CAP_EVENT_CHANNEL_OPENED:
1146                     l2cap_event_channel_opened_get_address(packet, event_addr);
1147                     status = l2cap_event_channel_opened_get_status(packet);
1148                     local_cid = l2cap_event_channel_opened_get_local_cid(packet);
1149                     log_info("received L2CAP_EVENT_CHANNEL_OPENED, cid 0x%02x", local_cid);
1150 
1151                     connection_controller = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
1152                     if (!connection_controller){
1153                         log_error("Failed to find AVRCP connection for bd_addr %s", bd_addr_to_str(event_addr));
1154                         avrcp_emit_browsing_connection_established(local_cid, event_addr, L2CAP_LOCAL_CID_DOES_NOT_EXIST);
1155                         l2cap_disconnect(local_cid, 0); // reason isn't used
1156                         break;
1157                     }
1158 
1159                     if (status != ERROR_CODE_SUCCESS){
1160                         log_info("L2CAP connection to connection %s failed. status code 0x%02x", bd_addr_to_str(event_addr), status);
1161                         avrcp_emit_browsing_connection_established(connection_controller->avrcp_browsing_cid, event_addr, status);
1162                         avrcp_browsing_finalize_connection(connection_controller);
1163                         break;
1164                     }
1165                     if (connection_controller->browsing_connection->state != AVCTP_CONNECTION_W4_L2CAP_CONNECTED) break;
1166 
1167                     connection_controller->browsing_connection->l2cap_browsing_cid = local_cid;
1168 
1169                     log_info("L2CAP_EVENT_CHANNEL_OPENED browsing cid 0x%02x, l2cap cid 0x%02x", connection_controller->avrcp_browsing_cid, connection_controller->browsing_connection->l2cap_browsing_cid);
1170                     connection_controller->browsing_connection->state = AVCTP_CONNECTION_OPENED;
1171                     avrcp_emit_browsing_connection_established(connection_controller->avrcp_browsing_cid, event_addr, ERROR_CODE_SUCCESS);
1172                     break;
1173 
1174                 case L2CAP_EVENT_CHANNEL_CLOSED:
1175                     local_cid = l2cap_event_channel_closed_get_local_cid(packet);
1176                     connection_controller = get_avrcp_connection_for_browsing_l2cap_cid_for_role(AVRCP_CONTROLLER, local_cid);
1177 
1178                     if (connection_controller && connection_controller->browsing_connection){
1179                         avrcp_emit_browsing_connection_closed(connection_controller->avrcp_browsing_cid);
1180                         avrcp_browsing_finalize_connection(connection_controller);
1181                         break;
1182                     }
1183                     break;
1184                 case HCI_EVENT_DISCONNECTION_COMPLETE:
1185                     avrcp_emit_browsing_connection_closed(ERROR_CODE_SUCCESS);
1186                     break;
1187                 case L2CAP_EVENT_CAN_SEND_NOW:
1188                     (*browsing_callback)(packet_type, channel, packet, size);
1189                     break;
1190 
1191                 default:
1192                     break;
1193             }
1194             break;
1195         default:
1196             break;
1197     }
1198 
1199 }
1200 
1201 static void avrcp_browsing_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1202     avrcp_browsing_packet_handler_with_role(packet_type, channel, packet, size, AVRCP_CONTROLLER);
1203     // avrcp_browsing_packet_handler_with_role(packet_type, channel, packet, size, AVRCP_TARGET);
1204 }
1205 
1206 void avrcp_browsing_init(void){
1207     if (l2cap_browsing_service_registered) return;
1208     int status = l2cap_register_service(&avrcp_browsing_packet_handler, PSM_AVCTP_BROWSING, 0xffff, LEVEL_2);
1209 
1210     if (status != ERROR_CODE_SUCCESS) return;
1211     l2cap_browsing_service_registered = true;
1212 }
1213 
1214 
1215 uint8_t avrcp_browsing_connect(bd_addr_t remote_addr, uint8_t * ertm_buffer, uint32_t ertm_buffer_size, l2cap_ertm_config_t * ertm_config, uint16_t * avrcp_browsing_cid){
1216     btstack_assert(avrcp_browsing_controller_packet_handler != NULL);
1217     btstack_assert(avrcp_browsing_target_packet_handler != NULL);
1218 
1219     avrcp_connection_t * connection_controller = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, remote_addr);
1220     if (!connection_controller){
1221         return ERROR_CODE_COMMAND_DISALLOWED;
1222     }
1223     avrcp_connection_t * connection_target = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, remote_addr);
1224     if (!connection_target){
1225         return ERROR_CODE_COMMAND_DISALLOWED;
1226     }
1227 
1228     if (connection_controller->browsing_connection){
1229         return ERROR_CODE_COMMAND_DISALLOWED;
1230     }
1231     if (connection_target->browsing_connection){
1232         return ERROR_CODE_COMMAND_DISALLOWED;
1233     }
1234 
1235     uint16_t cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
1236 
1237     connection_controller->browsing_connection = avrcp_browsing_create_connection(connection_controller, cid);
1238     if (!connection_controller->browsing_connection) return BTSTACK_MEMORY_ALLOC_FAILED;
1239 
1240     connection_target->browsing_connection = avrcp_browsing_create_connection(connection_target, cid);
1241     if (!connection_target->browsing_connection){
1242         avrcp_browsing_finalize_connection(connection_controller);
1243         return BTSTACK_MEMORY_ALLOC_FAILED;
1244     }
1245     avrcp_browsing_configure_ertm(connection_controller->browsing_connection, ertm_buffer, ertm_buffer_size, ertm_config);
1246     avrcp_browsing_configure_ertm(connection_target->browsing_connection, ertm_buffer, ertm_buffer_size, ertm_config);
1247 
1248     if (avrcp_browsing_cid != NULL){
1249         *avrcp_browsing_cid = cid;
1250     }
1251 
1252     connection_controller->browsing_connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
1253     connection_target->browsing_connection->state     = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
1254 
1255     return l2cap_create_ertm_channel(avrcp_browsing_packet_handler, remote_addr, connection_controller->browsing_l2cap_psm,
1256                     &connection_controller->browsing_connection->ertm_config,
1257                     connection_controller->browsing_connection->ertm_buffer,
1258                     connection_controller->browsing_connection->ertm_buffer_size, NULL);
1259 
1260 }
1261 
1262 uint8_t avrcp_browsing_configure_incoming_connection(uint16_t avrcp_browsing_cid, uint8_t * ertm_buffer, uint32_t ertm_buffer_size, l2cap_ertm_config_t * ertm_config){
1263     avrcp_connection_t * connection_controller = get_avrcp_connection_for_browsing_cid_for_role(AVRCP_CONTROLLER, avrcp_browsing_cid);
1264     if (!connection_controller){
1265         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1266     }
1267     avrcp_connection_t * connection_target = get_avrcp_connection_for_browsing_cid_for_role(AVRCP_TARGET, avrcp_browsing_cid);
1268     if (!connection_target){
1269         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1270     }
1271 
1272     if (!connection_controller->browsing_connection){
1273         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1274     }
1275     if (!connection_target->browsing_connection){
1276         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1277     }
1278 
1279     if (connection_controller->browsing_connection->state != AVCTP_CONNECTION_W4_ERTM_CONFIGURATION){
1280         return ERROR_CODE_COMMAND_DISALLOWED;
1281     }
1282 
1283     avrcp_browsing_configure_ertm(connection_controller->browsing_connection, ertm_buffer, ertm_buffer_size, ertm_config);
1284     avrcp_browsing_configure_ertm(connection_target->browsing_connection, ertm_buffer, ertm_buffer_size, ertm_config);
1285 
1286     connection_controller->browsing_connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
1287     connection_target->browsing_connection->state     = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
1288 
1289     l2cap_accept_ertm_connection(connection_controller->browsing_connection->l2cap_browsing_cid,
1290         &connection_controller->browsing_connection->ertm_config,
1291         connection_controller->browsing_connection->ertm_buffer,
1292         connection_controller->browsing_connection->ertm_buffer_size);
1293     return ERROR_CODE_SUCCESS;
1294 }
1295 
1296 
1297 uint8_t avrcp_browsing_decline_incoming_connection(uint16_t avrcp_browsing_cid){
1298     avrcp_connection_t * connection_controller = get_avrcp_connection_for_browsing_cid_for_role(AVRCP_CONTROLLER, avrcp_browsing_cid);
1299     if (!connection_controller){
1300         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1301     }
1302     avrcp_connection_t * connection_target = get_avrcp_connection_for_browsing_cid_for_role(AVRCP_TARGET, avrcp_browsing_cid);
1303     if (!connection_target){
1304         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1305     }
1306 
1307     if (!connection_controller->browsing_connection){
1308         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1309     }
1310     if (!connection_target->browsing_connection){
1311         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1312     }
1313 
1314     if (connection_controller->browsing_connection->state != AVCTP_CONNECTION_W4_ERTM_CONFIGURATION){
1315         return ERROR_CODE_COMMAND_DISALLOWED;
1316     }
1317 
1318     l2cap_decline_connection(connection_controller->browsing_connection->l2cap_browsing_cid);
1319 
1320     avrcp_browsing_finalize_connection(connection_controller);
1321     avrcp_browsing_finalize_connection(connection_target);
1322     return ERROR_CODE_SUCCESS;
1323 }
1324 
1325 uint8_t avrcp_browsing_disconnect(uint16_t avrcp_browsing_cid){
1326     avrcp_connection_t * connection_controller = get_avrcp_connection_for_browsing_cid_for_role(AVRCP_CONTROLLER, avrcp_browsing_cid);
1327     if (!connection_controller){
1328         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1329     }
1330     avrcp_connection_t * connection_target = get_avrcp_connection_for_browsing_cid_for_role(AVRCP_TARGET, avrcp_browsing_cid);
1331     if (!connection_target){
1332         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1333     }
1334 
1335     if (!connection_controller->browsing_connection){
1336         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1337     }
1338     if (!connection_target->browsing_connection){
1339         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1340     }
1341 
1342     l2cap_disconnect(connection_controller->browsing_connection->l2cap_browsing_cid, 0);
1343     return ERROR_CODE_SUCCESS;
1344 }
1345 
1346 void avrcp_browsing_register_controller_packet_handler(btstack_packet_handler_t callback){
1347     avrcp_browsing_controller_packet_handler = callback;
1348 }
1349 
1350 void avrcp_browsing_register_target_packet_handler(btstack_packet_handler_t callback){
1351     avrcp_browsing_target_packet_handler = callback;
1352 }
1353 
1354 void avrcp_browsing_register_packet_handler(btstack_packet_handler_t callback){
1355     btstack_assert(callback != NULL);
1356     avrcp_browsing_callback = callback;
1357 }