xref: /btstack/src/classic/a2dp_source.c (revision 80555d912ab413d317cc68162576a3f5febb670b)
1 
2 /*
3  * Copyright (C) 2016 BlueKitchen GmbH
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Neither the name of the copyright holders nor the names of
15  *    contributors may be used to endorse or promote products derived
16  *    from this software without specific prior written permission.
17  * 4. Any redistribution, use, or modification is done solely for
18  *    personal benefit and not for any commercial purpose or for
19  *    monetary gain.
20  *
21  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
25  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
28  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
31  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * Please inquire about commercial licensing options at
35  * [email protected]
36  *
37  */
38 
39 /**
40  * Supported use cases:
41  * - single incoming connection: sep discovery starts and stream will get setup if remote sink sep with SBC is found
42  * - single outgoing connection: see above
43  * - outgoing and incoming connection to same device:
44  *    - if outgoing is triggered first, incoming will get ignored.
45  *    - if incoming starts first, start ougoing will fail, but incoming will succeed.
46  * - outgoing and incoming connections to different devices:
47  *    - if outgoing is first, incoming gets ignored.
48  *    - if incoming starts first SEP discovery will get stopped and outgoing will succeed.
49  */
50 
51 #define BTSTACK_FILE__ "a2dp_source.c"
52 
53 #include <stdint.h>
54 #include <string.h>
55 
56 #include "bluetooth_psm.h"
57 #include "bluetooth_sdp.h"
58 #include "btstack_debug.h"
59 #include "btstack_event.h"
60 #include "classic/a2dp_source.h"
61 #include "classic/avdtp_source.h"
62 #include "classic/avdtp_util.h"
63 #include "classic/sdp_util.h"
64 #include "l2cap.h"
65 
66 #define AVDTP_MAX_SEP_NUM 10
67 #define A2DP_SET_CONFIG_DELAY_MS 150
68 
69 static const char * default_a2dp_source_service_name = "BTstack A2DP Source Service";
70 static const char * default_a2dp_source_service_provider_name = "BTstack A2DP Source Service Provider";
71 static btstack_timer_source_t a2dp_source_set_config_timer;
72 
73 //
74 static bool     outgoing_active;
75 
76 // discover remote seps
77 static a2dp_state_t a2dp_source_state = A2DP_IDLE;
78 static uint16_t     a2dp_source_cid;
79 static uint16_t     num_remote_seps = 0;
80 static avdtp_sep_t  remote_seps[AVDTP_MAX_SEP_NUM];
81 static bool a2dp_source_have_config;
82 
83 static bool stream_endpoint_configured = false;
84 
85 static avdtp_stream_endpoint_context_t sc;
86 static btstack_packet_handler_t a2dp_source_packet_handler_user;
87 
88 static void a2dp_source_packet_handler_internal(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
89 static void a2dp_discover_seps_with_next_waiting_connection(void);
90 
91 static void a2dp_source_streaming_emit_connection_failed(avdtp_connection_t * connection, uint8_t local_seid, uint8_t status) {
92     uint8_t event[14];
93     int pos = 0;
94     event[pos++] = HCI_EVENT_A2DP_META;
95     event[pos++] = sizeof(event) - 2;
96     event[pos++] = A2DP_SUBEVENT_STREAM_ESTABLISHED;
97     little_endian_store_16(event, pos, connection->avdtp_cid);
98     pos += 2;
99     reverse_bd_addr(connection->remote_addr, &event[pos]);
100     pos += 6;
101     event[pos++] = local_seid;
102     event[pos++] = 0;
103     event[pos++] = status;
104 
105     (*a2dp_source_packet_handler_user)(HCI_EVENT_PACKET, 0, event, sizeof(event));
106 }
107 
108 void a2dp_source_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint16_t supported_features, const char * service_name, const char * service_provider_name){
109     uint8_t* attribute;
110     de_create_sequence(service);
111 
112     // 0x0000 "Service Record Handle"
113     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
114     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
115 
116     // 0x0001 "Service Class ID List"
117     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
118     attribute = de_push_sequence(service);
119     {
120         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AUDIO_SOURCE);
121     }
122     de_pop_sequence(service, attribute);
123 
124     // 0x0004 "Protocol Descriptor List"
125     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
126     attribute = de_push_sequence(service);
127     {
128         uint8_t* l2cpProtocol = de_push_sequence(attribute);
129         {
130             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
131             de_add_number(l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PSM_AVDTP);
132         }
133         de_pop_sequence(attribute, l2cpProtocol);
134 
135         uint8_t* avProtocol = de_push_sequence(attribute);
136         {
137             de_add_number(avProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVDTP);  // avProtocol_service
138             de_add_number(avProtocol,  DE_UINT, DE_SIZE_16,  0x0103);  // version
139         }
140         de_pop_sequence(attribute, avProtocol);
141     }
142     de_pop_sequence(service, attribute);
143 
144     // 0x0005 "Public Browse Group"
145     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
146     attribute = de_push_sequence(service);
147     {
148         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
149     }
150     de_pop_sequence(service, attribute);
151 
152     // 0x0009 "Bluetooth Profile Descriptor List"
153     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
154     attribute = de_push_sequence(service);
155     {
156         uint8_t *a2dProfile = de_push_sequence(attribute);
157         {
158             de_add_number(a2dProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_ADVANCED_AUDIO_DISTRIBUTION);
159             de_add_number(a2dProfile,  DE_UINT, DE_SIZE_16, 0x0103);
160         }
161         de_pop_sequence(attribute, a2dProfile);
162     }
163     de_pop_sequence(service, attribute);
164 
165 
166     // 0x0100 "Service Name"
167     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
168     if (service_name){
169         de_add_data(service,  DE_STRING, strlen(service_name), (uint8_t *) service_name);
170     } else {
171         de_add_data(service,  DE_STRING, strlen(default_a2dp_source_service_name), (uint8_t *) default_a2dp_source_service_name);
172     }
173 
174     // 0x0100 "Provider Name"
175     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0102);
176     if (service_provider_name){
177         de_add_data(service,  DE_STRING, strlen(service_provider_name), (uint8_t *) service_provider_name);
178     } else {
179         de_add_data(service,  DE_STRING, strlen(default_a2dp_source_service_provider_name), (uint8_t *) default_a2dp_source_service_provider_name);
180     }
181 
182     // 0x0311 "Supported Features"
183     de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);
184     de_add_number(service, DE_UINT, DE_SIZE_16, supported_features);
185 }
186 
187 static void a2dp_signaling_emit_reconfigured(uint16_t cid, uint8_t local_seid, uint8_t status){
188     uint8_t event[7];
189     int pos = 0;
190     event[pos++] = HCI_EVENT_A2DP_META;
191     event[pos++] = sizeof(event) - 2;
192     event[pos++] = A2DP_SUBEVENT_STREAM_RECONFIGURED;
193     little_endian_store_16(event, pos, cid);
194     pos += 2;
195     event[pos++] = local_seid;
196     event[pos++] = status;
197     (*a2dp_source_packet_handler_user)(HCI_EVENT_PACKET, 0, event, sizeof(event));
198 }
199 
200 static void a2dp_source_discover_stream_endpoints(uint16_t avdtp_cid){
201     a2dp_source_cid = avdtp_cid;
202     avdtp_source_discover_stream_endpoints(avdtp_cid);
203 }
204 
205 static void a2dp_source_set_config_timer_handler(btstack_timer_source_t * timer){
206     if (stream_endpoint_configured) return;
207 
208     uint16_t avdtp_cid = (uint16_t)(uintptr_t) btstack_run_loop_get_timer_context(timer);
209 	avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
210 	btstack_run_loop_set_timer_context(&a2dp_source_set_config_timer, NULL);
211 
212     if (connection == NULL) {
213         log_info("a2dp_discover_seps_with_next_waiting_connection");
214         a2dp_discover_seps_with_next_waiting_connection();
215         return;
216     }
217 
218     a2dp_source_discover_stream_endpoints(avdtp_cid);
219 }
220 
221 static void a2dp_source_set_config_timer_start(uint16_t avdtp_cid){
222     log_info("a2dp_source_set_config_timer_start cid 0%02x", avdtp_cid);
223     btstack_run_loop_remove_timer(&a2dp_source_set_config_timer);
224     btstack_run_loop_set_timer_handler(&a2dp_source_set_config_timer,a2dp_source_set_config_timer_handler);
225     btstack_run_loop_set_timer(&a2dp_source_set_config_timer, A2DP_SET_CONFIG_DELAY_MS);
226     btstack_run_loop_set_timer_context(&a2dp_source_set_config_timer, (void *)(uintptr_t)avdtp_cid);
227     btstack_run_loop_add_timer(&a2dp_source_set_config_timer);
228 }
229 
230 static void a2dp_source_set_config_timer_stop(void){
231     log_info("a2dp_source_set_config_timer_stop");
232     btstack_run_loop_remove_timer(&a2dp_source_set_config_timer);
233 	btstack_run_loop_set_timer_context(&a2dp_source_set_config_timer, NULL);
234 }
235 
236 static void a2dp_start_discovering_seps(avdtp_connection_t * connection){
237     a2dp_source_state = A2DP_DISCOVER_SEPS;
238     sc.active_remote_sep_index = 0;
239     num_remote_seps = 0;
240     memset(remote_seps, 0, sizeof(avdtp_sep_t) * AVDTP_MAX_SEP_NUM);
241     connection->a2dp_source_discover_seps = false;
242 
243     // if we initiated the connection, start config right away, else wait a bit to give remote a chance to do it first
244     if (outgoing_active && (a2dp_source_cid == connection->avdtp_cid)){
245         log_info("discover seps");
246         a2dp_source_discover_stream_endpoints(connection->avdtp_cid);
247     } else {
248         log_info("wait a bit, then discover seps");
249         a2dp_source_set_config_timer_start(connection->avdtp_cid);
250     }
251 }
252 
253 static void a2dp_discover_seps_with_next_waiting_connection(void){
254     a2dp_source_state = A2DP_IDLE;
255 
256     btstack_linked_list_iterator_t it;
257     btstack_linked_list_iterator_init(&it, avdtp_get_connections());
258     while (btstack_linked_list_iterator_has_next(&it)){
259         avdtp_connection_t * next_connection = (avdtp_connection_t *)btstack_linked_list_iterator_next(&it);
260         if (!next_connection->a2dp_source_discover_seps) continue;
261         a2dp_start_discovering_seps(next_connection);
262     }
263 }
264 
265 static void a2dp_source_packet_handler_internal(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
266     UNUSED(channel);
267     UNUSED(size);
268 
269     uint16_t cid;
270     avdtp_connection_t * connection;
271 
272     uint8_t signal_identifier;
273     uint8_t status;
274     uint8_t remote_seid;
275 
276     if (packet_type != HCI_EVENT_PACKET) return;
277     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVDTP_META) return;
278 
279     switch (packet[2]){
280         case AVDTP_SUBEVENT_SIGNALING_CONNECTION_ESTABLISHED:
281             if (sc.local_stream_endpoint == NULL) return;
282 
283             cid = avdtp_subevent_signaling_connection_established_get_avdtp_cid(packet);
284             connection = avdtp_get_connection_for_avdtp_cid(cid);
285             btstack_assert(connection != NULL);
286 
287             status = avdtp_subevent_signaling_connection_established_get_status(packet);
288             if (status != ERROR_CODE_SUCCESS){
289                 // notify about connection error only if we're initiator
290                 if (outgoing_active && (a2dp_source_cid == cid)){
291                     log_info("A2DP source signaling connection failed status 0x%02x", status);
292                     outgoing_active = false;
293                     a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_CONNECTION_ESTABLISHED);
294                 }
295                 break;
296             }
297             log_info("A2DP source signaling connection established avdtp_cid 0x%02x", cid);
298 
299             // notify app
300             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_CONNECTION_ESTABLISHED);
301 
302             // we already have a valid setup
303             if (stream_endpoint_configured) return;
304 
305             // start discover seps now if:
306             // - outgoing active: signaling for outgoing connection
307             // - outgoing not active: incoming connection and no sep discover ongoing
308 
309             log_info("outgoing_active %d, current avdtp cid 0x%02x, a2dp_source_state %d", outgoing_active, cid, a2dp_source_state);
310             if ((outgoing_active && (a2dp_source_cid == cid)) || (!outgoing_active && (a2dp_source_state == A2DP_IDLE))){
311                 a2dp_start_discovering_seps(connection);
312             } else {
313                 // post-pone sep discovery
314                 connection->a2dp_source_discover_seps = true;
315             }
316             break;
317 
318         case AVDTP_SUBEVENT_SIGNALING_SEP_FOUND:
319             cid = avdtp_subevent_signaling_sep_found_get_avdtp_cid(packet);
320             if (a2dp_source_cid != cid) break;
321             if (a2dp_source_state == A2DP_DISCOVER_SEPS) {
322                 avdtp_sep_t sep;
323                 sep.seid       = avdtp_subevent_signaling_sep_found_get_remote_seid(packet);;
324                 sep.in_use     = avdtp_subevent_signaling_sep_found_get_in_use(packet);
325                 sep.media_type = (avdtp_media_type_t) avdtp_subevent_signaling_sep_found_get_media_type(packet);
326                 sep.type       = (avdtp_sep_type_t) avdtp_subevent_signaling_sep_found_get_sep_type(packet);
327                 log_info("A2DP Found sep: remote seid 0x%02x, in_use %d, media type %d, sep type %s, index %d",
328                          sep.seid, sep.in_use, sep.media_type, sep.type == AVDTP_SOURCE ? "source" : "sink",
329                          num_remote_seps);
330                 if (sep.type == AVDTP_SINK) {
331                     remote_seps[num_remote_seps++] = sep;
332                 }
333             }
334             break;
335 
336         case AVDTP_SUBEVENT_SIGNALING_SEP_DICOVERY_DONE:
337             cid = avdtp_subevent_signaling_sep_dicovery_done_get_avdtp_cid(packet);
338             if (a2dp_source_cid != cid) break;
339             if (a2dp_source_state != A2DP_DISCOVER_SEPS) break;
340 
341             connection = avdtp_get_connection_for_avdtp_cid(cid);
342             btstack_assert(connection != NULL);
343 
344             if (num_remote_seps > 0){
345                 a2dp_source_state = A2DP_GET_CAPABILITIES;
346                 sc.active_remote_sep_index = 0;
347                 a2dp_source_have_config = false;
348             } else {
349                 if (outgoing_active){
350                     outgoing_active = false;
351                     connection = avdtp_get_connection_for_avdtp_cid(cid);
352                     btstack_assert(connection != NULL);
353                     a2dp_source_streaming_emit_connection_failed(connection, sc.local_stream_endpoint->sep.seid, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_NO_SUITABLE_CHANNEL_FOUND);
354                 }
355 
356                 // continue
357                 a2dp_discover_seps_with_next_waiting_connection();
358             }
359             break;
360 
361         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CAPABILITY:
362             cid = avdtp_subevent_signaling_media_codec_sbc_capability_get_avdtp_cid(packet);
363             if (a2dp_source_cid != cid) break;
364             if (a2dp_source_state != A2DP_GET_CAPABILITIES) break;
365 
366             // forward codec capability
367             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CAPABILITY);
368 
369             // select SEP if none configured yet
370             if (a2dp_source_have_config == false){
371                // choose SBC config params
372                 uint16_t sampling_frequency       = avdtp_choose_sbc_sampling_frequency(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_sampling_frequency_bitmap(packet));
373                 avdtp_channel_mode_t channel_mode = avdtp_choose_sbc_channel_mode(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_channel_mode_bitmap(packet));
374                 uint8_t block_length        = avdtp_choose_sbc_block_length(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_block_length_bitmap(packet));
375                 uint8_t subbands            = avdtp_choose_sbc_subbands(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_subbands_bitmap(packet));
376                 avdtp_sbc_allocation_method_t allocation_method = avdtp_choose_sbc_allocation_method(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_allocation_method_bitmap(packet));
377                 uint8_t max_bitpool_value   = avdtp_choose_sbc_max_bitpool_value(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_max_bitpool_value(packet));
378                 uint8_t min_bitpool_value   = avdtp_choose_sbc_min_bitpool_value(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_min_bitpool_value(packet));
379 
380                 // and pre-select this (safe) endpoint
381                 uint8_t local_seid = avdtp_stream_endpoint_seid(sc.local_stream_endpoint);
382                 remote_seid = avdtp_subevent_signaling_media_codec_sbc_capability_get_remote_seid(packet);
383                 a2dp_source_set_config_sbc(cid, local_seid, remote_seid, sampling_frequency, channel_mode, block_length, subbands, allocation_method, min_bitpool_value, max_bitpool_value);
384             }
385             break;
386 
387         // forward codec capability
388         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_MPEG_AUDIO_CAPABILITY:
389             cid = avdtp_subevent_signaling_media_codec_mpeg_audio_capability_get_avdtp_cid(packet);
390             if (a2dp_source_cid != cid) break;
391             if (a2dp_source_state != A2DP_GET_CAPABILITIES) break;
392             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_MPEG_AUDIO_CAPABILITY);
393             break;
394         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_MPEG_AAC_CAPABILITY:
395             cid = avdtp_subevent_signaling_media_codec_mpeg_aac_capability_get_avdtp_cid(packet);
396             if (a2dp_source_cid != cid) break;
397             if (a2dp_source_state != A2DP_GET_CAPABILITIES) break;
398             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_MPEG_AAC_CAPABILITY);
399             break;
400         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_ATRAC_CAPABILITY:
401             cid = avdtp_subevent_signaling_media_codec_atrac_capability_get_avdtp_cid(packet);
402             if (a2dp_source_cid != cid) break;
403             if (a2dp_source_state != A2DP_GET_CAPABILITIES) break;
404             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_ATRAC_CAPABILITY);
405             break;
406         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CAPABILITY:
407             cid = avdtp_subevent_signaling_media_codec_other_capability_get_avdtp_cid(packet);
408             if (a2dp_source_cid != cid) break;
409             if (a2dp_source_state != A2DP_GET_CAPABILITIES) break;
410             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CAPABILITY);
411             break;
412 
413         // not forwarded
414         case AVDTP_SUBEVENT_SIGNALING_MEDIA_TRANSPORT_CAPABILITY:
415         case AVDTP_SUBEVENT_SIGNALING_REPORTING_CAPABILITY:
416         case AVDTP_SUBEVENT_SIGNALING_RECOVERY_CAPABILITY:
417         case AVDTP_SUBEVENT_SIGNALING_CONTENT_PROTECTION_CAPABILITY:
418         case AVDTP_SUBEVENT_SIGNALING_HEADER_COMPRESSION_CAPABILITY:
419         case AVDTP_SUBEVENT_SIGNALING_MULTIPLEXING_CAPABILITY:
420             break;
421 
422         case AVDTP_SUBEVENT_SIGNALING_DELAY_REPORTING_CAPABILITY:
423             cid = avdtp_subevent_signaling_delay_reporting_capability_get_avdtp_cid(packet);
424             log_info("received AVDTP_SUBEVENT_SIGNALING_DELAY_REPORTING_CAPABILITY, cid 0x%02x, state %d", cid, a2dp_source_state);
425 
426             if (a2dp_source_cid != cid) break;
427             if (a2dp_source_state != A2DP_GET_CAPABILITIES) break;
428 
429             sc.local_stream_endpoint->remote_configuration_bitmap = store_bit16(sc.local_stream_endpoint->remote_configuration_bitmap, AVDTP_DELAY_REPORTING, 1);
430             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_DELAY_REPORTING_CAPABILITY);
431             break;
432 
433         case AVDTP_SUBEVENT_SIGNALING_CAPABILITIES_DONE:
434             cid = avdtp_subevent_signaling_capabilities_done_get_avdtp_cid(packet);
435             if (a2dp_source_cid != cid) break;
436             if (a2dp_source_state != A2DP_GET_CAPABILITIES) break;
437 
438             // forward capabilities done for endpoint
439             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_CAPABILITIES_DONE);
440 
441             // endpoint was not suitable, check next one
442             sc.active_remote_sep_index++;
443             if (sc.active_remote_sep_index >= num_remote_seps){
444 
445                 // emit 'all capabilities for all seps reported'
446                 uint8_t event[6];
447                 uint8_t pos = 0;
448                 event[pos++] = HCI_EVENT_A2DP_META;
449                 event[pos++] = sizeof(event) - 2;
450                 event[pos++] = A2DP_SUBEVENT_SIGNALING_CAPABILITIES_COMPLETE;
451                 little_endian_store_16(event, pos, cid);
452                 (*a2dp_source_packet_handler_user)(HCI_EVENT_PACKET, 0, event, sizeof(event));
453 
454                 // do we have a valid config?
455                 if (a2dp_source_have_config){
456                     a2dp_source_state = A2DP_SET_CONFIGURATION;
457                     a2dp_source_have_config = false;
458                     break;
459                 }
460 
461                 // we didn't find a suitable SBC stream endpoint, sorry.
462                 if (outgoing_active){
463                     outgoing_active = false;
464                     connection = avdtp_get_connection_for_avdtp_cid(cid);
465                     btstack_assert(connection != NULL);
466                     a2dp_source_streaming_emit_connection_failed(connection, sc.local_stream_endpoint->sep.seid, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_NO_SUITABLE_CHANNEL_FOUND);
467                 }
468                 a2dp_discover_seps_with_next_waiting_connection();
469             }
470             break;
471 
472         case AVDTP_SUBEVENT_SIGNALING_DELAY_REPORT:
473             cid = avdtp_subevent_signaling_delay_report_get_avdtp_cid(packet);
474             if (a2dp_source_cid != cid) break;
475             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_DELAY_REPORT);
476             break;
477 
478         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:
479             cid = avdtp_subevent_signaling_media_codec_sbc_configuration_get_avdtp_cid(packet);
480 
481             if ((a2dp_source_cid == cid) && (a2dp_source_state == A2DP_W4_SET_CONFIGURATION)){
482 				// outgoing: discovery and config of remote sink sep successful, trigger stream open
483 				a2dp_source_state = A2DP_W2_OPEN_STREAM_WITH_SEID;
484             } else {
485 				// incoming: accept cid and wait for stream open
486 				a2dp_source_cid = cid;
487 				a2dp_source_state = A2DP_W4_OPEN_STREAM_WITH_SEID;
488             }
489 
490             // config set: stop timer
491 			a2dp_source_set_config_timer_stop();
492             stream_endpoint_configured = true;
493 
494             sc.sampling_frequency = avdtp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
495             sc.channel_mode = avdtp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
496             sc.block_length = avdtp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
497             sc.subbands = avdtp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
498             sc.allocation_method = avdtp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
499             sc.max_bitpool_value = avdtp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
500             sc.min_bitpool_value = avdtp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
501 
502             log_info("A2DP received SBC Config: sample rate %u, max bitpool %u., remote seid 0x%02x", sc.sampling_frequency, sc.max_bitpool_value, avdtp_subevent_signaling_media_codec_sbc_configuration_get_remote_seid(packet));
503             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION);
504             break;
505 
506         // forward codec configuration
507         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_MPEG_AUDIO_CONFIGURATION:
508             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_MPEG_AUDIO_CONFIGURATION);
509             break;
510         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_MPEG_AAC_CONFIGURATION:
511             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_MPEG_AAC_CONFIGURATION);
512             break;
513         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_ATRAC_CONFIGURATION:
514             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_ATRAC_CONFIGURATION);
515             break;
516         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
517             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION);
518             break;
519 
520         case AVDTP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW:
521             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW);
522             break;
523 
524         case AVDTP_SUBEVENT_STREAMING_CONNECTION_ESTABLISHED:
525             cid = avdtp_subevent_streaming_connection_established_get_avdtp_cid(packet);
526             if (a2dp_source_cid != cid) break;
527             if (a2dp_source_state != A2DP_W4_OPEN_STREAM_WITH_SEID) break;
528 
529 			outgoing_active = false;
530             status = avdtp_subevent_streaming_connection_established_get_status(packet);
531             if (status != ERROR_CODE_SUCCESS){
532                 log_info("A2DP source streaming connection could not be established, avdtp_cid 0x%02x, status 0x%02x ---", cid, status);
533                 a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_STREAM_ESTABLISHED);
534                 break;
535             }
536 
537             log_info("A2DP source streaming connection established --- avdtp_cid 0x%02x, local seid 0x%02x, remote seid 0x%02x", cid,
538                 avdtp_subevent_streaming_connection_established_get_local_seid(packet),
539                 avdtp_subevent_streaming_connection_established_get_remote_seid(packet));
540             a2dp_source_state = A2DP_STREAMING_OPENED;
541             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_STREAM_ESTABLISHED);
542             break;
543 
544         case AVDTP_SUBEVENT_SIGNALING_ACCEPT:
545             cid = avdtp_subevent_signaling_accept_get_avdtp_cid(packet);
546 
547 			// reset discovery timer while remote is active
548 			if (avdtp_subevent_signaling_accept_get_is_initiator(packet) == 0) {
549 				uint16_t avdtp_cid = (uint16_t)(uintptr_t) btstack_run_loop_get_timer_context(&a2dp_source_set_config_timer);
550 				if ((avdtp_cid == 0) || (avdtp_cid != cid)) break;
551 				log_info("Reset discovery timer");
552 				a2dp_source_set_config_timer_start(avdtp_cid);
553 				break;
554 			}
555 
556             if (a2dp_source_cid != cid) break;
557 
558             signal_identifier = avdtp_subevent_signaling_accept_get_signal_identifier(packet);
559 
560             log_info("A2DP cmd %s accepted, global state %d, cid 0x%02x", avdtp_si2str(signal_identifier), a2dp_source_state, cid);
561 
562             switch (a2dp_source_state){
563                 case A2DP_GET_CAPABILITIES:
564                     remote_seid = remote_seps[sc.active_remote_sep_index].seid;
565                     log_info("A2DP get capabilities for remote seid 0x%02x", remote_seid);
566                     avdtp_source_get_all_capabilities(cid, remote_seid);
567                     return;
568 
569                 case A2DP_SET_CONFIGURATION:
570                     remote_seid = sc.local_stream_endpoint->set_config_remote_seid;
571                     log_info("A2DP initiate set configuration locally and wait for response ... local seid 0x%02x, remote seid 0x%02x", avdtp_stream_endpoint_seid(sc.local_stream_endpoint), remote_seid);
572                     a2dp_source_state = A2DP_W4_SET_CONFIGURATION;
573                     avdtp_source_set_configuration(cid, avdtp_stream_endpoint_seid(sc.local_stream_endpoint), remote_seid, sc.local_stream_endpoint->remote_configuration_bitmap, sc.local_stream_endpoint->remote_configuration);
574                     return;
575 
576                 case A2DP_W2_OPEN_STREAM_WITH_SEID:
577                     log_info("A2DP open stream ... local seid 0x%02x, active remote seid 0x%02x", avdtp_stream_endpoint_seid(sc.local_stream_endpoint), sc.local_stream_endpoint->remote_sep.seid);
578                     a2dp_source_state = A2DP_W4_OPEN_STREAM_WITH_SEID;
579                     avdtp_source_open_stream(cid, avdtp_stream_endpoint_seid(sc.local_stream_endpoint), sc.local_stream_endpoint->remote_sep.seid);
580                     break;
581 
582                 case A2DP_W2_RECONFIGURE_WITH_SEID:
583                     log_info("A2DP reconfigured ... local seid 0x%02x, active remote seid 0x%02x", avdtp_stream_endpoint_seid(sc.local_stream_endpoint), sc.local_stream_endpoint->remote_sep.seid);
584                     a2dp_signaling_emit_reconfigured(cid, avdtp_stream_endpoint_seid(sc.local_stream_endpoint), ERROR_CODE_SUCCESS);
585                     a2dp_source_state = A2DP_STREAMING_OPENED;
586                     break;
587 
588                 case A2DP_STREAMING_OPENED:
589                     switch (signal_identifier){
590                         case  AVDTP_SI_START:
591                             a2dp_emit_stream_event(a2dp_source_packet_handler_user, cid, avdtp_stream_endpoint_seid(sc.local_stream_endpoint), A2DP_SUBEVENT_STREAM_STARTED);
592                             break;
593                         case AVDTP_SI_SUSPEND:
594                             a2dp_emit_stream_event(a2dp_source_packet_handler_user, cid, avdtp_stream_endpoint_seid(sc.local_stream_endpoint), A2DP_SUBEVENT_STREAM_SUSPENDED);
595                             break;
596                         case AVDTP_SI_ABORT:
597                         case AVDTP_SI_CLOSE:
598                             a2dp_emit_stream_event(a2dp_source_packet_handler_user, cid, avdtp_stream_endpoint_seid(sc.local_stream_endpoint), A2DP_SUBEVENT_STREAM_STOPPED);
599                             break;
600                         default:
601                             break;
602                     }
603                     break;
604 
605                 default:
606                     break;
607             }
608             break;
609 
610         case AVDTP_SUBEVENT_SIGNALING_REJECT:
611             cid = avdtp_subevent_signaling_reject_get_avdtp_cid(packet);
612             if (a2dp_source_cid != cid) break;
613             if (avdtp_subevent_signaling_reject_get_is_initiator(packet) == 0) break;
614 
615             a2dp_source_state = A2DP_CONNECTED;
616             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_COMMAND_REJECTED);
617             break;
618 
619         case AVDTP_SUBEVENT_SIGNALING_GENERAL_REJECT:
620             cid = avdtp_subevent_signaling_general_reject_get_avdtp_cid(packet);
621             if (a2dp_source_cid != cid) break;
622             if (avdtp_subevent_signaling_general_reject_get_is_initiator(packet) == 0) break;
623 
624             a2dp_source_state = A2DP_CONNECTED;
625             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_COMMAND_REJECTED);
626             break;
627 
628         case AVDTP_SUBEVENT_STREAMING_CONNECTION_RELEASED:
629             cid = avdtp_subevent_streaming_connection_released_get_avdtp_cid(packet);
630             if (a2dp_source_cid != cid) break;
631 
632             a2dp_source_state = A2DP_CONFIGURED;
633             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_STREAM_RELEASED);
634             break;
635 
636         case AVDTP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
637             cid = avdtp_subevent_signaling_connection_released_get_avdtp_cid(packet);
638             // connect/release are passed on to app
639             if (a2dp_source_cid == cid){
640                 stream_endpoint_configured = false;
641                 a2dp_source_state = A2DP_IDLE;
642                 a2dp_source_cid = 0;
643             }
644             a2dp_replace_subevent_id_and_emit_cmd(a2dp_source_packet_handler_user, packet, size, A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED);
645             break;
646 
647         default:
648             break;
649     }
650 }
651 void a2dp_source_register_packet_handler(btstack_packet_handler_t callback){
652     btstack_assert(callback != NULL);
653 
654     avdtp_source_register_packet_handler(&a2dp_source_packet_handler_internal);
655     a2dp_source_packet_handler_user = callback;
656 }
657 
658 void a2dp_source_init(void){
659     avdtp_source_init();
660 }
661 
662 avdtp_stream_endpoint_t * a2dp_source_create_stream_endpoint(avdtp_media_type_t media_type, avdtp_media_codec_type_t media_codec_type,
663 															 uint8_t * codec_capabilities, uint16_t codec_capabilities_len,
664 															 uint8_t * codec_configuration, uint16_t codec_configuration_len){
665     avdtp_stream_endpoint_t * local_stream_endpoint = avdtp_source_create_stream_endpoint(AVDTP_SOURCE, media_type);
666     if (!local_stream_endpoint){
667         return NULL;
668     }
669     avdtp_source_register_media_transport_category(avdtp_stream_endpoint_seid(local_stream_endpoint));
670     avdtp_source_register_media_codec_category(avdtp_stream_endpoint_seid(local_stream_endpoint), media_type, media_codec_type,
671         codec_capabilities, codec_capabilities_len);
672 	avdtp_source_register_delay_reporting_category(avdtp_stream_endpoint_seid(local_stream_endpoint));
673 
674 	// store user codec configuration buffer
675 	local_stream_endpoint->media_codec_configuration_info = codec_configuration;
676 	local_stream_endpoint->media_codec_configuration_len  = codec_configuration_len;
677 
678     sc.local_stream_endpoint = local_stream_endpoint;
679     return local_stream_endpoint;
680 }
681 
682 void a2dp_source_finalize_stream_endpoint(avdtp_stream_endpoint_t * stream_endpoint){
683     avdtp_source_finalize_stream_endpoint(stream_endpoint);
684 }
685 
686 uint8_t a2dp_source_establish_stream(bd_addr_t remote_addr, uint8_t loc_seid, uint16_t * avdtp_cid){
687     if (outgoing_active || stream_endpoint_configured) {
688         return ERROR_CODE_COMMAND_DISALLOWED;
689     }
690 
691     sc.local_stream_endpoint = avdtp_get_stream_endpoint_for_seid(loc_seid);
692     if (!sc.local_stream_endpoint){
693         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
694     }
695 
696     uint16_t outgoing_cid;
697 
698     outgoing_active = true;
699     uint8_t status = avdtp_source_connect(remote_addr, &outgoing_cid);
700     if (status != ERROR_CODE_SUCCESS) {
701         // if there's already a connection for for remote addr, avdtp_source_connect fails,
702         // but the stream will get set-up nevertheless
703         outgoing_active = false;
704         return status;
705     }
706 
707     // stop sep discovery for other
708     if (a2dp_source_state != A2DP_IDLE){
709         avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(a2dp_source_cid);
710         if (connection != NULL){
711             // sdp discovery has started: post-pone action, reserve sep discovery mechanism
712             connection->a2dp_source_discover_seps = true;
713         }
714     }
715 
716     // setup state
717     a2dp_source_state = A2DP_W4_CONNECTED;
718     a2dp_source_cid   = outgoing_cid;
719     *avdtp_cid = outgoing_cid;
720 
721     return ERROR_CODE_SUCCESS;
722 }
723 
724 uint8_t a2dp_source_disconnect(uint16_t avdtp_cid){
725     return avdtp_disconnect(avdtp_cid);
726 }
727 
728 
729 uint8_t a2dp_source_start_stream(uint16_t avdtp_cid, uint8_t local_seid){
730     return avdtp_start_stream(avdtp_cid, local_seid);
731 }
732 
733 uint8_t a2dp_source_pause_stream(uint16_t avdtp_cid, uint8_t local_seid){
734     return avdtp_suspend_stream(avdtp_cid, local_seid);
735 }
736 
737 void a2dp_source_stream_endpoint_request_can_send_now(uint16_t avdtp_cid, uint8_t local_seid){
738     avdtp_source_stream_endpoint_request_can_send_now(avdtp_cid, local_seid);
739 }
740 
741 int a2dp_max_media_payload_size(uint16_t avdtp_cid, uint8_t local_seid){
742     return avdtp_max_media_payload_size(avdtp_cid, local_seid);
743 }
744 
745 int a2dp_source_stream_send_media_payload(uint16_t avdtp_cid, uint8_t local_seid, uint8_t * storage, int num_bytes_to_copy, uint8_t num_frames, uint8_t marker){
746     return avdtp_source_stream_send_media_payload(avdtp_cid, local_seid, storage, num_bytes_to_copy, num_frames, marker);
747 }
748 
749 uint8_t	a2dp_source_stream_send_media_packet(uint16_t a2dp_cid, uint8_t local_seid, const uint8_t * packet, uint16_t size){
750     return avdtp_source_stream_send_media_packet(a2dp_cid, local_seid, packet, size);
751 }
752 
753 static void avdtp_config_sbc_set_sampling_frequency(uint8_t * config, uint16_t sampling_frequency_hz){
754     avdtp_sbc_sampling_frequency_t sampling_frequency;
755     switch (sampling_frequency_hz){
756         case 16000:
757             sampling_frequency = AVDTP_SBC_16000;
758             break;
759         case 32000:
760             sampling_frequency = AVDTP_SBC_32000;
761             break;
762         case 48000:
763             sampling_frequency = AVDTP_SBC_48000;
764             break;
765         default:
766             sampling_frequency = AVDTP_SBC_44100;
767             break;
768     }
769     config[0] = (((uint8_t) sampling_frequency) << 4) | (config[0] & 0x0f);
770 }
771 
772 static void avdtp_config_sbc_store(uint8_t * config, uint16_t sampling_frequency_hz, avdtp_channel_mode_t channel_mode, uint8_t block_length, uint8_t subbands,
773                                   avdtp_sbc_allocation_method_t  allocation_method, uint8_t min_bitpool_value, uint8_t max_bitpool_value) {
774     avdtp_sbc_channel_mode_t sbc_channel_mode;
775     switch (channel_mode){
776         case AVDTP_CHANNEL_MODE_MONO:
777             sbc_channel_mode = AVDTP_SBC_MONO;
778             break;
779         case AVDTP_CHANNEL_MODE_DUAL_CHANNEL:
780             sbc_channel_mode = AVDTP_SBC_DUAL_CHANNEL;
781             break;
782         case AVDTP_CHANNEL_MODE_STEREO:
783             sbc_channel_mode = AVDTP_SBC_STEREO;
784             break;
785         default:
786             sbc_channel_mode = AVDTP_SBC_JOINT_STEREO;
787             break;
788     }
789     config[0] = (uint8_t) sbc_channel_mode;
790     config[1] = (block_length << 4) | (subbands << 2) | allocation_method;
791     config[2] = min_bitpool_value;
792     config[3] = max_bitpool_value;
793     avdtp_config_sbc_set_sampling_frequency(config, sampling_frequency_hz);
794 }
795 
796 static void avdtp_config_mpeg_audio_set_sampling_frequency(uint8_t * config, uint16_t sampling_frequency_hz) {
797     uint8_t sampling_frequency_index = 0;
798     switch (sampling_frequency_hz){
799         case 16000:
800             sampling_frequency_index = 5;
801             break;
802         case 22040:
803             sampling_frequency_index = 4;
804             break;
805         case 24000:
806             sampling_frequency_index = 3;
807             break;
808         case 32000:
809             sampling_frequency_index = 2;
810             break;
811         case 44100:
812             sampling_frequency_index = 1;
813             break;
814         case 48000:
815             sampling_frequency_index = 0;
816             break;
817     }
818     config[1] = (config[1] & 0xC0) | (1 << sampling_frequency_index);
819 }
820 
821 static void avdtp_config_mpeg_audio_store(uint8_t * config, avdtp_mpeg_layer_t layer, uint8_t crc, avdtp_channel_mode_t channel_mode, uint8_t media_payload_format,
822                                           uint16_t sampling_frequency, uint8_t vbr, uint8_t bit_rate_index){
823 
824     config[0] = (((uint8_t) layer) << 5) | ((crc & 0x01) << 4) | (1 << (channel_mode - AVDTP_CHANNEL_MODE_MONO));
825     config[1] = ((media_payload_format & 0x01) << 6) ;
826     uint16_t bit_rate_mask = 1 << bit_rate_index;
827     config[2] = ((vbr & 0x01) << 7) | ((bit_rate_mask >> 8) & 0x3f);
828     config[3] = bit_rate_mask & 0xff;
829     avdtp_config_mpeg_audio_set_sampling_frequency(config, sampling_frequency);
830 }
831 
832 
833 static void avdtp_config_mpeg_aac_set_sampling_frequency(uint8_t * config, uint16_t sampling_frequency_hz) {
834     uint16_t sampling_frequency_bitmap = 0;
835     uint8_t i;
836     const uint32_t aac_sampling_frequency_table[] = {
837             96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000
838     };
839     for (i=0;i<12;i++){
840         if (sampling_frequency_hz == aac_sampling_frequency_table[i]){
841             sampling_frequency_bitmap = 1 << i;
842             break;
843         }
844     }
845     config[1] = sampling_frequency_bitmap >> 4;
846     config[2] = ((sampling_frequency_bitmap & 0x0f) << 4) | (config[2] & 0x0f);
847 }
848 
849 static void avdtp_config_mpeg_aac_store(uint8_t * config,  avdtp_aac_object_type_t object_type, uint32_t sampling_frequency, uint8_t channels, uint32_t bit_rate, uint8_t vbr) {
850     config[0] = 1 << (7 -(object_type - AVDTP_AAC_MPEG2_LC));
851     uint8_t channels_bitmap = 0;
852     switch (channels){
853         case 1:
854             channels_bitmap = 0x02;
855             break;
856         case 2:
857             channels_bitmap = 0x01;
858             break;
859         default:
860             break;
861     }
862     config[2] = channels_bitmap << 2;
863     config[3] = ((vbr & 0x01) << 7) | ((bit_rate >> 16) & 0x7f);
864     config[4] = (bit_rate >> 8) & 0xff;
865     config[5] =  bit_rate & 0xff;
866     avdtp_config_mpeg_aac_set_sampling_frequency(config, sampling_frequency);
867 }
868 
869 static void avdtp_config_atrac_set_sampling_frequency(uint8_t * config, uint16_t sampling_frequency_hz) {
870     uint8_t fs_bitmap = 0;
871     switch (sampling_frequency_hz){
872         case 44100:
873             fs_bitmap = 2;
874             break;
875         case 48000:
876             fs_bitmap = 1;
877             break;
878         default:
879             break;
880     }
881     config[1] = (fs_bitmap << 4) | (config[1] & 0x0F);
882 }
883 
884 static void avdtp_config_atrac_store(uint8_t * config, avdtp_atrac_version_t version, avdtp_channel_mode_t channel_mode, uint16_t sampling_frequency, uint8_t vbr,
885                                      uint8_t bit_rate_index, uint16_t maximum_sul) {
886     uint8_t channel_mode_bitamp = 0;
887     switch (channel_mode){
888         case AVDTP_CHANNEL_MODE_MONO:
889             channel_mode_bitamp = 4;
890             break;
891         case AVDTP_CHANNEL_MODE_DUAL_CHANNEL:
892             channel_mode_bitamp = 2;
893             break;
894         case AVDTP_CHANNEL_MODE_JOINT_STEREO:
895             channel_mode_bitamp = 1;
896             break;
897         default:
898             break;
899     }
900     config[0] = ((version - AVDTP_ATRAC_VERSION_1 + 1) << 5) | (channel_mode_bitamp << 2);
901     uint32_t bit_rate_bitmap = 1 << (0x18 - bit_rate_index);
902     config[1] = ((vbr & 0x01) << 3) | ((bit_rate_bitmap >> 16) & 0x07);
903     config[2] = (bit_rate_bitmap >> 8) & 0xff;
904     config[3] = bit_rate_bitmap & 0xff;
905     config[4] = maximum_sul >> 8;
906     config[5] = maximum_sul & 0xff;
907     config[6] = 0;
908     avdtp_config_atrac_set_sampling_frequency(config, sampling_frequency);
909 }
910 
911 static void a2dp_source_config_init(uint8_t remote_seid, avdtp_media_codec_type_t codec_type, const uint8_t * codec_info, uint8_t codec_info_len){
912     // set media configuration
913     sc.local_stream_endpoint->remote_configuration_bitmap = store_bit16(sc.local_stream_endpoint->remote_configuration_bitmap, AVDTP_MEDIA_CODEC, 1);
914     sc.local_stream_endpoint->remote_configuration.media_codec.media_type = AVDTP_AUDIO;
915     sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_type = AVDTP_CODEC_SBC;
916     // select reserved config buffer
917     sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information = (uint8_t *) codec_info;
918     sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information_len = codec_info_len;
919     // store SBC configuration in reserved field
920     sc.local_stream_endpoint->set_config_remote_seid = remote_seid;
921     // suitable Sink SEP found, configure SEP
922     a2dp_source_have_config = true;
923 }
924 
925 uint8_t a2dp_source_set_config_sbc(uint16_t a2dp_cid,  uint8_t local_seid, uint8_t remote_seid, uint16_t sampling_frequency, avdtp_channel_mode_t channel_mode,
926                                    uint8_t block_length, uint8_t subbands, avdtp_sbc_allocation_method_t allocation_method, uint8_t min_bitpool_value, uint8_t max_bitpool_value){
927 
928     UNUSED(local_seid);
929 
930     if (a2dp_source_cid != a2dp_cid){
931         return ERROR_CODE_COMMAND_DISALLOWED;
932     }
933 
934     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(a2dp_cid);
935     if (connection == NULL){
936         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
937     }
938 
939     a2dp_source_config_init(remote_seid, AVDTP_CODEC_SBC, sc.local_stream_endpoint->media_codec_info, 4);
940     avdtp_config_sbc_store( sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information,
941                             sampling_frequency, channel_mode, block_length, subbands, allocation_method, min_bitpool_value, max_bitpool_value);
942 
943     return ERROR_CODE_SUCCESS;
944 }
945 
946 uint8_t a2dp_source_set_config_mpeg_audio(uint16_t a2dp_cid,  uint8_t local_seid, uint8_t remote_seid, avdtp_mpeg_layer_t layer, uint8_t crc,
947                                           avdtp_channel_mode_t channel_mode, uint8_t media_payload_format,
948                                           uint16_t sampling_frequency, uint8_t vbr, uint8_t bit_rate_index){
949     UNUSED(local_seid);
950 
951     if (a2dp_source_cid != a2dp_cid){
952         return ERROR_CODE_COMMAND_DISALLOWED;
953     }
954 
955     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(a2dp_cid);
956     if (connection == NULL){
957         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
958     }
959 
960     a2dp_source_config_init(remote_seid, AVDTP_CODEC_MPEG_1_2_AUDIO, sc.local_stream_endpoint->media_codec_info, 4);
961     avdtp_config_mpeg_audio_store( sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information,
962                                    layer, crc, channel_mode, media_payload_format, sampling_frequency, vbr, bit_rate_index);
963 
964     return ERROR_CODE_SUCCESS;
965 }
966 
967 uint8_t a2dp_source_set_config_mpeg_aac(uint16_t a2dp_cid,  uint8_t local_seid, uint8_t remote_seid, avdtp_aac_object_type_t object_type,
968                                         uint32_t sampling_frequency, uint8_t channels, uint32_t bit_rate, uint8_t vbr){
969     UNUSED(local_seid);
970 
971     if (a2dp_source_cid != a2dp_cid){
972         return ERROR_CODE_COMMAND_DISALLOWED;
973     }
974 
975     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(a2dp_cid);
976     if (connection == NULL){
977         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
978     }
979 
980     a2dp_source_config_init(remote_seid, AVDTP_CODEC_MPEG_2_4_AAC, sc.local_stream_endpoint->media_codec_info, 6);
981     avdtp_config_mpeg_aac_store( sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information,
982                                    object_type, sampling_frequency, channels, bit_rate, vbr);
983 
984     return ERROR_CODE_SUCCESS;
985 }
986 
987 uint8_t a2dp_source_set_config_atrac(uint16_t a2dp_cid,  uint8_t local_seid, uint8_t remote_seid, avdtp_atrac_version_t version,
988                                      avdtp_channel_mode_t channel_mode, uint16_t sampling_frequency, uint8_t vbr,
989                                      uint8_t bit_rate_index, uint16_t maximum_sul){
990     UNUSED(local_seid);
991 
992     if (a2dp_source_cid != a2dp_cid){
993         return ERROR_CODE_COMMAND_DISALLOWED;
994     }
995 
996     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(a2dp_cid);
997     if (connection == NULL){
998         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
999     }
1000     a2dp_source_config_init(remote_seid, AVDTP_CODEC_ATRAC_FAMILY, sc.local_stream_endpoint->media_codec_info, 7);
1001     avdtp_config_atrac_store( sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information,
1002                                  version, channel_mode, sampling_frequency, vbr, bit_rate_index, maximum_sul);
1003 
1004     return ERROR_CODE_SUCCESS;
1005 }
1006 
1007 uint8_t a2dp_source_set_config_other(uint16_t a2dp_cid,  uint8_t local_seid, uint8_t remote_seid,
1008                                      const uint8_t * media_codec_information, uint8_t media_codec_information_len){
1009     if (a2dp_source_cid != a2dp_cid){
1010         return ERROR_CODE_COMMAND_DISALLOWED;
1011     }
1012 
1013     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(a2dp_cid);
1014     if (connection == NULL){
1015         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1016     }
1017 
1018     a2dp_source_config_init(remote_seid, AVDTP_CODEC_NON_A2DP, media_codec_information, media_codec_information_len);
1019 
1020     return ERROR_CODE_SUCCESS;
1021 }
1022 
1023 uint8_t a2dp_source_reconfigure_stream_sampling_frequency(uint16_t avdtp_cid, uint32_t sampling_frequency){
1024     btstack_assert(sc.local_stream_endpoint != NULL);
1025 
1026     if (a2dp_source_cid != avdtp_cid){
1027         return ERROR_CODE_COMMAND_DISALLOWED;
1028     }
1029 
1030     avdtp_connection_t * connection = avdtp_get_connection_for_avdtp_cid(avdtp_cid);
1031     if (connection == NULL){
1032         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1033     }
1034 
1035     if (a2dp_source_state != A2DP_STREAMING_OPENED) {
1036         return ERROR_CODE_COMMAND_DISALLOWED;
1037     }
1038 
1039     log_info("Reconfigure avdtp_cid 0x%02x", avdtp_cid);
1040 
1041     avdtp_media_codec_type_t codec_type = sc.local_stream_endpoint->sep.capabilities.media_codec.media_codec_type;
1042     uint8_t codec_info_len;
1043     switch (codec_type){
1044         case AVDTP_CODEC_SBC:
1045             codec_info_len = 4;
1046             (void)memcpy(sc.local_stream_endpoint->media_codec_info, sc.local_stream_endpoint->remote_sep.configuration.media_codec.media_codec_information, codec_info_len);
1047             avdtp_config_sbc_set_sampling_frequency(sc.local_stream_endpoint->media_codec_info, sampling_frequency);
1048             break;
1049         case AVDTP_CODEC_MPEG_1_2_AUDIO:
1050             codec_info_len = 4;
1051             (void)memcpy(sc.local_stream_endpoint->media_codec_info, sc.local_stream_endpoint->remote_sep.configuration.media_codec.media_codec_information, codec_info_len);
1052             avdtp_config_mpeg_audio_set_sampling_frequency(sc.local_stream_endpoint->media_codec_info, sampling_frequency);
1053             break;
1054         case AVDTP_CODEC_MPEG_2_4_AAC:
1055             codec_info_len = 6;
1056             (void)memcpy(sc.local_stream_endpoint->media_codec_info, sc.local_stream_endpoint->remote_sep.configuration.media_codec.media_codec_information, codec_info_len);
1057             avdtp_config_mpeg_aac_set_sampling_frequency(sc.local_stream_endpoint->media_codec_info, sampling_frequency);
1058             break;
1059         case AVDTP_CODEC_ATRAC_FAMILY:
1060             codec_info_len = 7;
1061             (void)memcpy(sc.local_stream_endpoint->media_codec_info, sc.local_stream_endpoint->remote_sep.configuration.media_codec.media_codec_information, codec_info_len);
1062             avdtp_config_atrac_set_sampling_frequency(sc.local_stream_endpoint->media_codec_info, sampling_frequency);
1063             break;
1064         case AVDTP_CODEC_NON_A2DP:
1065             return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1066     }
1067 
1068     avdtp_capabilities_t new_configuration;
1069     new_configuration.media_codec.media_type = AVDTP_AUDIO;
1070     new_configuration.media_codec.media_codec_type = codec_type;
1071     new_configuration.media_codec.media_codec_information_len = codec_info_len;
1072     new_configuration.media_codec.media_codec_information = sc.local_stream_endpoint->media_codec_info;
1073 
1074     // start reconfigure
1075     a2dp_source_state = A2DP_W2_RECONFIGURE_WITH_SEID;
1076 
1077     return avdtp_source_reconfigure(
1078             avdtp_cid,
1079             avdtp_stream_endpoint_seid(sc.local_stream_endpoint),
1080             sc.local_stream_endpoint->remote_sep.seid,
1081             1 << AVDTP_MEDIA_CODEC,
1082             new_configuration
1083     );
1084 }
1085