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