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