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