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