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