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