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