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