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