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