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