xref: /btstack/src/classic/avrcp.c (revision cee0e5b6352919f0a1f00d4673e08193b3caceec)
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 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
54 
55 static const char * default_avrcp_controller_service_name = "BTstack AVRCP Controller Service";
56 static const char * default_avrcp_controller_service_provider_name = "BTstack AVRCP Controller Service Provider";
57 static const char * default_avrcp_target_service_name = "BTstack AVRCP Target Service";
58 static const char * default_avrcp_target_service_provider_name = "BTstack AVRCP Target Service Provider";
59 
60 static uint16_t  avrcp_cid_counter = 0;
61 
62 static avrcp_context_t * sdp_query_context;
63 
64 avrcp_context_t avrcp_controller_context;
65 avrcp_context_t avrcp_target_context;
66 
67 static btstack_packet_handler_t avrcp_callback;
68 
69 static uint8_t   attribute_value[45];
70 static const unsigned int attribute_value_buffer_size = sizeof(attribute_value);
71 
72 static btstack_linked_list_t connections;
73 static btstack_packet_handler_t avrcp_controller_packet_handler;
74 static btstack_packet_handler_t avrcp_target_packet_handler;
75 static int l2cap_service_registered = 0;
76 
77 static const char * avrcp_subunit_type_name[] = {
78     "MONITOR", "AUDIO", "PRINTER", "DISC", "TAPE_RECORDER_PLAYER", "TUNER",
79     "CA", "CAMERA", "RESERVED", "PANEL", "BULLETIN_BOARD", "CAMERA_STORAGE",
80     "VENDOR_UNIQUE", "RESERVED_FOR_ALL_SUBUNIT_TYPES",
81     "EXTENDED_TO_NEXT_BYTE", "UNIT", "ERROR"
82 };
83 
84 const char * avrcp_subunit2str(uint16_t index){
85     if (index <= 11) return avrcp_subunit_type_name[index];
86     if ((index >= 0x1C) && (index <= 0x1F)) return avrcp_subunit_type_name[index - 0x10];
87     return avrcp_subunit_type_name[16];
88 }
89 
90 static const char * avrcp_event_name[] = {
91     "ERROR", "PLAYBACK_STATUS_CHANGED",
92     "TRACK_CHANGED", "TRACK_REACHED_END", "TRACK_REACHED_START",
93     "PLAYBACK_POS_CHANGED", "BATT_STATUS_CHANGED", "SYSTEM_STATUS_CHANGED",
94     "PLAYER_APPLICATION_SETTING_CHANGED", "NOW_PLAYING_CONTENT_CHANGED",
95     "AVAILABLE_PLAYERS_CHANGED", "ADDRESSED_PLAYER_CHANGED", "UIDS_CHANGED", "VOLUME_CHANGED"
96 };
97 const char * avrcp_event2str(uint16_t index){
98     if (index <= 0x0d) return avrcp_event_name[index];
99     return avrcp_event_name[0];
100 }
101 
102 static const char * avrcp_operation_name[] = {
103     "NOT SUPPORTED", // 0x3B
104     "SKIP", "NOT SUPPORTED", "NOT SUPPORTED", "NOT SUPPORTED", "NOT SUPPORTED",
105     "VOLUME_UP", "VOLUME_DOWN", "MUTE", "PLAY", "STOP", "PAUSE", "NOT SUPPORTED",
106     "REWIND", "FAST_FORWARD", "NOT SUPPORTED", "FORWARD", "BACKWARD" // 0x4C
107 };
108 const char * avrcp_operation2str(uint8_t index){
109     if ((index >= 0x3B) && (index <= 0x4C)) return avrcp_operation_name[index - 0x3B];
110     return avrcp_operation_name[0];
111 }
112 
113 static const char * avrcp_media_attribute_id_name[] = {
114     "NONE", "TITLE", "ARTIST", "ALBUM", "TRACK", "TOTAL TRACKS", "GENRE", "SONG LENGTH"
115 };
116 const char * avrcp_attribute2str(uint8_t index){
117     if ((index >= 1) && (index <= 7)) return avrcp_media_attribute_id_name[index];
118     return avrcp_media_attribute_id_name[0];
119 }
120 
121 static const char * avrcp_play_status_name[] = {
122     "STOPPED", "PLAYING", "PAUSED", "FORWARD SEEK", "REVERSE SEEK",
123     "ERROR" // 0xFF
124 };
125 const char * avrcp_play_status2str(uint8_t index){
126     if ((index >= 1) && (index <= 4)) return avrcp_play_status_name[index];
127     return avrcp_play_status_name[5];
128 }
129 
130 static const char * avrcp_ctype_name[] = {
131     "CONTROL",
132     "STATUS",
133     "SPECIFIC_INQUIRY",
134     "NOTIFY",
135     "GENERAL_INQUIRY",
136     "RESERVED5",
137     "RESERVED6",
138     "RESERVED7",
139     "NOT IMPLEMENTED IN REMOTE",
140     "ACCEPTED BY REMOTE",
141     "REJECTED BY REMOTE",
142     "IN_TRANSITION",
143     "IMPLEMENTED_STABLE",
144     "CHANGED_STABLE",
145     "RESERVED",
146     "INTERIM"
147 };
148 const char * avrcp_ctype2str(uint8_t index){
149     if (index < sizeof(avrcp_ctype_name)){
150         return avrcp_ctype_name[index];
151     }
152     return "NONE";
153 }
154 
155 static const char * avrcp_shuffle_mode_name[] = {
156     "SHUFFLE OFF",
157     "SHUFFLE ALL TRACKS",
158     "SHUFFLE GROUP"
159 };
160 
161 const char * avrcp_shuffle2str(uint8_t index){
162     if ((index >= 1) && (index <= 3)) return avrcp_shuffle_mode_name[index-1];
163     return "NONE";
164 }
165 
166 static const char * avrcp_repeat_mode_name[] = {
167     "REPEAT OFF",
168     "REPEAT SINGLE TRACK",
169     "REPEAT ALL TRACKS",
170     "REPEAT GROUP"
171 };
172 
173 const char * avrcp_repeat2str(uint8_t index){
174     if ((index >= 1) && (index <= 4)) return avrcp_repeat_mode_name[index-1];
175     return "NONE";
176 }
177 
178 uint8_t avrcp_cmd_opcode(uint8_t *packet, uint16_t size){
179     uint8_t cmd_opcode_index = 5;
180     if (cmd_opcode_index > size) return AVRCP_CMD_OPCODE_UNDEFINED;
181     return packet[cmd_opcode_index];
182 }
183 
184 void avrcp_create_sdp_record(uint8_t controller, uint8_t * service, uint32_t service_record_handle, uint8_t browsing, uint16_t supported_features,
185     const char * service_name, const char * service_provider_name){
186     uint8_t* attribute;
187     de_create_sequence(service);
188 
189     // 0x0000 "Service Record Handle"
190     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
191     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
192 
193     // 0x0001 "Service Class ID List"
194     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
195     attribute = de_push_sequence(service);
196     {
197         if (controller){
198             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL);
199             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_CONTROLLER);
200         } else {
201             de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_TARGET);
202         }
203     }
204     de_pop_sequence(service, attribute);
205 
206     // 0x0004 "Protocol Descriptor List"
207     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
208     attribute = de_push_sequence(service);
209     {
210         uint8_t* l2cpProtocol = de_push_sequence(attribute);
211         {
212             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
213             de_add_number(l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PSM_AVCTP);
214         }
215         de_pop_sequence(attribute, l2cpProtocol);
216 
217         uint8_t* avctpProtocol = de_push_sequence(attribute);
218         {
219             de_add_number(avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // avctpProtocol_service
220             de_add_number(avctpProtocol,  DE_UINT, DE_SIZE_16,  0x0103);    // version
221         }
222         de_pop_sequence(attribute, avctpProtocol);
223     }
224     de_pop_sequence(service, attribute);
225 
226     // 0x0005 "Public Browse Group"
227     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
228     attribute = de_push_sequence(service);
229     {
230         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
231     }
232     de_pop_sequence(service, attribute);
233 
234     // 0x0009 "Bluetooth Profile Descriptor List"
235     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
236     attribute = de_push_sequence(service);
237     {
238         uint8_t *avrcProfile = de_push_sequence(attribute);
239         {
240             de_add_number(avrcProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL);
241             de_add_number(avrcProfile,  DE_UINT, DE_SIZE_16, 0x0105);
242         }
243         de_pop_sequence(attribute, avrcProfile);
244     }
245     de_pop_sequence(service, attribute);
246 
247     // 0x000d "Additional Bluetooth Profile Descriptor List"
248     if (browsing){
249         de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS);
250         attribute = de_push_sequence(service);
251         {
252             uint8_t * des = de_push_sequence(attribute);
253             {
254                 uint8_t* browsing_l2cpProtocol = de_push_sequence(des);
255                 {
256                     de_add_number(browsing_l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
257                     de_add_number(browsing_l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PSM_AVCTP_BROWSING);
258                 }
259                 de_pop_sequence(des, browsing_l2cpProtocol);
260 
261                 uint8_t* browsing_avctpProtocol = de_push_sequence(des);
262                 {
263                     de_add_number(browsing_avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // browsing_avctpProtocol_service
264                     de_add_number(browsing_avctpProtocol,  DE_UINT, DE_SIZE_16,  0x0103);    // version
265                 }
266                 de_pop_sequence(des, browsing_avctpProtocol);
267             }
268             de_pop_sequence(attribute, des);
269         }
270         de_pop_sequence(service, attribute);
271     }
272 
273 
274     // 0x0100 "Service Name"
275     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
276     if (service_name){
277         de_add_data(service,  DE_STRING, strlen(service_name), (uint8_t *) service_name);
278     } else {
279         if (controller){
280             de_add_data(service,  DE_STRING, strlen(default_avrcp_controller_service_name), (uint8_t *) default_avrcp_controller_service_name);
281         } else {
282             de_add_data(service,  DE_STRING, strlen(default_avrcp_target_service_name), (uint8_t *) default_avrcp_target_service_name);
283         }
284     }
285 
286     // 0x0100 "Provider Name"
287     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0102);
288     if (service_provider_name){
289         de_add_data(service,  DE_STRING, strlen(service_provider_name), (uint8_t *) service_provider_name);
290     } else {
291         if (controller){
292             de_add_data(service,  DE_STRING, strlen(default_avrcp_controller_service_provider_name), (uint8_t *) default_avrcp_controller_service_provider_name);
293         } else {
294             de_add_data(service,  DE_STRING, strlen(default_avrcp_target_service_provider_name), (uint8_t *) default_avrcp_target_service_provider_name);
295         }
296     }
297 
298     // 0x0311 "Supported Features"
299     de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);
300     de_add_number(service, DE_UINT, DE_SIZE_16, supported_features);
301 }
302 
303 avrcp_connection_t * get_avrcp_connection_for_bd_addr_for_role(avrcp_role_t role, bd_addr_t addr){
304     btstack_linked_list_iterator_t it;
305     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
306     while (btstack_linked_list_iterator_has_next(&it)){
307         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
308         if (connection->role != role) continue;
309         if (memcmp(addr, connection->remote_addr, 6) != 0) continue;
310         return connection;
311     }
312     return NULL;
313 }
314 
315 avrcp_connection_t * get_avrcp_connection_for_l2cap_signaling_cid_for_role(avrcp_role_t role, uint16_t l2cap_cid){
316     btstack_linked_list_iterator_t it;
317     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
318     while (btstack_linked_list_iterator_has_next(&it)){
319         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
320         if (connection->role != role) continue;
321         if (connection->l2cap_signaling_cid != l2cap_cid) continue;
322         return connection;
323     }
324     return NULL;
325 }
326 
327 avrcp_connection_t * get_avrcp_connection_for_avrcp_cid_for_role(avrcp_role_t role, uint16_t avrcp_cid){
328     btstack_linked_list_iterator_t it;
329     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
330     while (btstack_linked_list_iterator_has_next(&it)){
331         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
332         if (connection->role != role) continue;
333         if (connection->avrcp_cid != avrcp_cid) continue;
334         return connection;
335     }
336     return NULL;
337 }
338 
339 avrcp_connection_t * get_avrcp_connection_for_browsing_cid_for_role(avrcp_role_t role, uint16_t browsing_cid){
340     btstack_linked_list_iterator_t it;
341     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
342     while (btstack_linked_list_iterator_has_next(&it)){
343         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
344         if (connection->role != role) continue;
345         if (connection->avrcp_browsing_cid != browsing_cid) continue;
346         return connection;
347     }
348     return NULL;
349 }
350 
351 avrcp_connection_t * get_avrcp_connection_for_browsing_l2cap_cid_for_role(avrcp_role_t role, uint16_t browsing_l2cap_cid){
352     btstack_linked_list_iterator_t it;
353     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
354     while (btstack_linked_list_iterator_has_next(&it)){
355         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
356         if (connection->role != role) continue;
357         if (connection->browsing_connection &&  (connection->browsing_connection->l2cap_browsing_cid != browsing_l2cap_cid)) continue;
358         return connection;
359     }
360     return NULL;
361 }
362 
363 avrcp_browsing_connection_t * get_avrcp_browsing_connection_for_l2cap_cid_for_role(avrcp_role_t role, uint16_t l2cap_cid){
364     btstack_linked_list_iterator_t it;
365     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &connections);
366     while (btstack_linked_list_iterator_has_next(&it)){
367         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
368         if (connection->role != role) continue;
369         if (connection->browsing_connection && (connection->browsing_connection->l2cap_browsing_cid != l2cap_cid)) continue;
370         return connection->browsing_connection;
371     }
372     return NULL;
373 }
374 
375 static btstack_packet_handler_t avrcp_packet_handler_for_role(avrcp_role_t role){
376     switch (role){
377         case AVRCP_CONTROLLER:
378             return avrcp_controller_packet_handler;
379         case AVRCP_TARGET:
380             return avrcp_target_packet_handler;
381     }
382     return NULL;
383 }
384 
385 void avrcp_request_can_send_now(avrcp_connection_t * connection, uint16_t l2cap_cid){
386     // printf("AVRCP: avrcp_request_can_send_now, role %d\n", connection->role);
387     connection->wait_to_send = 1;
388     l2cap_request_can_send_now_event(l2cap_cid);
389 }
390 
391 
392 uint16_t avrcp_get_next_cid(avrcp_role_t role){
393     do {
394         if (avrcp_cid_counter == 0xffff) {
395             avrcp_cid_counter = 1;
396         } else {
397             avrcp_cid_counter++;
398         }
399     } while (get_avrcp_connection_for_avrcp_cid_for_role(role, avrcp_cid_counter) !=  NULL) ;
400     return avrcp_cid_counter;
401 }
402 
403 
404 static avrcp_connection_t * avrcp_create_connection(avrcp_role_t role, bd_addr_t remote_addr){
405     avrcp_connection_t * connection = btstack_memory_avrcp_connection_get();
406     if (!connection){
407         log_error("Not enough memory to create connection for role %d", role);
408         return NULL;
409     }
410 
411     connection->state = AVCTP_CONNECTION_IDLE;
412     connection->role = role;
413     connection->transaction_label = 0xFF;
414     connection->max_num_fragments = 0xFF;
415     log_info("avrcp_create_connection, role %d, avrcp cid 0x%02x", role, connection->avrcp_cid);
416     (void)memcpy(connection->remote_addr, remote_addr, 6);
417     btstack_linked_list_add(&connections, (btstack_linked_item_t *) connection);
418     return connection;
419 }
420 
421 static void avrcp_finalize_connection(avrcp_connection_t * connection){
422     btstack_linked_list_remove(&connections, (btstack_linked_item_t*) connection);
423     btstack_memory_avrcp_connection_free(connection);
424 }
425 
426 static void avrcp_emit_connection_established(uint16_t avrcp_cid, bd_addr_t addr, uint8_t status){
427     btstack_assert(avrcp_callback != NULL);
428 
429     uint8_t event[12];
430     int pos = 0;
431     event[pos++] = HCI_EVENT_AVRCP_META;
432     event[pos++] = sizeof(event) - 2;
433     event[pos++] = AVRCP_SUBEVENT_CONNECTION_ESTABLISHED;
434     event[pos++] = status;
435     reverse_bd_addr(addr,&event[pos]);
436     pos += 6;
437     little_endian_store_16(event, pos, avrcp_cid);
438     pos += 2;
439     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
440 }
441 
442 static void avrcp_emit_connection_closed(uint16_t avrcp_cid){
443     btstack_assert(avrcp_callback != NULL);
444 
445     uint8_t event[5];
446     int pos = 0;
447     event[pos++] = HCI_EVENT_AVRCP_META;
448     event[pos++] = sizeof(event) - 2;
449     event[pos++] = AVRCP_SUBEVENT_CONNECTION_RELEASED;
450     little_endian_store_16(event, pos, avrcp_cid);
451     pos += 2;
452     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
453 }
454 
455 static void avrcp_handle_sdp_client_query_attribute_value(uint8_t *packet){
456     des_iterator_t des_list_it;
457     des_iterator_t prot_it;
458 
459     // Handle new SDP record
460     if (sdp_event_query_attribute_byte_get_record_id(packet) != sdp_query_context->record_id) {
461         sdp_query_context->record_id = sdp_event_query_attribute_byte_get_record_id(packet);
462         sdp_query_context->parse_sdp_record = 0;
463         // log_info("SDP Record: Nr: %d", record_id);
464     }
465 
466     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= attribute_value_buffer_size) {
467         attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
468 
469         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
470             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
471                 case BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST:
472                     if (de_get_element_type(attribute_value) != DE_DES) break;
473                     for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
474                         uint8_t * element = des_iterator_get_element(&des_list_it);
475                         if (de_get_element_type(element) != DE_UUID) continue;
476                         uint32_t uuid = de_get_uuid32(element);
477                         switch (uuid){
478                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_TARGET:
479                                 if (sdp_query_context->role == AVRCP_CONTROLLER) {
480                                     sdp_query_context->parse_sdp_record = 1;
481                                     break;
482                                 }
483                                 break;
484                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL:
485                             case BLUETOOTH_SERVICE_CLASS_AV_REMOTE_CONTROL_CONTROLLER:
486                                 if (sdp_query_context->role == AVRCP_TARGET) {
487                                     sdp_query_context->parse_sdp_record = 1;
488                                     break;
489                                 }
490                                 break;
491                             default:
492                                 break;
493                         }
494                     }
495                     break;
496 
497                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST: {
498                     if (!sdp_query_context->parse_sdp_record) break;
499                     // log_info("SDP Attribute: 0x%04x", sdp_event_query_attribute_byte_get_attribute_id(packet));
500                     for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
501                         uint8_t       *des_element;
502                         uint8_t       *element;
503                         uint32_t       uuid;
504 
505                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
506 
507                         des_element = des_iterator_get_element(&des_list_it);
508                         des_iterator_init(&prot_it, des_element);
509                         element = des_iterator_get_element(&prot_it);
510 
511                         if (de_get_element_type(element) != DE_UUID) continue;
512 
513                         uuid = de_get_uuid32(element);
514                         des_iterator_next(&prot_it);
515                         switch (uuid){
516                             case BLUETOOTH_PROTOCOL_L2CAP:
517                                 if (!des_iterator_has_more(&prot_it)) continue;
518                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_query_context->avrcp_l2cap_psm);
519                                 break;
520                             case BLUETOOTH_PROTOCOL_AVCTP:
521                                 if (!des_iterator_has_more(&prot_it)) continue;
522                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_query_context->avrcp_version);
523                                 break;
524                             default:
525                                 break;
526                         }
527                     }
528                 }
529                     break;
530                 case BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS: {
531                     // log_info("SDP Attribute: 0x%04x", sdp_event_query_attribute_byte_get_attribute_id(packet));
532                     if (!sdp_query_context->parse_sdp_record) break;
533                     if (de_get_element_type(attribute_value) != DE_DES) break;
534 
535                     des_iterator_t des_list_0_it;
536                     uint8_t       *element_0;
537 
538                     des_iterator_init(&des_list_0_it, attribute_value);
539                     element_0 = des_iterator_get_element(&des_list_0_it);
540 
541                     for (des_iterator_init(&des_list_it, element_0); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
542                         uint8_t       *des_element;
543                         uint8_t       *element;
544                         uint32_t       uuid;
545 
546                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
547 
548                         des_element = des_iterator_get_element(&des_list_it);
549                         des_iterator_init(&prot_it, des_element);
550                         element = des_iterator_get_element(&prot_it);
551 
552                         if (de_get_element_type(element) != DE_UUID) continue;
553 
554                         uuid = de_get_uuid32(element);
555                         des_iterator_next(&prot_it);
556                         switch (uuid){
557                             case BLUETOOTH_PROTOCOL_L2CAP:
558                                 if (!des_iterator_has_more(&prot_it)) continue;
559                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_query_context->browsing_l2cap_psm);
560                                 break;
561                             case BLUETOOTH_PROTOCOL_AVCTP:
562                                 if (!des_iterator_has_more(&prot_it)) continue;
563                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_query_context->browsing_version);
564                                 break;
565                             default:
566                                 break;
567                         }
568                     }
569                 }
570                     break;
571                 default:
572                     break;
573             }
574         }
575     } else {
576         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));
577     }
578 }
579 
580 static void avrcp_handle_sdp_query_failed(avrcp_connection_t * connection, uint8_t status){
581     if (connection == NULL) return;
582     log_info("AVRCP: SDP query failed with status 0x%02x.", status);
583     avrcp_emit_connection_established(connection->avrcp_cid, connection->remote_addr, status);
584     avrcp_finalize_connection(connection);
585 }
586 
587 static void avrcp_handle_sdp_query_succeeded(avrcp_connection_t * connection, uint16_t browsing_l2cap_psm, uint16_t browsing_version){
588     if (connection == NULL) return;
589     connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
590     connection->browsing_version = browsing_version;
591     connection->browsing_l2cap_psm = browsing_l2cap_psm;
592 }
593 
594 void avrcp_handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
595     UNUSED(packet_type);
596     UNUSED(channel);
597     UNUSED(size);
598 
599     avrcp_connection_t * avrcp_target_connection = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, sdp_query_context->remote_addr);
600     avrcp_connection_t * avrcp_controller_connection = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, sdp_query_context->remote_addr);
601 
602     uint8_t status;
603 
604     switch (hci_event_packet_get_type(packet)){
605         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
606             avrcp_handle_sdp_client_query_attribute_value(packet);
607             break;
608 
609         case SDP_EVENT_QUERY_COMPLETE:
610             status = sdp_event_query_complete_get_status(packet);
611 
612             if (status != ERROR_CODE_SUCCESS){
613                 avrcp_handle_sdp_query_failed(avrcp_controller_connection, status);
614                 avrcp_handle_sdp_query_failed(avrcp_target_connection, status);
615                 break;
616             }
617 
618             if (!sdp_query_context->avrcp_l2cap_psm){
619                 avrcp_handle_sdp_query_failed(avrcp_controller_connection, SDP_SERVICE_NOT_FOUND);
620                 avrcp_handle_sdp_query_failed(avrcp_target_connection, SDP_SERVICE_NOT_FOUND);
621                 break;
622             }
623 
624             avrcp_handle_sdp_query_succeeded(avrcp_controller_connection, sdp_query_context->browsing_l2cap_psm, sdp_query_context->browsing_version);
625             avrcp_handle_sdp_query_succeeded(avrcp_target_connection, sdp_query_context->browsing_l2cap_psm, sdp_query_context->browsing_version);
626 
627             l2cap_create_channel(&avrcp_packet_handler, sdp_query_context->remote_addr, sdp_query_context->avrcp_l2cap_psm, l2cap_max_mtu(), NULL);
628             break;
629 
630         default:
631             break;
632 
633     }
634 }
635 
636 
637 static int avrcp_handle_incoming_connection_for_role(avrcp_role_t role, bd_addr_t event_addr, uint16_t local_cid, uint16_t avrcp_cid){
638     if (!avrcp_packet_handler_for_role(role)) {
639         // printf("AVRCP: avrcp_handle_incoming_connection_for_role %d, PH not defined\n", role);
640         return 0;
641     }
642 
643     avrcp_connection_t * connection = avrcp_create_connection(role, event_addr);
644 
645     if (!connection) {
646         // printf("AVRCP: avrcp_handle_incoming_connection_for_role %d, no connection created\n", role);
647         return 0 ;
648     }
649 
650     // printf("AVRCP: AVCTP_CONNECTION_W4_L2CAP_CONNECTED, role %d\n", role);
651     connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
652     connection->l2cap_signaling_cid = local_cid;
653     connection->avrcp_cid = avrcp_cid;
654     return 1;
655 }
656 
657 static void avrcp_handle_open_connection_for_role( avrcp_connection_t * connection, uint16_t local_cid, uint16_t l2cap_mtu){
658     connection->l2cap_signaling_cid = local_cid;
659     connection->l2cap_mtu = l2cap_mtu;
660     connection->incoming_declined = false;
661     connection->song_length_ms = 0xFFFFFFFF;
662     connection->song_position_ms = 0xFFFFFFFF;
663     connection->playback_status = AVRCP_PLAYBACK_STATUS_ERROR;
664     connection->state = AVCTP_CONNECTION_OPENED;
665 
666     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);
667 }
668 
669 static avrcp_role_t avrcp_role_from_transport_header(uint8_t transport_header){
670     avrcp_frame_type_t frame_type = (avrcp_frame_type_t)((transport_header & 0x02) >> 1);
671     switch (frame_type){
672         case AVRCP_COMMAND_FRAME:
673             return AVRCP_TARGET;
674         default: // AVRCP_RESPONSE_FRAME - make compiler happy
675             return AVRCP_CONTROLLER;
676     }
677 }
678 
679 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
680     UNUSED(channel);
681     UNUSED(size);
682     bd_addr_t event_addr;
683     uint16_t local_cid;
684     uint16_t l2cap_mtu;
685     uint8_t  status;
686     avrcp_role_t role;
687     btstack_packet_handler_t packet_handler;
688     uint8_t status_target;
689     uint8_t status_controller;
690     bool decline_connection;
691     bool outoing_active;
692 
693     avrcp_connection_t * connection_controller;
694     avrcp_connection_t * connection_target;
695 
696     switch (packet_type) {
697         case L2CAP_DATA_PACKET:
698             role = avrcp_role_from_transport_header(packet[0]);
699             packet_handler = avrcp_packet_handler_for_role(role);
700             if (!packet_handler) return;
701 
702             (*packet_handler)(packet_type, channel, packet, size);
703             break;
704 
705         case HCI_EVENT_PACKET:
706             switch (hci_event_packet_get_type(packet)) {
707 
708                 case L2CAP_EVENT_INCOMING_CONNECTION:
709                     l2cap_event_incoming_connection_get_address(packet, event_addr);
710                     local_cid = l2cap_event_incoming_connection_get_local_cid(packet);
711                     outoing_active = false;
712 
713                     connection_target = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, event_addr);
714                     if (connection_target != NULL){
715                         outoing_active = true;
716                         connection_target->incoming_declined = true;
717                     }
718 
719                     connection_controller = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
720                     if (connection_controller != NULL){
721                         outoing_active = true;
722                         connection_controller->incoming_declined = true;
723                     }
724 
725                     decline_connection = outoing_active;
726                     if (outoing_active == false){
727                         // create two connection objects (both)
728                         uint16_t avrcp_cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
729 
730                         status_target = avrcp_handle_incoming_connection_for_role(AVRCP_TARGET, event_addr, local_cid, avrcp_cid);
731                         status_controller = avrcp_handle_incoming_connection_for_role(AVRCP_CONTROLLER, event_addr, local_cid, avrcp_cid);
732                         if (!status_target && !status_controller) {
733                             decline_connection = true;
734                         }
735                     }
736                     if (decline_connection){
737                         l2cap_decline_connection(local_cid);
738                     } else {
739                         log_info("AVRCP: L2CAP_EVENT_INCOMING_CONNECTION avrcp_cid 0x%02x", local_cid);
740                         l2cap_accept_connection(local_cid);
741                     }
742                     break;
743 
744                 case L2CAP_EVENT_CHANNEL_OPENED:
745                     // printf("AVRCP: L2CAP_EVENT_CHANNEL_OPENED \n");
746                     l2cap_event_channel_opened_get_address(packet, event_addr);
747                     status = l2cap_event_channel_opened_get_status(packet);
748                     local_cid = l2cap_event_channel_opened_get_local_cid(packet);
749                     l2cap_mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
750 
751                     connection_controller = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, event_addr);
752                     connection_target = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, event_addr);
753                     if ((connection_controller == NULL) || (connection_target == NULL)) {
754                         break;
755                     }
756 
757                     if (status != ERROR_CODE_SUCCESS){
758                         log_info("L2CAP connection to connection %s failed. status code 0x%02x", bd_addr_to_str(event_addr), status);
759                         avrcp_emit_connection_established(connection_controller->avrcp_cid, event_addr, status);
760                         avrcp_finalize_connection(connection_controller);
761                         avrcp_finalize_connection(connection_target);
762                         return;
763                     }
764 
765                     avrcp_handle_open_connection_for_role(connection_target, local_cid, l2cap_mtu);
766                     avrcp_handle_open_connection_for_role(connection_controller, local_cid, l2cap_mtu);
767 
768                     avrcp_emit_connection_established(connection_controller->avrcp_cid, event_addr, status);
769                     break;
770 
771                 case L2CAP_EVENT_CHANNEL_CLOSED:
772                     local_cid = l2cap_event_channel_closed_get_local_cid(packet);
773 
774                     connection_controller = get_avrcp_connection_for_l2cap_signaling_cid_for_role(AVRCP_CONTROLLER, local_cid);
775                     connection_target = get_avrcp_connection_for_l2cap_signaling_cid_for_role(AVRCP_TARGET, local_cid);
776                     if ((connection_controller == NULL) || (connection_target == NULL)) {
777                         break;
778                     }
779                     avrcp_emit_connection_closed(connection_controller->avrcp_cid);
780                     avrcp_finalize_connection(connection_controller);
781 
782                     avrcp_emit_connection_closed(connection_target->avrcp_cid);
783                     avrcp_finalize_connection(connection_target);
784                     break;
785 
786                 case L2CAP_EVENT_CAN_SEND_NOW:
787                     local_cid = l2cap_event_can_send_now_get_local_cid(packet);
788                     connection_target = get_avrcp_connection_for_l2cap_signaling_cid_for_role(AVRCP_TARGET, local_cid);
789                     if (connection_target && connection_target->wait_to_send){
790                         // printf("AVRCP: L2CAP_EVENT_CAN_SEND_NOW target\n");
791                         connection_target->wait_to_send = 0;
792                         (*avrcp_target_packet_handler)(HCI_EVENT_PACKET, channel, packet, size);
793                         break;
794                     }
795 
796                     connection_controller = get_avrcp_connection_for_l2cap_signaling_cid_for_role(AVRCP_CONTROLLER, local_cid);
797                     if (connection_controller && connection_controller->wait_to_send){
798                         // printf("AVRCP: L2CAP_EVENT_CAN_SEND_NOW controller\n");
799                         connection_controller->wait_to_send = 0;
800                         (*avrcp_controller_packet_handler)(HCI_EVENT_PACKET, channel, packet, size);
801                         break;
802                     }
803                     break;
804 
805                 default:
806                     break;
807             }
808             break;
809         default:
810             break;
811     }
812 }
813 
814 uint8_t avrcp_disconnect(uint16_t avrcp_cid){
815     avrcp_connection_t * connection_controller = get_avrcp_connection_for_avrcp_cid_for_role(AVRCP_CONTROLLER, avrcp_cid);
816     if (!connection_controller){
817         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
818     }
819     avrcp_connection_t * connection_target = get_avrcp_connection_for_avrcp_cid_for_role(AVRCP_TARGET, avrcp_cid);
820     if (!connection_target){
821         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
822     }
823     if (connection_controller->browsing_connection){
824         l2cap_disconnect(connection_controller->browsing_connection->l2cap_browsing_cid, 0);
825     }
826     l2cap_disconnect(connection_controller->l2cap_signaling_cid, 0);
827     return ERROR_CODE_SUCCESS;
828 }
829 
830 uint8_t avrcp_connect(bd_addr_t remote_addr, uint16_t * avrcp_cid){
831     btstack_assert(avrcp_packet_handler_for_role(AVRCP_CONTROLLER) != NULL);
832     btstack_assert(avrcp_packet_handler_for_role(AVRCP_TARGET) != NULL);
833 
834     // TODO: implement delayed SDP query
835     if (sdp_client_ready() == 0){
836         return ERROR_CODE_COMMAND_DISALLOWED;
837     }
838 
839     avrcp_connection_t * connection_controller = get_avrcp_connection_for_bd_addr_for_role(AVRCP_CONTROLLER, remote_addr);
840     if (connection_controller){
841         return ERROR_CODE_COMMAND_DISALLOWED;
842     }
843     avrcp_connection_t * connection_target = get_avrcp_connection_for_bd_addr_for_role(AVRCP_TARGET, remote_addr);
844     if (connection_target){
845         return ERROR_CODE_COMMAND_DISALLOWED;
846     }
847 
848     uint16_t cid = avrcp_get_next_cid(AVRCP_CONTROLLER);
849 
850     connection_controller = avrcp_create_connection(AVRCP_CONTROLLER, remote_addr);
851     if (!connection_controller) return BTSTACK_MEMORY_ALLOC_FAILED;
852 
853     connection_target = avrcp_create_connection(AVRCP_TARGET, remote_addr);
854     if (!connection_target){
855         avrcp_finalize_connection(connection_controller);
856         return BTSTACK_MEMORY_ALLOC_FAILED;
857     }
858 
859     sdp_query_context = &avrcp_controller_context;
860 
861     if (avrcp_cid != NULL){
862         *avrcp_cid = cid;
863     }
864 
865     connection_controller->state = AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE;
866     connection_controller->avrcp_cid = cid;
867 
868     connection_target->state     = AVCTP_CONNECTION_W4_SDP_QUERY_COMPLETE;
869     connection_target->avrcp_cid = cid;
870 
871     sdp_query_context->avrcp_l2cap_psm = 0;
872     sdp_query_context->avrcp_version  = 0;
873     sdp_query_context->avrcp_cid = cid;
874     memcpy(sdp_query_context->remote_addr, remote_addr, 6);
875 
876     sdp_client_query_uuid16(&avrcp_handle_sdp_client_query_result, remote_addr, BLUETOOTH_PROTOCOL_AVCTP);
877     return ERROR_CODE_SUCCESS;
878 }
879 
880 void avrcp_init(void){
881     connections = NULL;
882     if (l2cap_service_registered) return;
883 
884     int status = l2cap_register_service(&avrcp_packet_handler, BLUETOOTH_PSM_AVCTP, 0xffff, gap_get_security_level());
885     if (status != ERROR_CODE_SUCCESS) return;
886     l2cap_service_registered = 1;
887 }
888 
889 void avrcp_register_controller_packet_handler(btstack_packet_handler_t callback){
890     avrcp_controller_packet_handler = callback;
891 }
892 
893 void avrcp_register_target_packet_handler(btstack_packet_handler_t callback){
894     avrcp_target_packet_handler = callback;
895 }
896 
897 void avrcp_register_packet_handler(btstack_packet_handler_t callback){
898     btstack_assert(callback != NULL);
899     avrcp_callback = callback;
900 }
901