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