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