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