xref: /btstack/src/classic/avdtp.c (revision 6d34f98e0c6a035be904a5ac00e86a7b4f285631)
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__ "avdtp.c"
39 
40 
41 #include <stdint.h>
42 #include <string.h>
43 
44 #include "bluetooth_psm.h"
45 #include "bluetooth_sdp.h"
46 #include "btstack_debug.h"
47 #include "btstack_event.h"
48 #include "btstack_memory.h"
49 #include "classic/avdtp.h"
50 #include "classic/avdtp_acceptor.h"
51 #include "classic/avdtp_initiator.h"
52 #include "classic/avdtp_util.h"
53 #include "classic/sdp_client.h"
54 #include "classic/sdp_util.h"
55 
56 btstack_linked_list_t stream_endpoints;
57 
58 static bool l2cap_registered;
59 
60 static btstack_packet_handler_t avdtp_source_callback;
61 static btstack_packet_handler_t avdtp_sink_callback;
62 static btstack_context_callback_registration_t avdtp_handle_sdp_client_query_request;
63 
64 static uint16_t sdp_query_context_avdtp_cid = 0;
65 
66 static uint16_t stream_endpoints_id_counter = 0;
67 
68 static btstack_linked_list_t connections;
69 static uint16_t transaction_id_counter = 0;
70 
71 static int record_id;
72 static uint8_t attribute_value[45];
73 static const unsigned int attribute_value_buffer_size = sizeof(attribute_value);
74 
75 static void (*avdtp_sink_handle_media_data)(uint8_t local_seid, uint8_t *packet, uint16_t size);
76 
77 static uint16_t avdtp_cid_counter = 0;
78 
79 static void avdtp_handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
80 
81 btstack_packet_handler_t
82 avdtp_packet_handler_for_stream_endpoint(const avdtp_stream_endpoint_t *stream_endpoint) {
83     return (stream_endpoint->sep.type == AVDTP_SOURCE) ? avdtp_source_callback : avdtp_sink_callback;
84 }
85 
86 void avdtp_emit_sink_and_source(uint8_t * packet, uint16_t size){
87     if (avdtp_source_callback != NULL){
88         (*avdtp_source_callback)(HCI_EVENT_PACKET, 0, packet, size);
89     }
90     if (avdtp_sink_callback != NULL){
91         (*avdtp_sink_callback)(HCI_EVENT_PACKET, 0, packet, size);
92     }
93 }
94 
95 void avdtp_emit_source(uint8_t * packet, uint16_t size){
96     if (avdtp_source_callback != NULL){
97         (*avdtp_source_callback)(HCI_EVENT_PACKET, 0, packet, size);
98     }
99 }
100 
101 btstack_linked_list_t * avdtp_get_stream_endpoints(void){
102     return &stream_endpoints;
103 }
104 
105 btstack_linked_list_t * avdtp_get_connections(void){
106     return &connections;
107 }
108 
109 static avdtp_connection_t * avdtp_get_connection_for_bd_addr(bd_addr_t addr){
110     btstack_linked_list_iterator_t it;
111     btstack_linked_list_iterator_init(&it, &connections);
112     while (btstack_linked_list_iterator_has_next(&it)){
113         avdtp_connection_t * connection = (avdtp_connection_t *)btstack_linked_list_iterator_next(&it);
114         if (memcmp(addr, connection->remote_addr, 6) != 0) continue;
115         return connection;
116     }
117     return NULL;
118 }
119 
120  avdtp_connection_t * avdtp_get_connection_for_avdtp_cid(uint16_t avdtp_cid){
121     btstack_linked_list_iterator_t it;
122     btstack_linked_list_iterator_init(&it, &connections);
123     while (btstack_linked_list_iterator_has_next(&it)){
124         avdtp_connection_t * connection = (avdtp_connection_t *)btstack_linked_list_iterator_next(&it);
125         if (connection->avdtp_cid != avdtp_cid) continue;
126         return connection;
127     }
128     return NULL;
129 }
130 
131 
132 avdtp_stream_endpoint_t * avdtp_get_stream_endpoint_for_seid(uint16_t seid){
133     btstack_linked_list_iterator_t it;
134     btstack_linked_list_iterator_init(&it, avdtp_get_stream_endpoints());
135     while (btstack_linked_list_iterator_has_next(&it)){
136         avdtp_stream_endpoint_t * stream_endpoint = (avdtp_stream_endpoint_t *)btstack_linked_list_iterator_next(&it);
137         if (stream_endpoint->sep.seid == seid){
138             return stream_endpoint;
139         }
140     }
141     return NULL;
142 }
143 
144 avdtp_stream_endpoint_t * avdtp_get_source_stream_endpoint_for_media_codec(avdtp_media_codec_type_t codec_type){
145     btstack_linked_list_iterator_t it;
146     btstack_linked_list_iterator_init(&it, avdtp_get_stream_endpoints());
147     while (btstack_linked_list_iterator_has_next(&it)){
148         avdtp_stream_endpoint_t * stream_endpoint = (avdtp_stream_endpoint_t *)btstack_linked_list_iterator_next(&it);
149         if (stream_endpoint->sep.type != AVDTP_SOURCE) continue;
150         if (stream_endpoint->sep.capabilities.media_codec.media_codec_type != codec_type) continue;
151         return stream_endpoint;
152     }
153     return NULL;
154 }
155 
156 
157 avdtp_connection_t * avdtp_get_connection_for_l2cap_signaling_cid(uint16_t l2cap_cid){
158     btstack_linked_list_iterator_t it;
159     btstack_linked_list_iterator_init(&it, &connections);
160     while (btstack_linked_list_iterator_has_next(&it)){
161         avdtp_connection_t * connection = (avdtp_connection_t *)btstack_linked_list_iterator_next(&it);
162         if (connection->l2cap_signaling_cid != l2cap_cid) continue;
163         return connection;
164     }
165     return NULL;
166 }
167 
168 static avdtp_stream_endpoint_t * avdtp_get_stream_endpoint_for_l2cap_cid(uint16_t l2cap_cid){
169     btstack_linked_list_iterator_t it;
170     btstack_linked_list_iterator_init(&it, avdtp_get_stream_endpoints());
171     while (btstack_linked_list_iterator_has_next(&it)){
172         avdtp_stream_endpoint_t * stream_endpoint = (avdtp_stream_endpoint_t *)btstack_linked_list_iterator_next(&it);
173         if (stream_endpoint->l2cap_media_cid == l2cap_cid){
174             return stream_endpoint;
175         }
176         if (stream_endpoint->l2cap_reporting_cid == l2cap_cid){
177             return stream_endpoint;
178         }
179         if (stream_endpoint->l2cap_recovery_cid == l2cap_cid){
180             return stream_endpoint;
181         }
182     }
183     return NULL;
184 }
185 
186 static avdtp_stream_endpoint_t * avdtp_get_stream_endpoint_for_signaling_cid(uint16_t l2cap_cid){
187     btstack_linked_list_iterator_t it;
188     btstack_linked_list_iterator_init(&it, avdtp_get_stream_endpoints());
189     while (btstack_linked_list_iterator_has_next(&it)){
190         avdtp_stream_endpoint_t * stream_endpoint = (avdtp_stream_endpoint_t *)btstack_linked_list_iterator_next(&it);
191         if (stream_endpoint->connection){
192             if (stream_endpoint->connection->l2cap_signaling_cid == l2cap_cid){
193                 return stream_endpoint;
194             }
195         }
196     }
197     return NULL;
198 }
199 
200 uint16_t avdtp_get_next_transaction_label(void){
201     transaction_id_counter++;
202     if (transaction_id_counter == 16){
203         transaction_id_counter = 1;
204     }
205     return transaction_id_counter;
206 }
207 
208 static avdtp_connection_t * avdtp_create_connection(bd_addr_t remote_addr, uint16_t cid){
209     avdtp_connection_t * connection = btstack_memory_avdtp_connection_get();
210     if (!connection){
211         log_error("Not enough memory to create connection");
212         return NULL;
213     }
214     connection->state = AVDTP_SIGNALING_CONNECTION_IDLE;
215     connection->initiator_transaction_label = avdtp_get_next_transaction_label();
216     connection->configuration_state = AVDTP_CONFIGURATION_STATE_IDLE;
217     connection->a2dp_source_discover_seps = false;
218     connection->avdtp_cid = cid;
219     (void)memcpy(connection->remote_addr, remote_addr, 6);
220 
221     btstack_linked_list_add(&connections, (btstack_linked_item_t *) connection);
222     return connection;
223 }
224 
225 static uint16_t avdtp_get_next_cid(void){
226     if (avdtp_cid_counter == 0xffff) {
227         avdtp_cid_counter = 1;
228     } else {
229         avdtp_cid_counter++;
230     }
231     return avdtp_cid_counter;
232 }
233 
234 static uint16_t avdtp_get_next_local_seid(void){
235     if (stream_endpoints_id_counter == 0xffff) {
236         stream_endpoints_id_counter = 1;
237     } else {
238         stream_endpoints_id_counter++;
239     }
240     return stream_endpoints_id_counter;
241 }
242 
243 static void avdtp_handle_start_sdp_client_query(void * context){
244     UNUSED(context);
245 
246     btstack_linked_list_iterator_t it;
247     btstack_linked_list_iterator_init(&it, &connections);
248     while (btstack_linked_list_iterator_has_next(&it)){
249         avdtp_connection_t * connection = (avdtp_connection_t *)btstack_linked_list_iterator_next(&it);
250 
251         switch (connection->state){
252             case AVDTP_SIGNALING_W2_SEND_SDP_QUERY_FOR_REMOTE_SOURCE:
253                 connection->state = AVDTP_SIGNALING_W4_SDP_QUERY_FOR_REMOTE_SOURCE_COMPLETE;
254                 break;
255             case AVDTP_SIGNALING_W2_SEND_SDP_QUERY_FOR_REMOTE_SINK:
256                 connection->state = AVDTP_SIGNALING_W4_SDP_QUERY_FOR_REMOTE_SINK_COMPLETE;
257                 break;
258             case AVDTP_SIGNALING_CONNECTION_OPENED:
259                 if (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_SEND_SDP_QUERY_THEN_GET_ALL_CAPABILITIES) continue;
260                 connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W4_SDP_QUERY_COMPLETE_THEN_GET_ALL_CAPABILITIES;
261                 break;
262             default:
263                 continue;
264         }
265         sdp_query_context_avdtp_cid = connection->avdtp_cid;
266         record_id = -1;
267         sdp_client_query_uuid16(&avdtp_handle_sdp_client_query_result, (uint8_t *) connection->remote_addr, BLUETOOTH_PROTOCOL_AVDTP);
268         return;
269     }
270 }
271 
272 uint8_t avdtp_connect(bd_addr_t remote, avdtp_role_t role, uint16_t * avdtp_cid){
273     avdtp_connection_t * connection = avdtp_get_connection_for_bd_addr(remote);
274     if (connection){
275         return ERROR_CODE_COMMAND_DISALLOWED;
276     }
277 
278     uint16_t cid = avdtp_get_next_cid();
279     if (avdtp_cid != NULL) {
280         *avdtp_cid = cid;
281     }
282 
283     connection = avdtp_create_connection(remote, cid);
284     if (!connection) return BTSTACK_MEMORY_ALLOC_FAILED;
285 
286     connection->avdtp_cid = cid;
287 
288     connection->avdtp_l2cap_psm = 0;
289     connection->avdtp_version  = 0;
290     connection->sink_supported = false;
291     connection->source_supported = false;
292 
293     switch (role){
294         case AVDTP_ROLE_SOURCE:
295             connection->state = AVDTP_SIGNALING_W2_SEND_SDP_QUERY_FOR_REMOTE_SINK;
296             break;
297         case AVDTP_ROLE_SINK:
298             connection->state = AVDTP_SIGNALING_W2_SEND_SDP_QUERY_FOR_REMOTE_SOURCE;
299             break;
300         default:
301             btstack_assert(false);
302             return ERROR_CODE_COMMAND_DISALLOWED;
303     }
304 
305     avdtp_handle_sdp_client_query_request.callback = &avdtp_handle_start_sdp_client_query;
306     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
307     (void) sdp_client_register_query_callback(&avdtp_handle_sdp_client_query_request);
308     return ERROR_CODE_SUCCESS;
309 }
310 
311 
312 void avdtp_register_sink_packet_handler(btstack_packet_handler_t callback){
313     btstack_assert(callback != NULL);
314     avdtp_sink_callback = callback;
315 }
316 
317 void avdtp_register_source_packet_handler(btstack_packet_handler_t callback){
318     btstack_assert(callback != NULL);
319     avdtp_source_callback = callback;
320 }
321 
322 void avdtp_register_media_transport_category(avdtp_stream_endpoint_t * stream_endpoint){
323     if (!stream_endpoint){
324         log_error("Stream endpoint with given seid is not registered.");
325         return;
326     }
327     uint16_t bitmap = store_bit16(stream_endpoint->sep.registered_service_categories, AVDTP_MEDIA_TRANSPORT, 1);
328     stream_endpoint->sep.registered_service_categories = bitmap;
329 }
330 
331 void avdtp_register_reporting_category(avdtp_stream_endpoint_t * stream_endpoint){
332     if (!stream_endpoint){
333         log_error("Stream endpoint with given seid is not registered.");
334         return;
335     }
336     uint16_t bitmap = store_bit16(stream_endpoint->sep.registered_service_categories, AVDTP_REPORTING, 1);
337     stream_endpoint->sep.registered_service_categories = bitmap;
338 }
339 
340 void avdtp_register_delay_reporting_category(avdtp_stream_endpoint_t * stream_endpoint){
341     if (!stream_endpoint){
342         log_error("Stream endpoint with given seid is not registered.");
343         return;
344     }
345     uint16_t bitmap = store_bit16(stream_endpoint->sep.registered_service_categories, AVDTP_DELAY_REPORTING, 1);
346     stream_endpoint->sep.registered_service_categories = bitmap;
347 }
348 
349 void avdtp_register_recovery_category(avdtp_stream_endpoint_t * stream_endpoint, uint8_t maximum_recovery_window_size, uint8_t maximum_number_media_packets){
350     if (!stream_endpoint){
351         log_error("Stream endpoint with given seid is not registered.");
352         return;
353     }
354     uint16_t bitmap = store_bit16(stream_endpoint->sep.registered_service_categories, AVDTP_RECOVERY, 1);
355     stream_endpoint->sep.registered_service_categories = bitmap;
356     stream_endpoint->sep.capabilities.recovery.recovery_type = 0x01; // 0x01 = RFC2733
357     stream_endpoint->sep.capabilities.recovery.maximum_recovery_window_size = maximum_recovery_window_size;
358     stream_endpoint->sep.capabilities.recovery.maximum_number_media_packets = maximum_number_media_packets;
359 }
360 
361 void avdtp_register_content_protection_category(avdtp_stream_endpoint_t * stream_endpoint, uint16_t cp_type, const uint8_t * cp_type_value, uint8_t cp_type_value_len){
362     if (!stream_endpoint){
363         log_error("Stream endpoint with given seid is not registered.");
364         return;
365     }
366     uint16_t bitmap = store_bit16(stream_endpoint->sep.registered_service_categories, AVDTP_CONTENT_PROTECTION, 1);
367     stream_endpoint->sep.registered_service_categories = bitmap;
368     stream_endpoint->sep.capabilities.content_protection.cp_type = cp_type;
369     (void)memcpy(stream_endpoint->sep.capabilities.content_protection.cp_type_value,
370                  cp_type_value,
371                  btstack_min(cp_type_value_len, AVDTP_MAX_CONTENT_PROTECTION_TYPE_VALUE_LEN));
372     stream_endpoint->sep.capabilities.content_protection.cp_type_value_len = btstack_min(cp_type_value_len, AVDTP_MAX_CONTENT_PROTECTION_TYPE_VALUE_LEN);
373 }
374 
375 void avdtp_register_header_compression_category(avdtp_stream_endpoint_t * stream_endpoint, uint8_t back_ch, uint8_t media, uint8_t recovery){
376     if (!stream_endpoint){
377         log_error("Stream endpoint with given seid is not registered.");
378         return;
379     }
380     uint16_t bitmap = store_bit16(stream_endpoint->sep.registered_service_categories, AVDTP_HEADER_COMPRESSION, 1);
381     stream_endpoint->sep.registered_service_categories = bitmap;
382     stream_endpoint->sep.capabilities.header_compression.back_ch = back_ch;
383     stream_endpoint->sep.capabilities.header_compression.media = media;
384     stream_endpoint->sep.capabilities.header_compression.recovery = recovery;
385 }
386 
387 void avdtp_register_media_codec_category(avdtp_stream_endpoint_t * stream_endpoint, avdtp_media_type_t media_type, avdtp_media_codec_type_t media_codec_type, uint8_t * media_codec_info, uint16_t media_codec_info_len){
388     if (!stream_endpoint){
389         log_error("Stream endpoint with given seid is not registered.");
390         return;
391     }
392     uint16_t bitmap = store_bit16(stream_endpoint->sep.registered_service_categories, AVDTP_MEDIA_CODEC, 1);
393     stream_endpoint->sep.registered_service_categories = bitmap;
394     stream_endpoint->sep.capabilities.media_codec.media_type = media_type;
395     stream_endpoint->sep.capabilities.media_codec.media_codec_type = media_codec_type;
396     stream_endpoint->sep.capabilities.media_codec.media_codec_information = media_codec_info;
397     stream_endpoint->sep.capabilities.media_codec.media_codec_information_len = media_codec_info_len;
398 }
399 
400 void avdtp_register_multiplexing_category(avdtp_stream_endpoint_t * stream_endpoint, uint8_t fragmentation){
401     if (!stream_endpoint){
402         log_error("Stream endpoint with given seid is not registered.");
403         return;
404     }
405     uint16_t bitmap = store_bit16(stream_endpoint->sep.registered_service_categories, AVDTP_MULTIPLEXING, 1);
406     stream_endpoint->sep.registered_service_categories = bitmap;
407     stream_endpoint->sep.capabilities.multiplexing_mode.fragmentation = fragmentation;
408 }
409 
410 void avdtp_register_media_handler(void (*callback)(uint8_t local_seid, uint8_t *packet, uint16_t size)){
411     avdtp_sink_handle_media_data = callback;
412 }
413 
414 /* START: tracking can send now requests per l2cap cid */
415 static void avdtp_handle_can_send_now(uint16_t l2cap_cid) {
416 
417 	log_debug("avdtp_packet_handler, L2CAP_EVENT_CAN_SEND_NOW l2cap_cid 0x%02x", l2cap_cid);
418 
419 	// get signaling connection for l2cap cid
420 	avdtp_connection_t * connection = avdtp_get_connection_for_l2cap_signaling_cid(l2cap_cid);
421 
422 	if (connection != NULL) {
423 		if (connection->wait_to_send_acceptor) {
424 			log_debug("call avdtp_acceptor_stream_config_subsm_run %p", connection);
425 			connection->wait_to_send_acceptor = false;
426 			avdtp_acceptor_stream_config_subsm_run(connection);
427 		} else if (connection->wait_to_send_initiator) {
428 			log_debug("call avdtp_initiator_stream_config_subsm_handle_can_send_now_signaling %p", connection);
429 			connection->wait_to_send_initiator = false;
430 			avdtp_initiator_stream_config_subsm_handle_can_send_now_signaling(connection);
431 		}
432 		bool more_to_send = connection->wait_to_send_acceptor || connection->wait_to_send_initiator;
433 		if (more_to_send){
434 			l2cap_request_can_send_now_event(l2cap_cid);
435 		}
436 		return;
437 	}
438 
439 	// get stream endpoint connection for l2cap cid
440 	avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_l2cap_cid(l2cap_cid);
441 	if (stream_endpoint != NULL) {
442 		log_debug("call avdtp_initiator_stream_config_subsm_handle_can_send_now_stream_endpoint %p", stream_endpoint);
443 		if (stream_endpoint->request_can_send_now) {
444 			stream_endpoint->request_can_send_now = 0;
445 			avdtp_initiator_stream_config_subsm_handle_can_send_now_stream_endpoint(stream_endpoint);
446 		}
447 		bool more_to_send = stream_endpoint->request_can_send_now != 0;
448 		if (more_to_send){
449 			l2cap_request_can_send_now_event(l2cap_cid);
450 		}
451 	}
452 }
453 /* END: tracking can send now requests per l2cap cid */
454 
455 
456 avdtp_stream_endpoint_t * avdtp_create_stream_endpoint(avdtp_sep_type_t sep_type, avdtp_media_type_t media_type){
457     avdtp_stream_endpoint_t * stream_endpoint = btstack_memory_avdtp_stream_endpoint_get();
458     if (!stream_endpoint){
459         log_error("Not enough memory to create stream endpoint");
460         return NULL;
461     }
462     stream_endpoint->sep.seid = avdtp_get_next_local_seid();
463     stream_endpoint->sep.media_type = media_type;
464     stream_endpoint->sep.type = sep_type;
465     btstack_linked_list_add(avdtp_get_stream_endpoints(), (btstack_linked_item_t *) stream_endpoint);
466     return stream_endpoint;
467 }
468 
469 void avdtp_finalize_stream_endpoint(avdtp_stream_endpoint_t * stream_endpoint){
470     btstack_linked_list_remove(avdtp_get_stream_endpoints(), (btstack_linked_item_t* ) stream_endpoint);
471     btstack_memory_avdtp_stream_endpoint_free(stream_endpoint);
472 }
473 
474 static void
475 handle_l2cap_data_packet_for_signaling_connection(avdtp_connection_t *connection, uint8_t *packet, uint16_t size) {
476     if (size < 2) return;
477 
478     uint16_t offset;
479     avdtp_message_type_t message_type = avdtp_get_signaling_packet_type(packet);
480     switch (message_type){
481         case AVDTP_CMD_MSG:
482             offset = avdtp_read_signaling_header(&connection->acceptor_signaling_packet, packet, size);
483             avdtp_acceptor_stream_config_subsm(connection, packet, size, offset);
484             break;
485         default:
486             offset = avdtp_read_signaling_header(&connection->initiator_signaling_packet, packet, size);
487             avdtp_initiator_stream_config_subsm(connection, packet, size, offset);
488             break;
489     }
490 }
491 
492 static void avdtp_handle_sdp_client_query_attribute_value(avdtp_connection_t * connection, uint8_t *packet){
493     des_iterator_t des_list_it;
494     des_iterator_t prot_it;
495 
496     // Handle new SDP record
497     if (sdp_event_query_attribute_byte_get_record_id(packet) != record_id) {
498         record_id = sdp_event_query_attribute_byte_get_record_id(packet);
499         // log_info("SDP Record: Nr: %d", record_id);
500     }
501 
502     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= attribute_value_buffer_size) {
503         attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
504 
505         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
506 
507             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
508 
509                 case BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST:
510                     if (de_get_element_type(attribute_value) != DE_DES) break;
511                     for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
512                         uint8_t * element = des_iterator_get_element(&des_list_it);
513                         if (de_get_element_type(element) != DE_UUID) continue;
514                         uint32_t uuid = de_get_uuid32(element);
515                         switch (uuid){
516                             case BLUETOOTH_SERVICE_CLASS_AUDIO_SOURCE:
517                                 connection->source_supported = true;
518                                 log_info("source_supported");
519                                 break;
520                             case BLUETOOTH_SERVICE_CLASS_AUDIO_SINK:
521                                 connection->sink_supported = true;
522                                 log_info("sink_supported");
523                                 break;
524                             default:
525                                 break;
526                         }
527                     }
528                     break;
529 
530                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
531                     // log_info("SDP Attribute: 0x%04x", sdp_event_query_attribute_byte_get_attribute_id(packet));
532                     for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
533                         uint8_t       *des_element;
534                         uint8_t       *element;
535                         uint32_t       uuid;
536 
537                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
538 
539                         des_element = des_iterator_get_element(&des_list_it);
540                         des_iterator_init(&prot_it, des_element);
541                         element = des_iterator_get_element(&prot_it);
542 
543                         if (de_get_element_type(element) != DE_UUID) continue;
544 
545                         uuid = de_get_uuid32(element);
546                         des_iterator_next(&prot_it);
547                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
548                         switch (uuid){
549                             case BLUETOOTH_PROTOCOL_L2CAP:
550                                 if (!des_iterator_has_more(&prot_it)) continue;
551                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->avdtp_l2cap_psm);
552                                 break;
553                             case BLUETOOTH_PROTOCOL_AVDTP:
554                                 if (!des_iterator_has_more(&prot_it)) continue;
555                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->avdtp_version);
556                                 log_info("avdtp version 0x%02x", connection->avdtp_version);
557                                 break;
558                             default:
559                                 break;
560                         }
561                     }
562                     break;
563 
564                 default:
565                     break;
566             }
567         }
568     } else {
569         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));
570     }
571 
572 }
573 
574 static void avdtp_finalize_connection(avdtp_connection_t * connection){
575     btstack_run_loop_remove_timer(&connection->retry_timer);
576     btstack_linked_list_remove(&connections, (btstack_linked_item_t*) connection);
577     btstack_memory_avdtp_connection_free(connection);
578 }
579 
580 static void avdtp_handle_sdp_query_failed(avdtp_connection_t * connection, uint8_t status){
581     switch (connection->state){
582         case AVDTP_SIGNALING_W4_SDP_QUERY_FOR_REMOTE_SINK_COMPLETE:
583         case AVDTP_SIGNALING_W4_SDP_QUERY_FOR_REMOTE_SOURCE_COMPLETE:
584             avdtp_signaling_emit_connection_established(connection->avdtp_cid, connection->remote_addr, connection->con_handle, status);
585             break;
586 
587         case AVDTP_SIGNALING_CONNECTION_OPENED:
588             // SDP query failed: try query that must be supported
589             connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_CAPABILITIES;
590 			avdtp_request_can_send_now_initiator(connection);
591             return;
592 
593         default:
594             btstack_assert(false);
595             break;
596     }
597     avdtp_finalize_connection(connection);
598     sdp_query_context_avdtp_cid = 0;
599     log_info("SDP query failed with status 0x%02x.", status);
600 }
601 
602 static void avdtp_handle_sdp_query_succeeded(avdtp_connection_t * connection){
603     log_info("avdtp_handle_sdp_query_succeeded: state %d", connection->state);
604 
605     switch (connection->state){
606         case AVDTP_SIGNALING_CONNECTION_OPENED:
607             if (connection->avdtp_version < 0x0103){
608                 connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_CAPABILITIES;
609             } else {
610                 connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_ALL_CAPABILITIES;
611             }
612 			avdtp_request_can_send_now_initiator(connection);
613             break;
614         default:
615             connection->state = AVDTP_SIGNALING_CONNECTION_W4_L2CAP_CONNECTED;
616             l2cap_create_channel(avdtp_packet_handler, connection->remote_addr, connection->avdtp_l2cap_psm, l2cap_max_mtu(), NULL);
617             break;
618     }
619 }
620 
621 static void avdtp_handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
622     UNUSED(packet_type);
623     UNUSED(channel);
624     UNUSED(size);
625 
626     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(sdp_query_context_avdtp_cid);
627     if (!connection) {
628         log_error("SDP query, connection with 0x%02x cid not found", sdp_query_context_avdtp_cid);
629         return;
630     }
631 
632     uint8_t status = ERROR_CODE_SUCCESS;
633     switch (connection->state){
634         case AVDTP_SIGNALING_W4_SDP_QUERY_FOR_REMOTE_SINK_COMPLETE:
635             switch (hci_event_packet_get_type(packet)){
636                 case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
637                     avdtp_handle_sdp_client_query_attribute_value(connection, packet);
638                     return;
639                 case SDP_EVENT_QUERY_COMPLETE:
640                     status = sdp_event_query_complete_get_status(packet);
641                     if (status != ERROR_CODE_SUCCESS) break;
642                     if (!connection->sink_supported || (connection->avdtp_l2cap_psm == 0)) {
643                         status = SDP_SERVICE_NOT_FOUND;
644                         break;
645                     }
646                     break;
647                 default:
648                     btstack_assert(false);
649                     return;
650             }
651             break;
652         case AVDTP_SIGNALING_W4_SDP_QUERY_FOR_REMOTE_SOURCE_COMPLETE:
653             switch (hci_event_packet_get_type(packet)){
654                 case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
655                     avdtp_handle_sdp_client_query_attribute_value(connection, packet);
656                     return;
657                 case SDP_EVENT_QUERY_COMPLETE:
658                     status = sdp_event_query_complete_get_status(packet);
659                     if (status != ERROR_CODE_SUCCESS) break;
660                     if (!connection->source_supported || (connection->avdtp_l2cap_psm == 0)) {
661                         status = SDP_SERVICE_NOT_FOUND;
662                         break;
663                     }
664                     break;
665                 default:
666                     btstack_assert(false);
667                     return;
668             }
669             break;
670 
671         case AVDTP_SIGNALING_CONNECTION_OPENED:
672             switch (hci_event_packet_get_type(packet)){
673                 case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
674                     avdtp_handle_sdp_client_query_attribute_value(connection, packet);
675                     return;
676                 case SDP_EVENT_QUERY_COMPLETE:
677                     // without suitable SDP Record, avdtp version v0.0 is assumed
678                     status = sdp_event_query_complete_get_status(packet);
679                     break;
680                 default:
681                     btstack_assert(false);
682                     return;
683             }
684             break;
685 
686         default:
687             // bail out, we must have had an incoming connection in the meantime; just trigger next sdp query on complete
688             if (hci_event_packet_get_type(packet) == SDP_EVENT_QUERY_COMPLETE){
689                 (void) sdp_client_register_query_callback(&avdtp_handle_sdp_client_query_request);
690             }
691             return;
692     }
693 
694     if (status == ERROR_CODE_SUCCESS){
695         avdtp_handle_sdp_query_succeeded(connection);
696     } else {
697         avdtp_handle_sdp_query_failed(connection, status);
698     }
699 
700     // register the SDP Query request to check if there is another connection waiting for the query
701     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
702     (void) sdp_client_register_query_callback(&avdtp_handle_sdp_client_query_request);
703 }
704 
705 static avdtp_connection_t * avdtp_handle_incoming_connection(avdtp_connection_t * connection, bd_addr_t event_addr, hci_con_handle_t con_handle, uint16_t local_cid){
706     if (connection == NULL){
707         uint16_t cid = avdtp_get_next_cid();
708         connection = avdtp_create_connection(event_addr, cid);
709     }
710 
711     if (connection) {
712         connection->state = AVDTP_SIGNALING_CONNECTION_W4_L2CAP_CONNECTED;
713         connection->l2cap_signaling_cid = local_cid;
714         connection->con_handle = con_handle;
715         btstack_run_loop_remove_timer(&connection->retry_timer);
716     }
717     return connection;
718 }
719 
720 static void avdtp_retry_timer_timeout_handler(btstack_timer_source_t * timer){
721     uint16_t avdtp_cid = (uint16_t)(uintptr_t) btstack_run_loop_get_timer_context(timer);
722 
723     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
724     if (connection == NULL) return;
725 
726     if (connection->state == AVDTP_SIGNALING_CONNECTION_W2_L2CAP_RETRY){
727         connection->state = AVDTP_SIGNALING_CONNECTION_W4_L2CAP_CONNECTED;
728         l2cap_create_channel(&avdtp_packet_handler, connection->remote_addr, connection->avdtp_l2cap_psm, l2cap_max_mtu(), NULL);
729     }
730 }
731 
732 static void avdtp_retry_timer_start(avdtp_connection_t * connection){
733     btstack_run_loop_set_timer_handler(&connection->retry_timer, avdtp_retry_timer_timeout_handler);
734     btstack_run_loop_set_timer_context(&connection->retry_timer, (void *)(uintptr_t)connection->avdtp_cid);
735 
736     // add some jitter/randomness to reconnect delay
737     uint32_t timeout = 100 + (btstack_run_loop_get_time_ms() & 0x7F);
738     btstack_run_loop_set_timer(&connection->retry_timer, timeout);
739     btstack_run_loop_add_timer(&connection->retry_timer);
740 }
741 
742 
743 void avdtp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
744     bd_addr_t event_addr;
745     uint16_t psm;
746     uint16_t local_cid;
747     uint8_t  status;
748     uint16_t l2cap_mtu;
749     hci_con_handle_t con_handle;
750 
751     bool accept_streaming_connection;
752     bool outoing_signaling_active;
753     bool decline_connection;
754 
755     avdtp_stream_endpoint_t * stream_endpoint = NULL;
756     avdtp_connection_t * connection = NULL;
757 
758     switch (packet_type) {
759         case L2CAP_DATA_PACKET:
760             connection = avdtp_get_connection_for_l2cap_signaling_cid(channel);
761             if (connection){
762                 handle_l2cap_data_packet_for_signaling_connection(connection, packet, size);
763                 break;
764             }
765 
766             stream_endpoint = avdtp_get_stream_endpoint_for_l2cap_cid(channel);
767             if (!stream_endpoint){
768                 if (!connection) break;
769                 handle_l2cap_data_packet_for_signaling_connection(connection, packet, size);
770                 break;
771             }
772 
773             if (stream_endpoint->connection){
774                 if (channel == stream_endpoint->connection->l2cap_signaling_cid){
775                     handle_l2cap_data_packet_for_signaling_connection(stream_endpoint->connection, packet, size);
776                     break;
777                 }
778             }
779 
780             if (channel == stream_endpoint->l2cap_media_cid){
781                 btstack_assert(avdtp_sink_handle_media_data);
782                 (*avdtp_sink_handle_media_data)(avdtp_local_seid(stream_endpoint), packet, size);
783                 break;
784             }
785 
786             if (channel == stream_endpoint->l2cap_reporting_cid){
787                 log_info("L2CAP_DATA_PACKET for reporting: NOT IMPLEMENTED");
788             } else if (channel == stream_endpoint->l2cap_recovery_cid){
789                 log_info("L2CAP_DATA_PACKET for recovery: NOT IMPLEMENTED");
790             } else {
791                 log_error("avdtp packet handler L2CAP_DATA_PACKET: local cid 0x%02x not found", channel);
792             }
793             break;
794 
795         case HCI_EVENT_PACKET:
796             switch (hci_event_packet_get_type(packet)) {
797 
798                 case L2CAP_EVENT_INCOMING_CONNECTION:
799                     l2cap_event_incoming_connection_get_address(packet, event_addr);
800                     local_cid = l2cap_event_incoming_connection_get_local_cid(packet);
801                     con_handle = l2cap_event_incoming_connection_get_handle(packet);
802                     outoing_signaling_active = false;
803                     accept_streaming_connection = false;
804 
805                     connection = avdtp_get_connection_for_bd_addr(event_addr);
806                     if (connection != NULL){
807                         switch (connection->state){
808                             case AVDTP_SIGNALING_CONNECTION_W4_L2CAP_DISCONNECTED:
809                             case AVDTP_SIGNALING_CONNECTION_W4_L2CAP_CONNECTED:
810                                 outoing_signaling_active = true;
811                                 connection->incoming_declined = true;
812                                 break;
813                             case AVDTP_SIGNALING_CONNECTION_OPENED:
814                                 outoing_signaling_active = true;
815                                 accept_streaming_connection = true;
816                                 break;
817                             default:
818                                 break;
819                         }
820                     }
821                     log_info("incoming: %s, outoing_signaling_active %d, accept_streaming_connection %d",
822                         bd_addr_to_str(event_addr), outoing_signaling_active, accept_streaming_connection);
823 
824                     decline_connection = outoing_signaling_active && !accept_streaming_connection;
825                     if (outoing_signaling_active == false){
826                         connection = avdtp_handle_incoming_connection(connection, event_addr, con_handle, local_cid);
827                         if (connection == NULL){
828                             decline_connection = true;
829                         }
830                     } else if (accept_streaming_connection){
831                         if ((connection == NULL) || (connection->configuration_state != AVDTP_CONFIGURATION_STATE_REMOTE_CONFIGURED)) {
832                             decline_connection = true;
833                         } else {
834                             // now, we're only dealing with media connections that are created by remote side - we're acceptor here
835                             stream_endpoint = avdtp_get_stream_endpoint_for_seid(connection->acceptor_local_seid);
836                             if ((stream_endpoint == NULL) || (stream_endpoint->l2cap_media_cid != 0) ) {
837                                 decline_connection = true;
838                             }
839                         }
840                     }
841 
842                     if (decline_connection){
843                         l2cap_decline_connection(local_cid);
844                     } else {
845                         l2cap_accept_connection(local_cid);
846                     }
847                     break;
848 
849                 case L2CAP_EVENT_CHANNEL_OPENED:
850 
851                     psm = l2cap_event_channel_opened_get_psm(packet);
852                     if (psm != BLUETOOTH_PSM_AVDTP){
853                         log_info("Unexpected PSM - Not implemented yet, avdtp sink: L2CAP_EVENT_CHANNEL_OPENED ");
854                         return;
855                     }
856 
857                     status = l2cap_event_channel_opened_get_status(packet);
858                     // inform about new l2cap connection
859                     l2cap_event_channel_opened_get_address(packet, event_addr);
860                     local_cid = l2cap_event_channel_opened_get_local_cid(packet);
861                     l2cap_mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
862                     connection = avdtp_get_connection_for_bd_addr(event_addr);
863                     if (connection == NULL){
864                         log_info("L2CAP_EVENT_CHANNEL_OPENED: no connection found for %s", bd_addr_to_str(event_addr));
865                         break;
866                     }
867 
868                     con_handle = l2cap_event_channel_opened_get_handle(packet);
869 
870                     switch (connection->state){
871                         case AVDTP_SIGNALING_CONNECTION_W4_L2CAP_CONNECTED:
872                             switch (status){
873                                 case ERROR_CODE_SUCCESS:
874                                     connection->l2cap_signaling_cid = local_cid;
875                                     connection->incoming_declined = false;
876                                     connection->l2cap_mtu = l2cap_mtu;
877                                     connection->con_handle = con_handle;
878                                     connection->state = AVDTP_SIGNALING_CONNECTION_OPENED;
879                                     log_info("Connection opened l2cap_signaling_cid 0x%02x, avdtp_cid 0x%02x, con_handle 0x%02x", connection->l2cap_signaling_cid, connection->avdtp_cid, con_handle);
880                                     avdtp_signaling_emit_connection_established(connection->avdtp_cid, event_addr, con_handle, status);
881                                     return;
882                                 case L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES:
883                                     if (connection->incoming_declined == true) {
884                                         log_info("Connection was declined, and the outgoing failed");
885                                         connection->state = AVDTP_SIGNALING_CONNECTION_W2_L2CAP_RETRY;
886                                         connection->incoming_declined = false;
887                                         avdtp_retry_timer_start(connection);
888                                         return;
889                                     }
890                                     break;
891                                 default:
892                                     log_info("Connection to %s failed. status code 0x%02x", bd_addr_to_str(event_addr), status);
893                                     break;
894                             }
895                             avdtp_signaling_emit_connection_established(connection->avdtp_cid, event_addr, con_handle, status);
896                             avdtp_finalize_connection(connection);
897                             break;
898 
899                         case AVDTP_SIGNALING_CONNECTION_OPENED:
900                             stream_endpoint = avdtp_get_stream_endpoint_for_signaling_cid(connection->l2cap_signaling_cid);
901                             if (!stream_endpoint){
902                                 log_info("L2CAP_EVENT_CHANNEL_OPENED: stream_endpoint not found for signaling cid 0x%02x", connection->l2cap_signaling_cid);
903                                 return;
904                             }
905                             if (status != ERROR_CODE_SUCCESS){
906                                 log_info("AVDTP_STREAM_ENDPOINT_OPENED failed with status %d, avdtp cid 0x%02x, l2cap_media_cid 0x%02x, local seid %d, remote seid %d", status, connection->avdtp_cid, stream_endpoint->l2cap_media_cid, avdtp_local_seid(stream_endpoint), avdtp_remote_seid(stream_endpoint));
907                                 stream_endpoint->state = AVDTP_STREAM_ENDPOINT_IDLE;
908                                 avdtp_streaming_emit_connection_established(stream_endpoint, status);
909                                 break;
910                             }
911                             switch (stream_endpoint->state){
912                                 case AVDTP_STREAM_ENDPOINT_W4_L2CAP_FOR_MEDIA_CONNECTED:
913                                     stream_endpoint->state = AVDTP_STREAM_ENDPOINT_OPENED;
914                                     stream_endpoint->l2cap_media_cid = l2cap_event_channel_opened_get_local_cid(packet);
915                                     stream_endpoint->media_con_handle = l2cap_event_channel_opened_get_handle(packet);
916 
917                                     log_info("AVDTP_STREAM_ENDPOINT_OPENED, avdtp cid 0x%02x, l2cap_media_cid 0x%02x, local seid %d, remote seid %d", connection->avdtp_cid, stream_endpoint->l2cap_media_cid, avdtp_local_seid(stream_endpoint), avdtp_remote_seid(stream_endpoint));
918                                     avdtp_streaming_emit_connection_established(stream_endpoint, ERROR_CODE_SUCCESS);
919                                     break;
920                                 default:
921                                     log_info("AVDTP_STREAM_ENDPOINT_OPENED failed - stream endpoint in wrong state %d, avdtp cid 0x%02x, l2cap_media_cid 0x%02x, local seid %d, remote seid %d", stream_endpoint->state, connection->avdtp_cid, stream_endpoint->l2cap_media_cid, avdtp_local_seid(stream_endpoint), avdtp_remote_seid(stream_endpoint));
922                                     avdtp_streaming_emit_connection_established(stream_endpoint, ERROR_CODE_COMMAND_DISALLOWED);
923                                     break;
924                             }
925                             break;
926 
927                         default:
928                             log_info("L2CAP connection to %s ignored: status code 0x%02x, connection state %d", bd_addr_to_str(event_addr), status, connection->state);
929                             break;
930                     }
931                     break;
932 
933                 case L2CAP_EVENT_CHANNEL_CLOSED:
934                     local_cid = l2cap_event_channel_closed_get_local_cid(packet);
935                     stream_endpoint = avdtp_get_stream_endpoint_for_l2cap_cid(local_cid);
936                     connection = avdtp_get_connection_for_l2cap_signaling_cid(local_cid);
937 
938                     log_info("Received L2CAP_EVENT_CHANNEL_CLOSED, cid 0x%2x, connection %p, stream_endpoint %p", local_cid, connection, stream_endpoint);
939 
940                     if (stream_endpoint){
941                         if (stream_endpoint->l2cap_media_cid == local_cid){
942                             connection = stream_endpoint->connection;
943                             if (connection) {
944                                 avdtp_streaming_emit_connection_released(stream_endpoint,
945                                                                          connection->avdtp_cid,
946                                                                          avdtp_local_seid(stream_endpoint));
947                             }
948                             avdtp_reset_stream_endpoint(stream_endpoint);
949                             connection->configuration_state = AVDTP_CONFIGURATION_STATE_IDLE;
950                             break;
951                         }
952                         if (stream_endpoint->l2cap_recovery_cid == local_cid){
953                             log_info("L2CAP_EVENT_CHANNEL_CLOSED recovery cid 0x%0x", local_cid);
954                             stream_endpoint->l2cap_recovery_cid = 0;
955                             break;
956                         }
957 
958                         if (stream_endpoint->l2cap_reporting_cid == local_cid){
959                             log_info("L2CAP_EVENT_CHANNEL_CLOSED reporting cid 0x%0x", local_cid);
960                             stream_endpoint->l2cap_reporting_cid = 0;
961                             break;
962                         }
963                     }
964 
965                     if (connection){
966                         btstack_linked_list_iterator_t it;
967                         btstack_linked_list_iterator_init(&it, avdtp_get_stream_endpoints());
968                         while (btstack_linked_list_iterator_has_next(&it)){
969                             stream_endpoint = (avdtp_stream_endpoint_t *)btstack_linked_list_iterator_next(&it);
970                             if (stream_endpoint->connection == connection){
971                                 avdtp_reset_stream_endpoint(stream_endpoint);
972                             }
973                         }
974                         avdtp_signaling_emit_connection_released(connection->avdtp_cid);
975                         avdtp_finalize_connection(connection);
976                         break;
977                     }
978                     break;
979 
980                 case L2CAP_EVENT_CAN_SEND_NOW:
981                     log_debug("avdtp_packet_handler, L2CAP_EVENT_CAN_SEND_NOW l2cap_cid 0x%02x", channel);
982 					avdtp_handle_can_send_now(channel);
983                     break;
984                 default:
985                     log_info("Unknown HCI event type %02x", hci_event_packet_get_type(packet));
986                     break;
987             }
988             break;
989 
990         default:
991             // other packet type
992             break;
993     }
994 }
995 
996 uint8_t avdtp_disconnect(uint16_t avdtp_cid){
997     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
998     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
999 
1000     if (connection->state == AVDTP_SIGNALING_CONNECTION_W4_L2CAP_DISCONNECTED) return ERROR_CODE_SUCCESS;
1001 
1002     btstack_linked_list_iterator_t it;
1003     btstack_linked_list_iterator_init(&it, avdtp_get_stream_endpoints());
1004 
1005     while (btstack_linked_list_iterator_has_next(&it)){
1006         avdtp_stream_endpoint_t * stream_endpoint = (avdtp_stream_endpoint_t *)btstack_linked_list_iterator_next(&it);
1007         if (stream_endpoint->connection != connection) continue;
1008 
1009         switch (stream_endpoint->state){
1010             case AVDTP_STREAM_ENDPOINT_OPENED:
1011             case AVDTP_STREAM_ENDPOINT_STREAMING:
1012                 stream_endpoint->state = AVDTP_STREAM_ENDPOINT_W4_L2CAP_FOR_MEDIA_DISCONNECTED;
1013                 l2cap_disconnect(stream_endpoint->l2cap_media_cid, 0);
1014                 break;
1015             default:
1016                 break;
1017         }
1018     }
1019 
1020     connection->state = AVDTP_SIGNALING_CONNECTION_W4_L2CAP_DISCONNECTED;
1021     l2cap_disconnect(connection->l2cap_signaling_cid, 0);
1022     return ERROR_CODE_SUCCESS;
1023 }
1024 
1025 uint8_t avdtp_open_stream(uint16_t avdtp_cid, uint8_t local_seid, uint8_t remote_seid){
1026     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1027     if (!connection){
1028         log_error("avdtp_media_connect: no connection for signaling cid 0x%02x found", avdtp_cid);
1029         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1030     }
1031 
1032     if (connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) {
1033         log_error("avdtp_media_connect: wrong connection state %d", connection->state);
1034         return ERROR_CODE_COMMAND_DISALLOWED;
1035     }
1036 
1037     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1038     if (!stream_endpoint) {
1039         log_error("avdtp_media_connect: no stream_endpoint with seid %d found", local_seid);
1040         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1041     }
1042 
1043     if (stream_endpoint->remote_sep.seid != remote_seid){
1044         log_error("avdtp_media_connect: no remote sep with seid %d registered with the stream endpoint", remote_seid);
1045         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1046     }
1047 
1048     if (stream_endpoint->state < AVDTP_STREAM_ENDPOINT_CONFIGURED) return ERROR_CODE_COMMAND_DISALLOWED;
1049 
1050     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1051     connection->initiator_remote_seid = remote_seid;
1052     connection->initiator_local_seid = local_seid;
1053     stream_endpoint->initiator_config_state = AVDTP_INITIATOR_W2_OPEN_STREAM;
1054     stream_endpoint->state = AVDTP_STREAM_ENDPOINT_W2_REQUEST_OPEN_STREAM;
1055 	avdtp_request_can_send_now_initiator(connection);
1056     return ERROR_CODE_SUCCESS;
1057 }
1058 
1059 uint8_t avdtp_start_stream(uint16_t avdtp_cid, uint8_t local_seid){
1060     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1061     if (!connection){
1062         log_error("avdtp_start_stream: no connection for signaling cid 0x%02x found", avdtp_cid);
1063         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1064     }
1065 
1066     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1067     if (!stream_endpoint) {
1068         log_error("avdtp_start_stream: no stream_endpoint with seid %d found", local_seid);
1069         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1070     }
1071 
1072     if (stream_endpoint->l2cap_media_cid == 0){
1073         log_error("avdtp_start_stream: no media connection for stream_endpoint with seid %d found", local_seid);
1074         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1075     }
1076 
1077     if (!is_avdtp_remote_seid_registered(stream_endpoint)){
1078         log_error("avdtp_media_connect: no remote sep registered with the stream endpoint");
1079         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1080     }
1081 
1082     if (!is_avdtp_remote_seid_registered(stream_endpoint) || stream_endpoint->start_stream == 1){
1083         return ERROR_CODE_COMMAND_DISALLOWED;
1084     }
1085 
1086     stream_endpoint->start_stream = 1;
1087     connection->initiator_local_seid = local_seid;
1088     connection->initiator_remote_seid = stream_endpoint->remote_sep.seid;
1089 	avdtp_request_can_send_now_initiator(connection);
1090     return ERROR_CODE_SUCCESS;
1091 }
1092 
1093 uint8_t avdtp_stop_stream(uint16_t avdtp_cid, uint8_t local_seid){
1094     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1095     if (!connection){
1096         log_error("avdtp_stop_stream: no connection for signaling cid 0x%02x found", avdtp_cid);
1097         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1098     }
1099 
1100     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1101     if (!stream_endpoint) {
1102         log_error("avdtp_stop_stream: no stream_endpoint with seid %d found", local_seid);
1103         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1104     }
1105 
1106     if (stream_endpoint->l2cap_media_cid == 0){
1107         log_error("avdtp_stop_stream: no media connection for stream_endpoint with seid %d found", local_seid);
1108         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1109     }
1110 
1111     if (!is_avdtp_remote_seid_registered(stream_endpoint) || stream_endpoint->close_stream){
1112         return ERROR_CODE_COMMAND_DISALLOWED;
1113     }
1114 
1115     stream_endpoint->close_stream = 1;
1116     connection->initiator_local_seid = local_seid;
1117     connection->initiator_remote_seid = stream_endpoint->remote_sep.seid;
1118 	avdtp_request_can_send_now_initiator(connection);
1119     return ERROR_CODE_SUCCESS;
1120 }
1121 
1122 uint8_t avdtp_abort_stream(uint16_t avdtp_cid, uint8_t local_seid){
1123     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1124     if (!connection){
1125         log_error("avdtp_abort_stream: no connection for signaling cid 0x%02x found", avdtp_cid);
1126         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1127     }
1128 
1129     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1130     if (!stream_endpoint) {
1131         log_error("avdtp_abort_stream: no stream_endpoint with seid %d found", local_seid);
1132         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1133     }
1134 
1135     if (stream_endpoint->l2cap_media_cid == 0){
1136         log_error("avdtp_abort_stream: no media connection for stream_endpoint with seid %d found", local_seid);
1137         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1138     }
1139 
1140     if (!is_avdtp_remote_seid_registered(stream_endpoint) || stream_endpoint->abort_stream){
1141         return ERROR_CODE_COMMAND_DISALLOWED;
1142     }
1143 
1144     stream_endpoint->abort_stream = 1;
1145     connection->initiator_local_seid = local_seid;
1146     connection->initiator_remote_seid = stream_endpoint->remote_sep.seid;
1147 	avdtp_request_can_send_now_initiator(connection);
1148     return ERROR_CODE_SUCCESS;
1149 }
1150 
1151 uint8_t avdtp_suspend_stream(uint16_t avdtp_cid, uint8_t local_seid){
1152     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1153     if (!connection){
1154         log_error("avdtp_suspend_stream: no connection for signaling cid 0x%02x found", avdtp_cid);
1155         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1156     }
1157     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1158     if (!stream_endpoint) {
1159         log_error("avdtp_suspend_stream: no stream_endpoint with seid %d found", local_seid);
1160         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1161     }
1162 
1163     if (stream_endpoint->l2cap_media_cid == 0){
1164         log_error("avdtp_suspend_stream: no media connection for stream_endpoint with seid %d found", local_seid);
1165         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1166     }
1167 
1168     if (!is_avdtp_remote_seid_registered(stream_endpoint) || stream_endpoint->suspend_stream){
1169         return ERROR_CODE_COMMAND_DISALLOWED;
1170     }
1171 
1172     stream_endpoint->suspend_stream = 1;
1173     connection->initiator_local_seid = local_seid;
1174     connection->initiator_remote_seid = stream_endpoint->remote_sep.seid;
1175 	avdtp_request_can_send_now_initiator(connection);
1176     return ERROR_CODE_SUCCESS;
1177 }
1178 
1179 uint8_t avdtp_discover_stream_endpoints(uint16_t avdtp_cid){
1180     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1181     if (!connection){
1182         log_error("avdtp_discover_stream_endpoints: no connection for signaling cid 0x%02x found", avdtp_cid);
1183         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1184     }
1185     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1186         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1187         return ERROR_CODE_COMMAND_DISALLOWED;
1188     }
1189 
1190     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1191     connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_DISCOVER_SEPS;
1192     return avdtp_request_can_send_now_initiator(connection);
1193 }
1194 
1195 
1196 uint8_t avdtp_get_capabilities(uint16_t avdtp_cid, uint8_t remote_seid){
1197     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1198     if (!connection){
1199         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1200         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1201     }
1202     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1203         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1204         return ERROR_CODE_COMMAND_DISALLOWED;
1205     }
1206 
1207     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1208     connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_CAPABILITIES;
1209     connection->initiator_remote_seid = remote_seid;
1210     return avdtp_request_can_send_now_initiator(connection);
1211 }
1212 
1213 
1214 uint8_t avdtp_get_all_capabilities(uint16_t avdtp_cid, uint8_t remote_seid){
1215     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1216     if (!connection){
1217         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1218         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1219     }
1220     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1221         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1222         return ERROR_CODE_COMMAND_DISALLOWED;
1223     }
1224 
1225     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1226     connection->initiator_remote_seid = remote_seid;
1227 
1228     if (connection->avdtp_version == 0){
1229         connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_SEND_SDP_QUERY_THEN_GET_ALL_CAPABILITIES;
1230         avdtp_handle_sdp_client_query_request.callback = &avdtp_handle_start_sdp_client_query;
1231         // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1232         (void) sdp_client_register_query_callback(&avdtp_handle_sdp_client_query_request);
1233         return ERROR_CODE_SUCCESS;
1234     } else {
1235         // AVDTP version lower then 1.3 supports only get capabilities command
1236         if (connection->avdtp_version < 0x103){
1237             connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_CAPABILITIES;
1238         } else {
1239             connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_ALL_CAPABILITIES;
1240         }
1241         return avdtp_request_can_send_now_initiator(connection);
1242     }
1243 }
1244 
1245 uint8_t avdtp_get_configuration(uint16_t avdtp_cid, uint8_t remote_seid){
1246     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1247     if (!connection){
1248         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1249         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1250     }
1251     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1252         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1253         return ERROR_CODE_COMMAND_DISALLOWED;
1254     }
1255 
1256     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1257     connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_CONFIGURATION;
1258     connection->initiator_remote_seid = remote_seid;
1259     return avdtp_request_can_send_now_initiator(connection);
1260 }
1261 
1262 uint8_t avdtp_set_configuration(uint16_t avdtp_cid, uint8_t local_seid, uint8_t remote_seid, uint16_t configured_services_bitmap, avdtp_capabilities_t configuration){
1263     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1264     if (!connection){
1265         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1266         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1267     }
1268     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1269         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1270         log_error("connection in wrong state, %d, initiator state %d", connection->state, connection->initiator_connection_state);
1271         return ERROR_CODE_COMMAND_DISALLOWED;
1272     }
1273     if (connection->configuration_state != AVDTP_CONFIGURATION_STATE_IDLE){
1274         log_info("configuration already started, config state %u", connection->configuration_state);
1275         return ERROR_CODE_COMMAND_DISALLOWED;
1276     }
1277 
1278     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1279     if (!stream_endpoint) {
1280         log_error("No initiator stream endpoint for seid %d", local_seid);
1281         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1282     }
1283     if (stream_endpoint->state >= AVDTP_STREAM_ENDPOINT_CONFIGURED){
1284         log_error("Stream endpoint seid %d in wrong state %d", local_seid, stream_endpoint->state);
1285         return ERROR_CODE_COMMAND_DISALLOWED;
1286     }
1287 
1288     connection->active_stream_endpoint = (void*) stream_endpoint;
1289     connection->configuration_state = AVDTP_CONFIGURATION_STATE_LOCAL_INITIATED;
1290 
1291     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1292     connection->initiator_remote_seid = remote_seid;
1293     connection->initiator_local_seid = local_seid;
1294     stream_endpoint->remote_configuration_bitmap = configured_services_bitmap;
1295     stream_endpoint->remote_configuration = configuration;
1296     stream_endpoint->initiator_config_state = AVDTP_INITIATOR_W2_SET_CONFIGURATION;
1297 
1298 	log_debug("SE %p, initiator_config_state: 0x%02x", stream_endpoint, stream_endpoint->initiator_config_state);
1299 
1300     return avdtp_request_can_send_now_initiator(connection);
1301 }
1302 
1303 uint8_t avdtp_reconfigure(uint16_t avdtp_cid, uint8_t local_seid, uint8_t remote_seid, uint16_t configured_services_bitmap, avdtp_capabilities_t configuration){
1304     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1305     if (!connection){
1306         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1307         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1308     }
1309     //TODO: if opened only app capabilities, enable reconfigure for not opened
1310     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1311         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1312         return ERROR_CODE_COMMAND_DISALLOWED;
1313     }
1314 
1315     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1316     if (!stream_endpoint) {
1317         log_error("avdtp_reconfigure: no initiator stream endpoint for seid %d", local_seid);
1318         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1319     }
1320 
1321     if (!is_avdtp_remote_seid_registered(stream_endpoint)){
1322         log_error("avdtp_reconfigure: no associated remote sep");
1323         return ERROR_CODE_COMMAND_DISALLOWED;
1324     }
1325 
1326     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1327     connection->initiator_remote_seid = remote_seid;
1328     connection->initiator_local_seid = local_seid;
1329     stream_endpoint->remote_configuration_bitmap = configured_services_bitmap;
1330     stream_endpoint->remote_configuration = configuration;
1331     stream_endpoint->initiator_config_state = AVDTP_INITIATOR_W2_RECONFIGURE_STREAM_WITH_SEID;
1332     return avdtp_request_can_send_now_initiator(connection);
1333 }
1334 
1335 void    avdtp_set_preferred_sampling_frequeny(avdtp_stream_endpoint_t * stream_endpoint, uint32_t sampling_frequency){
1336     stream_endpoint->preferred_sampling_frequency = sampling_frequency;
1337 }
1338 
1339 void    avdtp_set_preferred_channel_mode(avdtp_stream_endpoint_t * stream_endpoint, uint8_t channel_mode){
1340     stream_endpoint->preferred_channel_mode = channel_mode;
1341 }
1342 
1343 
1344 avdtp_channel_mode_t avdtp_choose_sbc_channel_mode(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_channel_mode_bitmap){
1345     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1346     uint8_t channel_mode_bitmap = (media_codec[0] & 0x0F) & remote_channel_mode_bitmap;
1347 
1348     // use preferred channel mode if possible
1349     if (stream_endpoint->preferred_channel_mode == AVDTP_SBC_JOINT_STEREO){
1350         return AVDTP_CHANNEL_MODE_JOINT_STEREO;
1351     }
1352     if (stream_endpoint->preferred_channel_mode == AVDTP_SBC_STEREO){
1353         return AVDTP_CHANNEL_MODE_STEREO;
1354     }
1355     if (stream_endpoint->preferred_channel_mode == AVDTP_SBC_DUAL_CHANNEL){
1356         return AVDTP_CHANNEL_MODE_DUAL_CHANNEL;
1357     }
1358     if (stream_endpoint->preferred_channel_mode == AVDTP_SBC_MONO){
1359         return AVDTP_CHANNEL_MODE_MONO;
1360     }
1361 
1362 
1363     if (channel_mode_bitmap & AVDTP_SBC_JOINT_STEREO){
1364         return AVDTP_CHANNEL_MODE_JOINT_STEREO;
1365     } else if (channel_mode_bitmap & AVDTP_SBC_STEREO){
1366         return AVDTP_CHANNEL_MODE_STEREO;
1367     } else if (channel_mode_bitmap & AVDTP_SBC_DUAL_CHANNEL){
1368         return AVDTP_CHANNEL_MODE_DUAL_CHANNEL;
1369     } else if (channel_mode_bitmap & AVDTP_SBC_MONO){
1370         return AVDTP_CHANNEL_MODE_MONO;
1371     }
1372     return AVDTP_CHANNEL_MODE_JOINT_STEREO;
1373 }
1374 
1375 avdtp_sbc_allocation_method_t avdtp_choose_sbc_allocation_method(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_allocation_method_bitmap){
1376     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1377     uint8_t allocation_method_bitmap = (media_codec[1] & 0x03) & remote_allocation_method_bitmap;
1378 
1379     avdtp_sbc_allocation_method_t allocation_method = AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS;
1380     if (allocation_method_bitmap & AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS){
1381         allocation_method = AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS;
1382     } else if (allocation_method_bitmap & AVDTP_SBC_ALLOCATION_METHOD_SNR){
1383         allocation_method = AVDTP_SBC_ALLOCATION_METHOD_SNR;
1384     }
1385     return allocation_method;
1386 }
1387 
1388 uint8_t avdtp_stream_endpoint_seid(avdtp_stream_endpoint_t * stream_endpoint){
1389     if (!stream_endpoint) return 0;
1390     return stream_endpoint->sep.seid;
1391 }
1392 uint8_t avdtp_choose_sbc_subbands(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_subbands_bitmap){
1393     if (!stream_endpoint) return 0;
1394     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1395     uint8_t subbands_bitmap = ((media_codec[1] >> 2) & 0x03) & remote_subbands_bitmap;
1396 
1397     uint8_t subbands = AVDTP_SBC_SUBBANDS_8;
1398     if (subbands_bitmap & AVDTP_SBC_SUBBANDS_8){
1399         subbands = AVDTP_SBC_SUBBANDS_8;
1400     } else if (subbands_bitmap & AVDTP_SBC_SUBBANDS_4){
1401         subbands = AVDTP_SBC_SUBBANDS_4;
1402     }
1403     return subbands;
1404 }
1405 
1406 uint8_t avdtp_choose_sbc_block_length(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_block_length_bitmap){
1407     if (!stream_endpoint) return 0;
1408     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1409     uint8_t block_length_bitmap = (media_codec[1] >> 4) & remote_block_length_bitmap;
1410 
1411     uint8_t block_length = AVDTP_SBC_BLOCK_LENGTH_16;
1412     if (block_length_bitmap & AVDTP_SBC_BLOCK_LENGTH_16){
1413         block_length = AVDTP_SBC_BLOCK_LENGTH_16;
1414     } else if (block_length_bitmap & AVDTP_SBC_BLOCK_LENGTH_12){
1415         block_length = AVDTP_SBC_BLOCK_LENGTH_12;
1416     } else if (block_length_bitmap & AVDTP_SBC_BLOCK_LENGTH_8){
1417         block_length = AVDTP_SBC_BLOCK_LENGTH_8;
1418     } else if (block_length_bitmap & AVDTP_SBC_BLOCK_LENGTH_4){
1419         block_length = AVDTP_SBC_BLOCK_LENGTH_4;
1420     }
1421     return block_length;
1422 }
1423 
1424 uint16_t avdtp_choose_sbc_sampling_frequency(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_sampling_frequency_bitmap){
1425     if (!stream_endpoint) return 0;
1426     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1427     uint8_t supported_sampling_frequency_bitmap = (media_codec[0] >> 4) & remote_sampling_frequency_bitmap;
1428 
1429     // use preferred sampling frequency if possible
1430     if ((stream_endpoint->preferred_sampling_frequency == 48000) && (supported_sampling_frequency_bitmap & AVDTP_SBC_48000)){
1431         return stream_endpoint->preferred_sampling_frequency;
1432     }
1433     if ((stream_endpoint->preferred_sampling_frequency == 44100) && (supported_sampling_frequency_bitmap & AVDTP_SBC_44100)){
1434         return stream_endpoint->preferred_sampling_frequency;
1435     }
1436     if ((stream_endpoint->preferred_sampling_frequency == 32000) && (supported_sampling_frequency_bitmap & AVDTP_SBC_32000)){
1437         return stream_endpoint->preferred_sampling_frequency;
1438     }
1439     if ((stream_endpoint->preferred_sampling_frequency == 16000) && (supported_sampling_frequency_bitmap & AVDTP_SBC_16000)){
1440         return stream_endpoint->preferred_sampling_frequency;
1441     }
1442 
1443     // otherwise, use highest available
1444     if (supported_sampling_frequency_bitmap & AVDTP_SBC_48000){
1445         return 48000;
1446     }
1447     if (supported_sampling_frequency_bitmap & AVDTP_SBC_44100){
1448         return 44100;
1449     }
1450     if (supported_sampling_frequency_bitmap & AVDTP_SBC_32000){
1451         return 32000;
1452     }
1453     if (supported_sampling_frequency_bitmap & AVDTP_SBC_16000){
1454         return 16000;
1455     }
1456     return 44100; // some default
1457 }
1458 
1459 uint8_t avdtp_choose_sbc_max_bitpool_value(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_max_bitpool_value){
1460     if (!stream_endpoint) return 0;
1461     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1462     return btstack_min(media_codec[3], remote_max_bitpool_value);
1463 }
1464 
1465 uint8_t avdtp_choose_sbc_min_bitpool_value(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_min_bitpool_value){
1466     if (!stream_endpoint) return 0;
1467     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1468     return btstack_max(media_codec[2], remote_min_bitpool_value);
1469 }
1470 
1471 uint8_t is_avdtp_remote_seid_registered(avdtp_stream_endpoint_t * stream_endpoint){
1472     if (!stream_endpoint) return 0;
1473     if (stream_endpoint->remote_sep.seid == 0) return 0;
1474     if (stream_endpoint->remote_sep.seid > 0x3E) return 0;
1475     return 1;
1476 }
1477 
1478 void avdtp_init(void){
1479     if (!l2cap_registered){
1480         l2cap_registered = true;
1481         l2cap_register_service(&avdtp_packet_handler, BLUETOOTH_PSM_AVDTP, 0xffff, gap_get_security_level());
1482     }
1483 }
1484 
1485 void avdtp_deinit(void){
1486     l2cap_registered = false;
1487     stream_endpoints = NULL;
1488     connections = NULL;
1489     avdtp_sink_handle_media_data = NULL;
1490 
1491     sdp_query_context_avdtp_cid = 0;
1492     stream_endpoints_id_counter = 0;
1493     transaction_id_counter = 0;
1494     avdtp_cid_counter = 0;
1495 }
1496