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