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