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