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