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