xref: /btstack/src/classic/avdtp.c (revision 2cc827d4920e09c7219a79fceb0577d37efd4025)
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 static void avdtp_handle_close_media_channel(avdtp_stream_endpoint_t * stream_endpoint){
743     avdtp_connection_t * connection = stream_endpoint->connection;
744     btstack_assert(connection != NULL);
745     avdtp_streaming_emit_connection_released(stream_endpoint, connection->avdtp_cid, avdtp_local_seid(stream_endpoint));
746     avdtp_reset_stream_endpoint(stream_endpoint);
747     connection->configuration_state = AVDTP_CONFIGURATION_STATE_IDLE;
748 }
749 
750 static void avdtp_handle_close_recovery_channel(avdtp_stream_endpoint_t * stream_endpoint){
751     log_info("L2CAP_EVENT_CHANNEL_CLOSED recovery cid 0x%0x", stream_endpoint->l2cap_recovery_cid);
752     stream_endpoint->l2cap_recovery_cid = 0;
753 }
754 
755 static void avdtp_handle_close_reporting_channel(avdtp_stream_endpoint_t * stream_endpoint){
756     log_info("L2CAP_EVENT_CHANNEL_CLOSED reporting cid 0x%0x", stream_endpoint->l2cap_reporting_cid);
757     stream_endpoint->l2cap_reporting_cid = 0;
758 }
759 
760 
761 void avdtp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
762     bd_addr_t event_addr;
763     uint16_t psm;
764     uint16_t local_cid;
765     uint8_t  status;
766     uint16_t l2cap_mtu;
767     hci_con_handle_t con_handle;
768 
769     bool accept_streaming_connection;
770     bool outoing_signaling_active;
771     bool decline_connection;
772 
773     avdtp_stream_endpoint_t * stream_endpoint = NULL;
774     avdtp_connection_t * connection = NULL;
775 
776     switch (packet_type) {
777         case L2CAP_DATA_PACKET:
778             connection = avdtp_get_connection_for_l2cap_signaling_cid(channel);
779             if (connection){
780                 handle_l2cap_data_packet_for_signaling_connection(connection, packet, size);
781                 break;
782             }
783 
784             stream_endpoint = avdtp_get_stream_endpoint_for_l2cap_cid(channel);
785             if (!stream_endpoint){
786                 if (!connection) break;
787                 handle_l2cap_data_packet_for_signaling_connection(connection, packet, size);
788                 break;
789             }
790 
791             if (stream_endpoint->connection){
792                 if (channel == stream_endpoint->connection->l2cap_signaling_cid){
793                     handle_l2cap_data_packet_for_signaling_connection(stream_endpoint->connection, packet, size);
794                     break;
795                 }
796             }
797 
798             if (channel == stream_endpoint->l2cap_media_cid){
799                 btstack_assert(avdtp_sink_handle_media_data);
800                 (*avdtp_sink_handle_media_data)(avdtp_local_seid(stream_endpoint), packet, size);
801                 break;
802             }
803 
804             if (channel == stream_endpoint->l2cap_reporting_cid){
805                 log_info("L2CAP_DATA_PACKET for reporting: NOT IMPLEMENTED");
806             } else if (channel == stream_endpoint->l2cap_recovery_cid){
807                 log_info("L2CAP_DATA_PACKET for recovery: NOT IMPLEMENTED");
808             } else {
809                 log_error("avdtp packet handler L2CAP_DATA_PACKET: local cid 0x%02x not found", channel);
810             }
811             break;
812 
813         case HCI_EVENT_PACKET:
814             switch (hci_event_packet_get_type(packet)) {
815 
816                 case L2CAP_EVENT_INCOMING_CONNECTION:
817                     l2cap_event_incoming_connection_get_address(packet, event_addr);
818                     local_cid = l2cap_event_incoming_connection_get_local_cid(packet);
819                     con_handle = l2cap_event_incoming_connection_get_handle(packet);
820                     outoing_signaling_active = false;
821                     accept_streaming_connection = false;
822 
823                     connection = avdtp_get_connection_for_bd_addr(event_addr);
824                     if (connection != NULL){
825                         switch (connection->state){
826                             case AVDTP_SIGNALING_CONNECTION_W4_L2CAP_DISCONNECTED:
827                             case AVDTP_SIGNALING_CONNECTION_W4_L2CAP_CONNECTED:
828                                 outoing_signaling_active = true;
829                                 connection->incoming_declined = true;
830                                 break;
831                             case AVDTP_SIGNALING_CONNECTION_OPENED:
832                                 outoing_signaling_active = true;
833                                 accept_streaming_connection = true;
834                                 break;
835                             default:
836                                 break;
837                         }
838                     }
839                     log_info("incoming: %s, outoing_signaling_active %d, accept_streaming_connection %d",
840                         bd_addr_to_str(event_addr), outoing_signaling_active, accept_streaming_connection);
841 
842                     decline_connection = outoing_signaling_active && !accept_streaming_connection;
843                     if (outoing_signaling_active == false){
844                         connection = avdtp_handle_incoming_connection(connection, event_addr, con_handle, local_cid);
845                         if (connection == NULL){
846                             decline_connection = true;
847                         }
848                     } else if (accept_streaming_connection){
849                         if ((connection == NULL) || (connection->configuration_state != AVDTP_CONFIGURATION_STATE_REMOTE_CONFIGURED)) {
850                             decline_connection = true;
851                         } else {
852                             // now, we're only dealing with media connections that are created by remote side - we're acceptor here
853                             stream_endpoint = avdtp_get_stream_endpoint_for_seid(connection->acceptor_local_seid);
854                             if ((stream_endpoint == NULL) || (stream_endpoint->l2cap_media_cid != 0) ) {
855                                 decline_connection = true;
856                             }
857                         }
858                     }
859 
860                     if (decline_connection){
861                         l2cap_decline_connection(local_cid);
862                     } else {
863                         l2cap_accept_connection(local_cid);
864                     }
865                     break;
866 
867                 case L2CAP_EVENT_CHANNEL_OPENED:
868 
869                     psm = l2cap_event_channel_opened_get_psm(packet);
870                     if (psm != BLUETOOTH_PSM_AVDTP){
871                         log_info("Unexpected PSM - Not implemented yet, avdtp sink: L2CAP_EVENT_CHANNEL_OPENED ");
872                         return;
873                     }
874 
875                     status = l2cap_event_channel_opened_get_status(packet);
876                     // inform about new l2cap connection
877                     l2cap_event_channel_opened_get_address(packet, event_addr);
878                     local_cid = l2cap_event_channel_opened_get_local_cid(packet);
879                     l2cap_mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
880                     connection = avdtp_get_connection_for_bd_addr(event_addr);
881                     if (connection == NULL){
882                         log_info("L2CAP_EVENT_CHANNEL_OPENED: no connection found for %s", bd_addr_to_str(event_addr));
883                         break;
884                     }
885 
886                     con_handle = l2cap_event_channel_opened_get_handle(packet);
887 
888                     switch (connection->state){
889                         case AVDTP_SIGNALING_CONNECTION_W4_L2CAP_CONNECTED:
890                             switch (status){
891                                 case ERROR_CODE_SUCCESS:
892                                     connection->l2cap_signaling_cid = local_cid;
893                                     connection->incoming_declined = false;
894                                     connection->l2cap_mtu = l2cap_mtu;
895                                     connection->con_handle = con_handle;
896                                     connection->state = AVDTP_SIGNALING_CONNECTION_OPENED;
897                                     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);
898                                     avdtp_signaling_emit_connection_established(connection->avdtp_cid, event_addr, con_handle, status);
899                                     return;
900                                 case L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES:
901                                     if (connection->incoming_declined == true) {
902                                         log_info("Connection was declined, and the outgoing failed");
903                                         connection->state = AVDTP_SIGNALING_CONNECTION_W2_L2CAP_RETRY;
904                                         connection->incoming_declined = false;
905                                         avdtp_retry_timer_start(connection);
906                                         return;
907                                     }
908                                     break;
909                                 default:
910                                     log_info("Connection to %s failed. status code 0x%02x", bd_addr_to_str(event_addr), status);
911                                     break;
912                             }
913                             avdtp_signaling_emit_connection_established(connection->avdtp_cid, event_addr, con_handle, status);
914                             avdtp_finalize_connection(connection);
915                             break;
916 
917                         case AVDTP_SIGNALING_CONNECTION_OPENED:
918                             stream_endpoint = avdtp_get_stream_endpoint_for_signaling_cid(connection->l2cap_signaling_cid);
919                             if (!stream_endpoint){
920                                 log_info("L2CAP_EVENT_CHANNEL_OPENED: stream_endpoint not found for signaling cid 0x%02x", connection->l2cap_signaling_cid);
921                                 return;
922                             }
923                             if (status != ERROR_CODE_SUCCESS){
924                                 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));
925                                 stream_endpoint->state = AVDTP_STREAM_ENDPOINT_IDLE;
926                                 avdtp_streaming_emit_connection_established(stream_endpoint, status);
927                                 break;
928                             }
929                             switch (stream_endpoint->state){
930                                 case AVDTP_STREAM_ENDPOINT_W4_L2CAP_FOR_MEDIA_CONNECTED:
931                                     stream_endpoint->state = AVDTP_STREAM_ENDPOINT_OPENED;
932                                     stream_endpoint->l2cap_media_cid = l2cap_event_channel_opened_get_local_cid(packet);
933                                     stream_endpoint->media_con_handle = l2cap_event_channel_opened_get_handle(packet);
934 
935                                     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));
936                                     avdtp_streaming_emit_connection_established(stream_endpoint, ERROR_CODE_SUCCESS);
937                                     break;
938                                 default:
939                                     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));
940                                     avdtp_streaming_emit_connection_established(stream_endpoint, ERROR_CODE_COMMAND_DISALLOWED);
941                                     break;
942                             }
943                             break;
944 
945                         default:
946                             log_info("L2CAP connection to %s ignored: status code 0x%02x, connection state %d", bd_addr_to_str(event_addr), status, connection->state);
947                             break;
948                     }
949                     break;
950 
951                 case L2CAP_EVENT_CHANNEL_CLOSED:
952                     local_cid = l2cap_event_channel_closed_get_local_cid(packet);
953                     stream_endpoint = avdtp_get_stream_endpoint_for_l2cap_cid(local_cid);
954                     connection = avdtp_get_connection_for_l2cap_signaling_cid(local_cid);
955 
956                     log_info("Received L2CAP_EVENT_CHANNEL_CLOSED, cid 0x%2x, connection %p, stream_endpoint %p", local_cid, connection, stream_endpoint);
957 
958                     if (stream_endpoint){
959                         if (stream_endpoint->l2cap_media_cid == local_cid){
960                             avdtp_handle_close_media_channel(stream_endpoint);
961                             break;
962                         }
963                         if (stream_endpoint->l2cap_recovery_cid == local_cid){
964                             avdtp_handle_close_recovery_channel(stream_endpoint);
965                             break;
966                         }
967                         if (stream_endpoint->l2cap_reporting_cid == local_cid){
968                             avdtp_handle_close_reporting_channel(stream_endpoint);
969                             break;
970                         }
971                     }
972 
973                     if (connection){
974                         // closing signaling channel invalidates all other channels as well
975                         btstack_linked_list_iterator_t it;
976                         btstack_linked_list_iterator_init(&it, avdtp_get_stream_endpoints());
977                         while (btstack_linked_list_iterator_has_next(&it)){
978                             stream_endpoint = (avdtp_stream_endpoint_t *)btstack_linked_list_iterator_next(&it);
979                             if (stream_endpoint->connection == connection){
980                                 avdtp_handle_close_recovery_channel(stream_endpoint);
981                                 avdtp_handle_close_reporting_channel(stream_endpoint);
982                                 avdtp_handle_close_media_channel(stream_endpoint);
983                                 avdtp_reset_stream_endpoint(stream_endpoint);
984                             }
985                         }
986                         avdtp_signaling_emit_connection_released(connection->avdtp_cid);
987                         avdtp_finalize_connection(connection);
988                         break;
989                     }
990                     break;
991 
992                 case L2CAP_EVENT_CAN_SEND_NOW:
993                     log_debug("avdtp_packet_handler, L2CAP_EVENT_CAN_SEND_NOW l2cap_cid 0x%02x", channel);
994 					avdtp_handle_can_send_now(channel);
995                     break;
996                 default:
997                     log_info("Unknown HCI event type %02x", hci_event_packet_get_type(packet));
998                     break;
999             }
1000             break;
1001 
1002         default:
1003             // other packet type
1004             break;
1005     }
1006 }
1007 
1008 uint8_t avdtp_disconnect(uint16_t avdtp_cid){
1009     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1010     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1011 
1012     if (connection->state == AVDTP_SIGNALING_CONNECTION_W4_L2CAP_DISCONNECTED) return ERROR_CODE_SUCCESS;
1013 
1014     btstack_linked_list_iterator_t it;
1015     btstack_linked_list_iterator_init(&it, avdtp_get_stream_endpoints());
1016 
1017     while (btstack_linked_list_iterator_has_next(&it)){
1018         avdtp_stream_endpoint_t * stream_endpoint = (avdtp_stream_endpoint_t *)btstack_linked_list_iterator_next(&it);
1019         if (stream_endpoint->connection != connection) continue;
1020 
1021         switch (stream_endpoint->state){
1022             case AVDTP_STREAM_ENDPOINT_OPENED:
1023             case AVDTP_STREAM_ENDPOINT_STREAMING:
1024                 stream_endpoint->state = AVDTP_STREAM_ENDPOINT_W4_L2CAP_FOR_MEDIA_DISCONNECTED;
1025                 l2cap_disconnect(stream_endpoint->l2cap_media_cid, 0);
1026                 break;
1027             default:
1028                 break;
1029         }
1030     }
1031 
1032     connection->state = AVDTP_SIGNALING_CONNECTION_W4_L2CAP_DISCONNECTED;
1033     l2cap_disconnect(connection->l2cap_signaling_cid, 0);
1034     return ERROR_CODE_SUCCESS;
1035 }
1036 
1037 uint8_t avdtp_open_stream(uint16_t avdtp_cid, uint8_t local_seid, uint8_t remote_seid){
1038     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1039     if (!connection){
1040         log_error("avdtp_media_connect: no connection for signaling cid 0x%02x found", avdtp_cid);
1041         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1042     }
1043 
1044     if (connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) {
1045         log_error("avdtp_media_connect: wrong connection state %d", connection->state);
1046         return ERROR_CODE_COMMAND_DISALLOWED;
1047     }
1048 
1049     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1050     if (!stream_endpoint) {
1051         log_error("avdtp_media_connect: no stream_endpoint with seid %d found", local_seid);
1052         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1053     }
1054 
1055     if (stream_endpoint->remote_sep.seid != remote_seid){
1056         log_error("avdtp_media_connect: no remote sep with seid %d registered with the stream endpoint", remote_seid);
1057         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1058     }
1059 
1060     if (stream_endpoint->state < AVDTP_STREAM_ENDPOINT_CONFIGURED) return ERROR_CODE_COMMAND_DISALLOWED;
1061 
1062     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1063     connection->initiator_remote_seid = remote_seid;
1064     connection->initiator_local_seid = local_seid;
1065     stream_endpoint->initiator_config_state = AVDTP_INITIATOR_W2_OPEN_STREAM;
1066     stream_endpoint->state = AVDTP_STREAM_ENDPOINT_W2_REQUEST_OPEN_STREAM;
1067 	avdtp_request_can_send_now_initiator(connection);
1068     return ERROR_CODE_SUCCESS;
1069 }
1070 
1071 uint8_t avdtp_start_stream(uint16_t avdtp_cid, uint8_t local_seid){
1072     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1073     if (!connection){
1074         log_error("avdtp_start_stream: no connection for signaling cid 0x%02x found", avdtp_cid);
1075         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1076     }
1077 
1078     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1079     if (!stream_endpoint) {
1080         log_error("avdtp_start_stream: no stream_endpoint with seid %d found", local_seid);
1081         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1082     }
1083 
1084     if (stream_endpoint->l2cap_media_cid == 0){
1085         log_error("avdtp_start_stream: no media connection for stream_endpoint with seid %d found", local_seid);
1086         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1087     }
1088 
1089     if (!is_avdtp_remote_seid_registered(stream_endpoint)){
1090         log_error("avdtp_media_connect: no remote sep registered with the stream endpoint");
1091         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1092     }
1093 
1094     if (!is_avdtp_remote_seid_registered(stream_endpoint) || stream_endpoint->start_stream == 1){
1095         return ERROR_CODE_COMMAND_DISALLOWED;
1096     }
1097 
1098     stream_endpoint->start_stream = 1;
1099     connection->initiator_local_seid = local_seid;
1100     connection->initiator_remote_seid = stream_endpoint->remote_sep.seid;
1101 	avdtp_request_can_send_now_initiator(connection);
1102     return ERROR_CODE_SUCCESS;
1103 }
1104 
1105 uint8_t avdtp_stop_stream(uint16_t avdtp_cid, uint8_t local_seid){
1106     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1107     if (!connection){
1108         log_error("avdtp_stop_stream: no connection for signaling cid 0x%02x found", avdtp_cid);
1109         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1110     }
1111 
1112     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1113     if (!stream_endpoint) {
1114         log_error("avdtp_stop_stream: no stream_endpoint with seid %d found", local_seid);
1115         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1116     }
1117 
1118     if (stream_endpoint->l2cap_media_cid == 0){
1119         log_error("avdtp_stop_stream: no media connection for stream_endpoint with seid %d found", local_seid);
1120         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1121     }
1122 
1123     if (!is_avdtp_remote_seid_registered(stream_endpoint) || stream_endpoint->close_stream){
1124         return ERROR_CODE_COMMAND_DISALLOWED;
1125     }
1126 
1127     stream_endpoint->close_stream = 1;
1128     connection->initiator_local_seid = local_seid;
1129     connection->initiator_remote_seid = stream_endpoint->remote_sep.seid;
1130 	avdtp_request_can_send_now_initiator(connection);
1131     return ERROR_CODE_SUCCESS;
1132 }
1133 
1134 uint8_t avdtp_abort_stream(uint16_t avdtp_cid, uint8_t local_seid){
1135     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1136     if (!connection){
1137         log_error("avdtp_abort_stream: no connection for signaling cid 0x%02x found", avdtp_cid);
1138         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1139     }
1140 
1141     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1142     if (!stream_endpoint) {
1143         log_error("avdtp_abort_stream: no stream_endpoint with seid %d found", local_seid);
1144         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1145     }
1146 
1147     if (stream_endpoint->l2cap_media_cid == 0){
1148         log_error("avdtp_abort_stream: no media connection for stream_endpoint with seid %d found", local_seid);
1149         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1150     }
1151 
1152     if (!is_avdtp_remote_seid_registered(stream_endpoint) || stream_endpoint->abort_stream){
1153         return ERROR_CODE_COMMAND_DISALLOWED;
1154     }
1155 
1156     stream_endpoint->abort_stream = 1;
1157     connection->initiator_local_seid = local_seid;
1158     connection->initiator_remote_seid = stream_endpoint->remote_sep.seid;
1159 	avdtp_request_can_send_now_initiator(connection);
1160     return ERROR_CODE_SUCCESS;
1161 }
1162 
1163 uint8_t avdtp_suspend_stream(uint16_t avdtp_cid, uint8_t local_seid){
1164     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1165     if (!connection){
1166         log_error("avdtp_suspend_stream: no connection for signaling cid 0x%02x found", avdtp_cid);
1167         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1168     }
1169     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1170     if (!stream_endpoint) {
1171         log_error("avdtp_suspend_stream: no stream_endpoint with seid %d found", local_seid);
1172         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1173     }
1174 
1175     if (stream_endpoint->l2cap_media_cid == 0){
1176         log_error("avdtp_suspend_stream: no media connection for stream_endpoint with seid %d found", local_seid);
1177         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1178     }
1179 
1180     if (!is_avdtp_remote_seid_registered(stream_endpoint) || stream_endpoint->suspend_stream){
1181         return ERROR_CODE_COMMAND_DISALLOWED;
1182     }
1183 
1184     stream_endpoint->suspend_stream = 1;
1185     connection->initiator_local_seid = local_seid;
1186     connection->initiator_remote_seid = stream_endpoint->remote_sep.seid;
1187 	avdtp_request_can_send_now_initiator(connection);
1188     return ERROR_CODE_SUCCESS;
1189 }
1190 
1191 uint8_t avdtp_discover_stream_endpoints(uint16_t avdtp_cid){
1192     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1193     if (!connection){
1194         log_error("avdtp_discover_stream_endpoints: no connection for signaling cid 0x%02x found", avdtp_cid);
1195         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1196     }
1197     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1198         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1199         return ERROR_CODE_COMMAND_DISALLOWED;
1200     }
1201 
1202     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1203     connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_DISCOVER_SEPS;
1204     return avdtp_request_can_send_now_initiator(connection);
1205 }
1206 
1207 
1208 uint8_t avdtp_get_capabilities(uint16_t avdtp_cid, uint8_t remote_seid){
1209     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1210     if (!connection){
1211         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1212         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1213     }
1214     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1215         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1216         return ERROR_CODE_COMMAND_DISALLOWED;
1217     }
1218 
1219     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1220     connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_CAPABILITIES;
1221     connection->initiator_remote_seid = remote_seid;
1222     return avdtp_request_can_send_now_initiator(connection);
1223 }
1224 
1225 
1226 uint8_t avdtp_get_all_capabilities(uint16_t avdtp_cid, uint8_t remote_seid){
1227     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1228     if (!connection){
1229         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1230         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1231     }
1232     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1233         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1234         return ERROR_CODE_COMMAND_DISALLOWED;
1235     }
1236 
1237     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1238     connection->initiator_remote_seid = remote_seid;
1239 
1240     if (connection->avdtp_version == 0){
1241         connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_SEND_SDP_QUERY_THEN_GET_ALL_CAPABILITIES;
1242         avdtp_handle_sdp_client_query_request.callback = &avdtp_handle_start_sdp_client_query;
1243         // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1244         (void) sdp_client_register_query_callback(&avdtp_handle_sdp_client_query_request);
1245         return ERROR_CODE_SUCCESS;
1246     } else {
1247         // AVDTP version lower then 1.3 supports only get capabilities command
1248         if (connection->avdtp_version < 0x103){
1249             connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_CAPABILITIES;
1250         } else {
1251             connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_ALL_CAPABILITIES;
1252         }
1253         return avdtp_request_can_send_now_initiator(connection);
1254     }
1255 }
1256 
1257 uint8_t avdtp_get_configuration(uint16_t avdtp_cid, uint8_t remote_seid){
1258     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1259     if (!connection){
1260         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1261         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1262     }
1263     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1264         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1265         return ERROR_CODE_COMMAND_DISALLOWED;
1266     }
1267 
1268     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1269     connection->initiator_connection_state = AVDTP_SIGNALING_CONNECTION_INITIATOR_W2_GET_CONFIGURATION;
1270     connection->initiator_remote_seid = remote_seid;
1271     return avdtp_request_can_send_now_initiator(connection);
1272 }
1273 
1274 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){
1275     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1276     if (!connection){
1277         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1278         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1279     }
1280     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1281         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1282         log_error("connection in wrong state, %d, initiator state %d", connection->state, connection->initiator_connection_state);
1283         return ERROR_CODE_COMMAND_DISALLOWED;
1284     }
1285     if (connection->configuration_state != AVDTP_CONFIGURATION_STATE_IDLE){
1286         log_info("configuration already started, config state %u", connection->configuration_state);
1287         return ERROR_CODE_COMMAND_DISALLOWED;
1288     }
1289 
1290     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1291     if (!stream_endpoint) {
1292         log_error("No initiator stream endpoint for seid %d", local_seid);
1293         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1294     }
1295     if (stream_endpoint->state >= AVDTP_STREAM_ENDPOINT_CONFIGURED){
1296         log_error("Stream endpoint seid %d in wrong state %d", local_seid, stream_endpoint->state);
1297         return ERROR_CODE_COMMAND_DISALLOWED;
1298     }
1299 
1300     connection->active_stream_endpoint = (void*) stream_endpoint;
1301     connection->configuration_state = AVDTP_CONFIGURATION_STATE_LOCAL_INITIATED;
1302 
1303     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1304     connection->initiator_remote_seid = remote_seid;
1305     connection->initiator_local_seid = local_seid;
1306     stream_endpoint->remote_configuration_bitmap = configured_services_bitmap;
1307     stream_endpoint->remote_configuration = configuration;
1308     stream_endpoint->initiator_config_state = AVDTP_INITIATOR_W2_SET_CONFIGURATION;
1309 
1310 	log_debug("SE %p, initiator_config_state: 0x%02x", stream_endpoint, stream_endpoint->initiator_config_state);
1311 
1312     return avdtp_request_can_send_now_initiator(connection);
1313 }
1314 
1315 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){
1316     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1317     if (!connection){
1318         log_error("No connection for AVDTP cid 0x%02x found", avdtp_cid);
1319         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1320     }
1321     //TODO: if opened only app capabilities, enable reconfigure for not opened
1322     if ((connection->state != AVDTP_SIGNALING_CONNECTION_OPENED) ||
1323         (connection->initiator_connection_state != AVDTP_SIGNALING_CONNECTION_INITIATOR_IDLE)) {
1324         return ERROR_CODE_COMMAND_DISALLOWED;
1325     }
1326 
1327     avdtp_stream_endpoint_t * stream_endpoint = avdtp_get_stream_endpoint_for_seid(local_seid);
1328     if (!stream_endpoint) {
1329         log_error("avdtp_reconfigure: no initiator stream endpoint for seid %d", local_seid);
1330         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1331     }
1332 
1333     if (!is_avdtp_remote_seid_registered(stream_endpoint)){
1334         log_error("avdtp_reconfigure: no associated remote sep");
1335         return ERROR_CODE_COMMAND_DISALLOWED;
1336     }
1337 
1338     connection->initiator_transaction_label= avdtp_get_next_transaction_label();
1339     connection->initiator_remote_seid = remote_seid;
1340     connection->initiator_local_seid = local_seid;
1341     stream_endpoint->remote_configuration_bitmap = configured_services_bitmap;
1342     stream_endpoint->remote_configuration = configuration;
1343     stream_endpoint->initiator_config_state = AVDTP_INITIATOR_W2_RECONFIGURE_STREAM_WITH_SEID;
1344     return avdtp_request_can_send_now_initiator(connection);
1345 }
1346 
1347 void    avdtp_set_preferred_sampling_frequeny(avdtp_stream_endpoint_t * stream_endpoint, uint32_t sampling_frequency){
1348     stream_endpoint->preferred_sampling_frequency = sampling_frequency;
1349 }
1350 
1351 void    avdtp_set_preferred_channel_mode(avdtp_stream_endpoint_t * stream_endpoint, uint8_t channel_mode){
1352     stream_endpoint->preferred_channel_mode = channel_mode;
1353 }
1354 
1355 
1356 avdtp_channel_mode_t avdtp_choose_sbc_channel_mode(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_channel_mode_bitmap){
1357     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1358     uint8_t channel_mode_bitmap = (media_codec[0] & 0x0F) & remote_channel_mode_bitmap;
1359 
1360     // use preferred channel mode if possible
1361     if (stream_endpoint->preferred_channel_mode == AVDTP_SBC_JOINT_STEREO){
1362         return AVDTP_CHANNEL_MODE_JOINT_STEREO;
1363     }
1364     if (stream_endpoint->preferred_channel_mode == AVDTP_SBC_STEREO){
1365         return AVDTP_CHANNEL_MODE_STEREO;
1366     }
1367     if (stream_endpoint->preferred_channel_mode == AVDTP_SBC_DUAL_CHANNEL){
1368         return AVDTP_CHANNEL_MODE_DUAL_CHANNEL;
1369     }
1370     if (stream_endpoint->preferred_channel_mode == AVDTP_SBC_MONO){
1371         return AVDTP_CHANNEL_MODE_MONO;
1372     }
1373 
1374 
1375     if (channel_mode_bitmap & AVDTP_SBC_JOINT_STEREO){
1376         return AVDTP_CHANNEL_MODE_JOINT_STEREO;
1377     } else if (channel_mode_bitmap & AVDTP_SBC_STEREO){
1378         return AVDTP_CHANNEL_MODE_STEREO;
1379     } else if (channel_mode_bitmap & AVDTP_SBC_DUAL_CHANNEL){
1380         return AVDTP_CHANNEL_MODE_DUAL_CHANNEL;
1381     } else if (channel_mode_bitmap & AVDTP_SBC_MONO){
1382         return AVDTP_CHANNEL_MODE_MONO;
1383     }
1384     return AVDTP_CHANNEL_MODE_JOINT_STEREO;
1385 }
1386 
1387 avdtp_sbc_allocation_method_t avdtp_choose_sbc_allocation_method(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_allocation_method_bitmap){
1388     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1389     uint8_t allocation_method_bitmap = (media_codec[1] & 0x03) & remote_allocation_method_bitmap;
1390 
1391     avdtp_sbc_allocation_method_t allocation_method = AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS;
1392     if (allocation_method_bitmap & AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS){
1393         allocation_method = AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS;
1394     } else if (allocation_method_bitmap & AVDTP_SBC_ALLOCATION_METHOD_SNR){
1395         allocation_method = AVDTP_SBC_ALLOCATION_METHOD_SNR;
1396     }
1397     return allocation_method;
1398 }
1399 
1400 uint8_t avdtp_stream_endpoint_seid(avdtp_stream_endpoint_t * stream_endpoint){
1401     if (!stream_endpoint) return 0;
1402     return stream_endpoint->sep.seid;
1403 }
1404 uint8_t avdtp_choose_sbc_subbands(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_subbands_bitmap){
1405     if (!stream_endpoint) return 0;
1406     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1407     uint8_t subbands_bitmap = ((media_codec[1] >> 2) & 0x03) & remote_subbands_bitmap;
1408 
1409     uint8_t subbands = AVDTP_SBC_SUBBANDS_8;
1410     if (subbands_bitmap & AVDTP_SBC_SUBBANDS_8){
1411         subbands = AVDTP_SBC_SUBBANDS_8;
1412     } else if (subbands_bitmap & AVDTP_SBC_SUBBANDS_4){
1413         subbands = AVDTP_SBC_SUBBANDS_4;
1414     }
1415     return subbands;
1416 }
1417 
1418 uint8_t avdtp_choose_sbc_block_length(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_block_length_bitmap){
1419     if (!stream_endpoint) return 0;
1420     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1421     uint8_t block_length_bitmap = (media_codec[1] >> 4) & remote_block_length_bitmap;
1422 
1423     uint8_t block_length = AVDTP_SBC_BLOCK_LENGTH_16;
1424     if (block_length_bitmap & AVDTP_SBC_BLOCK_LENGTH_16){
1425         block_length = AVDTP_SBC_BLOCK_LENGTH_16;
1426     } else if (block_length_bitmap & AVDTP_SBC_BLOCK_LENGTH_12){
1427         block_length = AVDTP_SBC_BLOCK_LENGTH_12;
1428     } else if (block_length_bitmap & AVDTP_SBC_BLOCK_LENGTH_8){
1429         block_length = AVDTP_SBC_BLOCK_LENGTH_8;
1430     } else if (block_length_bitmap & AVDTP_SBC_BLOCK_LENGTH_4){
1431         block_length = AVDTP_SBC_BLOCK_LENGTH_4;
1432     }
1433     return block_length;
1434 }
1435 
1436 uint16_t avdtp_choose_sbc_sampling_frequency(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_sampling_frequency_bitmap){
1437     if (!stream_endpoint) return 0;
1438     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1439     uint8_t supported_sampling_frequency_bitmap = (media_codec[0] >> 4) & remote_sampling_frequency_bitmap;
1440 
1441     // use preferred sampling frequency if possible
1442     if ((stream_endpoint->preferred_sampling_frequency == 48000) && (supported_sampling_frequency_bitmap & AVDTP_SBC_48000)){
1443         return stream_endpoint->preferred_sampling_frequency;
1444     }
1445     if ((stream_endpoint->preferred_sampling_frequency == 44100) && (supported_sampling_frequency_bitmap & AVDTP_SBC_44100)){
1446         return stream_endpoint->preferred_sampling_frequency;
1447     }
1448     if ((stream_endpoint->preferred_sampling_frequency == 32000) && (supported_sampling_frequency_bitmap & AVDTP_SBC_32000)){
1449         return stream_endpoint->preferred_sampling_frequency;
1450     }
1451     if ((stream_endpoint->preferred_sampling_frequency == 16000) && (supported_sampling_frequency_bitmap & AVDTP_SBC_16000)){
1452         return stream_endpoint->preferred_sampling_frequency;
1453     }
1454 
1455     // otherwise, use highest available
1456     if (supported_sampling_frequency_bitmap & AVDTP_SBC_48000){
1457         return 48000;
1458     }
1459     if (supported_sampling_frequency_bitmap & AVDTP_SBC_44100){
1460         return 44100;
1461     }
1462     if (supported_sampling_frequency_bitmap & AVDTP_SBC_32000){
1463         return 32000;
1464     }
1465     if (supported_sampling_frequency_bitmap & AVDTP_SBC_16000){
1466         return 16000;
1467     }
1468     return 44100; // some default
1469 }
1470 
1471 uint8_t avdtp_choose_sbc_max_bitpool_value(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_max_bitpool_value){
1472     if (!stream_endpoint) return 0;
1473     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1474     return btstack_min(media_codec[3], remote_max_bitpool_value);
1475 }
1476 
1477 uint8_t avdtp_choose_sbc_min_bitpool_value(avdtp_stream_endpoint_t * stream_endpoint, uint8_t remote_min_bitpool_value){
1478     if (!stream_endpoint) return 0;
1479     uint8_t * media_codec = stream_endpoint->sep.capabilities.media_codec.media_codec_information;
1480     return btstack_max(media_codec[2], remote_min_bitpool_value);
1481 }
1482 
1483 uint8_t is_avdtp_remote_seid_registered(avdtp_stream_endpoint_t * stream_endpoint){
1484     if (!stream_endpoint) return 0;
1485     if (stream_endpoint->remote_sep.seid == 0) return 0;
1486     if (stream_endpoint->remote_sep.seid > 0x3E) return 0;
1487     return 1;
1488 }
1489 
1490 void avdtp_init(void){
1491     if (!l2cap_registered){
1492         l2cap_registered = true;
1493         l2cap_register_service(&avdtp_packet_handler, BLUETOOTH_PSM_AVDTP, 0xffff, gap_get_security_level());
1494     }
1495 }
1496 
1497 void avdtp_deinit(void){
1498     l2cap_registered = false;
1499     stream_endpoints = NULL;
1500     connections = NULL;
1501     avdtp_sink_handle_media_data = NULL;
1502 
1503     sdp_query_context_avdtp_cid = 0;
1504     stream_endpoints_id_counter = 0;
1505     transaction_id_counter = 0;
1506     avdtp_cid_counter = 0;
1507 }
1508