xref: /btstack/src/classic/a2dp_source.c (revision 7dc86dfd3569d69491d87d64749fd45afb46c67a)
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 #define __BTSTACK_FILE__ "a2dp_source.c"
40 
41 #include <stdint.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 
46 #include "btstack.h"
47 #include "classic/avdtp.h"
48 #include "classic/avdtp_util.h"
49 #include "classic/avdtp_source.h"
50 #include "classic/a2dp_source.h"
51 
52 #define AVDTP_MEDIA_PAYLOAD_HEADER_SIZE 12
53 
54 static const char * default_a2dp_source_service_name = "BTstack A2DP Source Service";
55 static const char * default_a2dp_source_service_provider_name = "BTstack A2DP Source Service Provider";
56 static avdtp_context_t a2dp_source_context;
57 
58 static a2dp_state_t app_state = A2DP_IDLE;
59 static avdtp_stream_endpoint_context_t sc;
60 static int next_remote_sep_index_to_query = 0;
61 
62 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
63 
64 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){
65     uint8_t* attribute;
66     de_create_sequence(service);
67 
68     // 0x0000 "Service Record Handle"
69     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
70     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
71 
72     // 0x0001 "Service Class ID List"
73     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
74     attribute = de_push_sequence(service);
75     {
76         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_AUDIO_SOURCE);
77     }
78     de_pop_sequence(service, attribute);
79 
80     // 0x0004 "Protocol Descriptor List"
81     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
82     attribute = de_push_sequence(service);
83     {
84         uint8_t* l2cpProtocol = de_push_sequence(attribute);
85         {
86             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
87             de_add_number(l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVDTP);
88         }
89         de_pop_sequence(attribute, l2cpProtocol);
90 
91         uint8_t* avProtocol = de_push_sequence(attribute);
92         {
93             de_add_number(avProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVDTP);  // avProtocol_service
94             de_add_number(avProtocol,  DE_UINT, DE_SIZE_16,  0x0103);  // version
95         }
96         de_pop_sequence(attribute, avProtocol);
97     }
98     de_pop_sequence(service, attribute);
99 
100     // 0x0005 "Public Browse Group"
101     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
102     attribute = de_push_sequence(service);
103     {
104         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
105     }
106     de_pop_sequence(service, attribute);
107 
108     // 0x0009 "Bluetooth Profile Descriptor List"
109     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
110     attribute = de_push_sequence(service);
111     {
112         uint8_t *a2dProfile = de_push_sequence(attribute);
113         {
114             de_add_number(a2dProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_ADVANCED_AUDIO_DISTRIBUTION);
115             de_add_number(a2dProfile,  DE_UINT, DE_SIZE_16, 0x0103);
116         }
117         de_pop_sequence(attribute, a2dProfile);
118     }
119     de_pop_sequence(service, attribute);
120 
121 
122     // 0x0100 "Service Name"
123     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
124     if (service_name){
125         de_add_data(service,  DE_STRING, strlen(service_name), (uint8_t *) service_name);
126     } else {
127         de_add_data(service,  DE_STRING, strlen(default_a2dp_source_service_name), (uint8_t *) default_a2dp_source_service_name);
128     }
129 
130     // 0x0100 "Provider Name"
131     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0102);
132     if (service_provider_name){
133         de_add_data(service,  DE_STRING, strlen(service_provider_name), (uint8_t *) service_provider_name);
134     } else {
135         de_add_data(service,  DE_STRING, strlen(default_a2dp_source_service_provider_name), (uint8_t *) default_a2dp_source_service_provider_name);
136     }
137 
138     // 0x0311 "Supported Features"
139     de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);
140     de_add_number(service, DE_UINT, DE_SIZE_16, supported_features);
141 }
142 
143 
144 static void a2dp_streaming_emit_can_send_media_packet_now(btstack_packet_handler_t callback, uint16_t cid, uint8_t seid){
145     if (!callback) return;
146     uint8_t event[8];
147     int pos = 0;
148     event[pos++] = HCI_EVENT_A2DP_META;
149     event[pos++] = sizeof(event) - 2;
150     event[pos++] = A2DP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW;
151     little_endian_store_16(event, pos, cid);
152     pos += 2;
153     event[pos++] = seid;
154     (*callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
155 }
156 
157 static inline void a2dp_signaling_emit_media_codec_sbc(btstack_packet_handler_t callback, uint8_t * event, uint16_t event_size){
158     if (!callback) return;
159     if (event_size < 18) return;
160     event[0] = HCI_EVENT_A2DP_META;
161     event[2] = A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION;
162     (*callback)(HCI_EVENT_PACKET, 0, event, event_size);
163 }
164 
165 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
166     UNUSED(channel);
167     UNUSED(size);
168 
169     uint8_t signal_identifier;
170     uint8_t status;
171     uint8_t local_seid;
172     uint8_t remote_seid;
173     uint16_t cid;
174     bd_addr_t address;
175 
176     if (packet_type != HCI_EVENT_PACKET) return;
177     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVDTP_META) return;
178 
179     switch (packet[2]){
180         case AVDTP_SUBEVENT_SIGNALING_CONNECTION_ESTABLISHED:{
181             avdtp_subevent_signaling_connection_established_get_bd_addr(packet, sc.remote_addr);
182             cid = avdtp_subevent_signaling_connection_established_get_avdtp_cid(packet);
183             status = avdtp_subevent_signaling_connection_established_get_status(packet);
184 
185             if (status != 0){
186                 log_info("AVDTP_SUBEVENT_SIGNALING_CONNECTION failed status %d ---", status);
187                 a2dp_streaming_emit_connection_established(a2dp_source_context.a2dp_callback, cid, sc.remote_addr, 0, 0, status);
188                 break;
189             }
190 
191             sc.active_remote_sep = NULL;
192             next_remote_sep_index_to_query = 0;
193             uint8_t event[11];
194             int pos = 0;
195             event[pos++] = HCI_EVENT_A2DP_META;
196             event[pos++] = sizeof(event) - 2;
197             event[pos++] = A2DP_SUBEVENT_SIGNALING_CONNECTION_ESTABLISHED;
198             little_endian_store_16(event, pos, cid);
199             pos += 2;
200             reverse_bd_addr(event+pos, sc.remote_addr);
201             pos += 6;
202             (*a2dp_source_context.a2dp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
203 
204             log_info("A2DP_SUBEVENT_SIGNALING_CONNECTION established avdtp_cid 0x%02x ---", a2dp_source_context.avdtp_cid);
205 
206             app_state = A2DP_W2_DISCOVER_SEPS;
207             avdtp_source_discover_stream_endpoints(cid);
208             break;
209         }
210         case AVDTP_SUBEVENT_SIGNALING_SEP_FOUND:
211             break;
212 
213         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CAPABILITY:{
214             log_info("A2DP received SBC capability.");
215             if (!sc.local_stream_endpoint) {
216                 printf("local seid %d \n", avdtp_subevent_signaling_media_codec_sbc_capability_get_local_seid(packet));
217                 return;
218             }
219             log_info("A2DP received SBC capability.");
220 
221             uint8_t sampling_frequency = avdtp_choose_sbc_sampling_frequency(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_sampling_frequency_bitmap(packet));
222             uint8_t channel_mode = avdtp_choose_sbc_channel_mode(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_channel_mode_bitmap(packet));
223             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));
224             uint8_t subbands = avdtp_choose_sbc_subbands(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_subbands_bitmap(packet));
225 
226             uint8_t allocation_method = avdtp_choose_sbc_allocation_method(sc.local_stream_endpoint, avdtp_subevent_signaling_media_codec_sbc_capability_get_allocation_method_bitmap(packet));
227             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));
228             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));
229 
230             sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information[0] = (sampling_frequency << 4) | channel_mode;
231             sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information[1] = (block_length << 4) | (subbands << 2) | allocation_method;
232             sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information[2] = min_bitpool_value;
233             sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_information[3] = max_bitpool_value;
234 
235             sc.local_stream_endpoint->remote_configuration_bitmap = store_bit16(sc.local_stream_endpoint->remote_configuration_bitmap, AVDTP_MEDIA_CODEC, 1);
236             sc.local_stream_endpoint->remote_configuration.media_codec.media_type = AVDTP_AUDIO;
237             sc.local_stream_endpoint->remote_configuration.media_codec.media_codec_type = AVDTP_CODEC_SBC;
238 
239             app_state = A2DP_W2_SET_CONFIGURATION;
240             break;
241         }
242         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CAPABILITY:
243             log_info("received non SBC codec. not implemented");
244             break;
245 
246         case AVDTP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
247             // TODO check cid
248             sc.sampling_frequency = avdtp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
249             sc.block_length = avdtp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
250             sc.subbands = avdtp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
251             sc.allocation_method = avdtp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet) - 1;
252             sc.max_bitpool_value = avdtp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
253             sc.channel_mode = avdtp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
254             // TODO: deal with reconfigure: avdtp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
255             log_info("A2DP received SBC Config: sample rate %u, max bitpool %u.", sc.sampling_frequency, sc.max_bitpool_value);
256             app_state = A2DP_W2_OPEN_STREAM_WITH_SEID;
257             a2dp_signaling_emit_media_codec_sbc(a2dp_source_context.a2dp_callback, packet, size);
258             break;
259         }
260 
261         case AVDTP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW:
262             cid = avdtp_subevent_streaming_can_send_media_packet_now_get_avdtp_cid(packet);
263             a2dp_streaming_emit_can_send_media_packet_now(a2dp_source_context.a2dp_callback, cid, 0);
264             break;
265 
266         case AVDTP_SUBEVENT_STREAMING_CONNECTION_ESTABLISHED:
267             avdtp_subevent_streaming_connection_established_get_bd_addr(packet, address);
268             status = avdtp_subevent_streaming_connection_established_get_status(packet);
269             cid = avdtp_subevent_streaming_connection_established_get_avdtp_cid(packet);
270             remote_seid = avdtp_subevent_streaming_connection_established_get_remote_seid(packet);
271             local_seid  = avdtp_subevent_streaming_connection_established_get_local_seid(packet);
272             if (status != 0){
273                 log_info("AVDTP_SUBEVENT_STREAMING_CONNECTION could not be established, status %d ---", status);
274                 a2dp_streaming_emit_connection_established(a2dp_source_context.a2dp_callback, cid, address, local_seid, remote_seid, status);
275                 break;
276             }
277 
278             app_state = A2DP_STREAMING_OPENED;
279             a2dp_streaming_emit_connection_established(a2dp_source_context.a2dp_callback, cid, address, local_seid, remote_seid, 0);
280             log_info("AVDTP_SUBEVENT_STREAMING_CONNECTION_ESTABLISHED --- avdtp_cid 0x%02x, local seid %d, remote seid %d", cid, local_seid, remote_seid);
281             break;
282 
283         case AVDTP_SUBEVENT_SIGNALING_ACCEPT:
284             // TODO check cid
285             signal_identifier = avdtp_subevent_signaling_accept_get_signal_identifier(packet);
286             cid = avdtp_subevent_signaling_accept_get_avdtp_cid(packet);
287             log_info("A2DP Accepted %d, state %d", signal_identifier, app_state);
288 
289             switch (app_state){
290                 case A2DP_W2_DISCOVER_SEPS:
291                     app_state = A2DP_W2_GET_ALL_CAPABILITIES;
292                     sc.active_remote_sep = avdtp_source_remote_sep(cid, next_remote_sep_index_to_query++);
293                     if (!sc.active_remote_sep) {
294                         app_state = A2DP_IDLE;
295                         a2dp_streaming_emit_connection_established(a2dp_source_context.a2dp_callback, cid, sc.remote_addr, 0, 0, AVDTP_SEID_DOES_NOT_EXIST);
296                         break;
297                     }
298                     avdtp_source_get_capabilities(cid, sc.active_remote_sep->seid);
299                     break;
300                 case A2DP_W2_GET_CAPABILITIES:
301                 case A2DP_W2_GET_ALL_CAPABILITIES:
302                     if (next_remote_sep_index_to_query < avdtp_source_remote_seps_num(cid)){
303                         sc.active_remote_sep = avdtp_source_remote_sep(cid, next_remote_sep_index_to_query++);
304                         // printf("Query get caps for seid %d\n", sc.active_remote_sep->seid);
305                         avdtp_source_get_capabilities(cid, sc.active_remote_sep->seid);
306                     } else {
307                         // printf("No more remote seps found\n");
308                         app_state = A2DP_IDLE;
309                         a2dp_streaming_emit_connection_established(a2dp_source_context.a2dp_callback, cid, sc.remote_addr, 0, 0, AVDTP_SEID_DOES_NOT_EXIST);
310                     }
311                     break;
312                 case A2DP_W2_SET_CONFIGURATION:{
313                     if (!sc.local_stream_endpoint) return;
314                     app_state = A2DP_IDLE;
315                     log_info("A2DP initiate set configuration locally and wait for response ... ");
316                     avdtp_source_set_configuration(cid, avdtp_stream_endpoint_seid(sc.local_stream_endpoint), sc.active_remote_sep->seid, sc.local_stream_endpoint->remote_configuration_bitmap, sc.local_stream_endpoint->remote_configuration);
317                     break;
318                 }
319                 case A2DP_W2_OPEN_STREAM_WITH_SEID:{
320                     log_info("A2DP open stream ");
321                     app_state = A2DP_W4_OPEN_STREAM_WITH_SEID;
322                     avdtp_source_open_stream(cid, avdtp_stream_endpoint_seid(sc.local_stream_endpoint), sc.active_remote_sep->seid);
323                     break;
324                 }
325                 case A2DP_STREAMING_OPENED:
326                     if (!a2dp_source_context.a2dp_callback) return;
327                     switch (signal_identifier){
328                         case  AVDTP_SI_START:{
329                             uint8_t event[6];
330                             int pos = 0;
331                             event[pos++] = HCI_EVENT_A2DP_META;
332                             event[pos++] = sizeof(event) - 2;
333                             event[pos++] = A2DP_SUBEVENT_STREAM_STARTED;
334                             little_endian_store_16(event, pos, cid);
335                             pos += 2;
336                             event[pos++] = avdtp_stream_endpoint_seid(sc.local_stream_endpoint);
337                             (*a2dp_source_context.a2dp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
338                             break;
339                         }
340                         case AVDTP_SI_SUSPEND:{
341                             uint8_t event[6];
342                             int pos = 0;
343                             event[pos++] = HCI_EVENT_A2DP_META;
344                             event[pos++] = sizeof(event) - 2;
345                             event[pos++] = A2DP_SUBEVENT_STREAM_SUSPENDED;
346                             little_endian_store_16(event, pos, cid);
347                             pos += 2;
348                             event[pos++] = avdtp_stream_endpoint_seid(sc.local_stream_endpoint);
349                             (*a2dp_source_context.a2dp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
350                             break;
351                         }
352                         case AVDTP_SI_ABORT:
353                         case AVDTP_SI_CLOSE:{
354                             uint8_t event[6];
355                             int pos = 0;
356                             event[pos++] = HCI_EVENT_A2DP_META;
357                             event[pos++] = sizeof(event) - 2;
358                             event[pos++] = A2DP_SUBEVENT_STREAM_STOPPED;
359                             little_endian_store_16(event, pos, cid);
360                             pos += 2;
361                             log_info("send A2DP_SUBEVENT_STREAM_RELEASED to app");
362                             event[pos++] = avdtp_stream_endpoint_seid(sc.local_stream_endpoint);
363                             (*a2dp_source_context.a2dp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
364                             break;
365                         }
366                         default:
367                             break;
368                     }
369                     break;
370                 default:
371                     app_state = A2DP_IDLE;
372                     break;
373             }
374 
375             break;
376         case AVDTP_SUBEVENT_SIGNALING_REJECT:
377             app_state = A2DP_IDLE;
378             signal_identifier = avdtp_subevent_signaling_reject_get_signal_identifier(packet);
379             log_info("A2DP Rejected %d", signal_identifier);
380             break;
381         case AVDTP_SUBEVENT_SIGNALING_GENERAL_REJECT:
382             app_state = A2DP_IDLE;
383             signal_identifier = avdtp_subevent_signaling_general_reject_get_signal_identifier(packet);
384             log_info("A2DP Rejected %d", signal_identifier);
385             break;
386         case AVDTP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:{
387             app_state = A2DP_IDLE;
388             uint8_t event[6];
389             int pos = 0;
390             event[pos++] = HCI_EVENT_A2DP_META;
391             event[pos++] = sizeof(event) - 2;
392             event[pos++] = A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED;
393             little_endian_store_16(event, pos, avdtp_subevent_streaming_connection_released_get_avdtp_cid(packet));
394             pos += 2;
395             event[pos++] = avdtp_subevent_streaming_connection_released_get_local_seid(packet);
396             (*a2dp_source_context.a2dp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
397             break;
398         }
399         case AVDTP_SUBEVENT_STREAMING_CONNECTION_RELEASED:{
400             app_state = A2DP_IDLE;
401             uint8_t event[6];
402             int pos = 0;
403             event[pos++] = HCI_EVENT_A2DP_META;
404             event[pos++] = sizeof(event) - 2;
405             event[pos++] = A2DP_SUBEVENT_STREAM_RELEASED;
406             little_endian_store_16(event, pos, avdtp_subevent_streaming_connection_released_get_avdtp_cid(packet));
407             pos += 2;
408             event[pos++] = avdtp_subevent_streaming_connection_released_get_local_seid(packet);
409             (*a2dp_source_context.a2dp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
410             break;
411         }
412         default:
413             app_state = A2DP_IDLE;
414             log_info("not implemented");
415             break;
416     }
417 }
418 void a2dp_source_register_packet_handler(btstack_packet_handler_t callback){
419     if (callback == NULL){
420         log_error("a2dp_source_register_packet_handler called with NULL callback");
421         return;
422     }
423     avdtp_source_register_packet_handler(&packet_handler);
424     a2dp_source_context.a2dp_callback = callback;
425 }
426 
427 void a2dp_source_init(void){
428     avdtp_source_init(&a2dp_source_context);
429     l2cap_register_service(&packet_handler, BLUETOOTH_PROTOCOL_AVDTP, 0xffff, LEVEL_0);
430 }
431 
432 avdtp_stream_endpoint_t * a2dp_source_create_stream_endpoint(avdtp_media_type_t media_type, avdtp_media_codec_type_t media_codec_type,
433     uint8_t * codec_capabilities, uint16_t codec_capabilities_len,
434     uint8_t * media_codec_info, uint16_t media_codec_info_len){
435     avdtp_stream_endpoint_t * local_stream_endpoint = avdtp_source_create_stream_endpoint(AVDTP_SOURCE, media_type);
436     if (!local_stream_endpoint){
437         return NULL;
438     }
439     avdtp_source_register_media_transport_category(avdtp_stream_endpoint_seid(local_stream_endpoint));
440     avdtp_source_register_media_codec_category(avdtp_stream_endpoint_seid(local_stream_endpoint), media_type, media_codec_type,
441         codec_capabilities, codec_capabilities_len);
442     local_stream_endpoint->remote_configuration.media_codec.media_codec_information     = media_codec_info;
443     local_stream_endpoint->remote_configuration.media_codec.media_codec_information_len = media_codec_info_len;
444     sc.local_stream_endpoint = local_stream_endpoint;
445     return local_stream_endpoint;
446 }
447 
448 uint8_t a2dp_source_establish_stream(bd_addr_t remote_addr, uint8_t loc_seid, uint16_t * a2dp_cid){
449     sc.local_stream_endpoint = avdtp_stream_endpoint_for_seid(loc_seid, &a2dp_source_context);
450     if (!sc.local_stream_endpoint){
451         log_error(" no local_stream_endpoint for seid %d", loc_seid);
452         return AVDTP_SEID_DOES_NOT_EXIST;
453     }
454     memcpy(sc.remote_addr, remote_addr, 6);
455     return avdtp_source_connect(remote_addr, a2dp_cid);
456 }
457 
458 uint8_t a2dp_source_disconnect(uint16_t a2dp_cid){
459     return avdtp_disconnect(a2dp_cid, &a2dp_source_context);
460 }
461 
462 uint8_t a2dp_source_start_stream(uint16_t a2dp_cid, uint8_t local_seid){
463     return avdtp_start_stream(a2dp_cid, local_seid, &a2dp_source_context);
464 }
465 
466 uint8_t a2dp_source_pause_stream(uint16_t a2dp_cid, uint8_t local_seid){
467     return avdtp_suspend_stream(a2dp_cid, local_seid, &a2dp_source_context);
468 }
469 
470 static void a2dp_source_setup_media_header(uint8_t * media_packet, int size, int *offset, uint8_t marker, uint16_t sequence_number){
471     if (size < AVDTP_MEDIA_PAYLOAD_HEADER_SIZE){
472         log_error("small outgoing buffer");
473         return;
474     }
475 
476     uint8_t  rtp_version = 2;
477     uint8_t  padding = 0;
478     uint8_t  extension = 0;
479     uint8_t  csrc_count = 0;
480     uint8_t  payload_type = 0x60;
481     // uint16_t sequence_number = stream_endpoint->sequence_number;
482     uint32_t timestamp = btstack_run_loop_get_time_ms();
483     uint32_t ssrc = 0x11223344;
484 
485     // rtp header (min size 12B)
486     int pos = 0;
487     // int mtu = l2cap_get_remote_mtu_for_local_cid(stream_endpoint->l2cap_media_cid);
488 
489     media_packet[pos++] = (rtp_version << 6) | (padding << 5) | (extension << 4) | csrc_count;
490     media_packet[pos++] = (marker << 1) | payload_type;
491     big_endian_store_16(media_packet, pos, sequence_number);
492     pos += 2;
493     big_endian_store_32(media_packet, pos, timestamp);
494     pos += 4;
495     big_endian_store_32(media_packet, pos, ssrc); // only used for multicast
496     pos += 4;
497     *offset = pos;
498 }
499 
500 void a2dp_source_stream_endpoint_request_can_send_now(uint16_t a2dp_cid, uint8_t local_seid){
501     avdtp_stream_endpoint_t * stream_endpoint = avdtp_stream_endpoint_for_seid(local_seid, &a2dp_source_context);
502     if (!stream_endpoint) {
503         log_error("A2DP source: no stream_endpoint with seid %d", local_seid);
504         return;
505     }
506     if (a2dp_source_context.avdtp_cid != a2dp_cid){
507         log_error("A2DP source: a2dp cid 0x%02x not known, expected 0x%02x", a2dp_cid, a2dp_source_context.avdtp_cid);
508         return;
509     }
510     stream_endpoint->send_stream = 1;
511     avdtp_request_can_send_now_initiator(stream_endpoint->connection, stream_endpoint->l2cap_media_cid);
512 }
513 
514 int a2dp_max_media_payload_size(uint16_t a2dp_cid, uint8_t local_seid){
515     avdtp_stream_endpoint_t * stream_endpoint = avdtp_stream_endpoint_for_seid(local_seid, &a2dp_source_context);
516     if (!stream_endpoint) {
517         log_error("A2DP source: no stream_endpoint with seid %d", local_seid);
518         return 0;
519     }
520     if (a2dp_source_context.avdtp_cid != a2dp_cid){
521         log_error("A2DP source: a2dp cid 0x%02x not known, expected 0x%02x", a2dp_cid, a2dp_source_context.avdtp_cid);
522         return 0;
523     }
524 
525     if (stream_endpoint->l2cap_media_cid == 0){
526         log_error("A2DP source: no media connection for seid %d", local_seid);
527         return 0;
528     }
529     return l2cap_get_remote_mtu_for_local_cid(stream_endpoint->l2cap_media_cid) - AVDTP_MEDIA_PAYLOAD_HEADER_SIZE;
530 }
531 
532 static void a2dp_source_copy_media_payload(uint8_t * media_packet, int size, int * offset, uint8_t * storage, int num_bytes_to_copy, uint8_t num_frames){
533     if (size < num_bytes_to_copy + 1){
534         log_error("small outgoing buffer: buffer size %u, but need %u", size, num_bytes_to_copy + 1);
535         return;
536     }
537 
538     int pos = *offset;
539     media_packet[pos++] = num_frames; // (fragmentation << 7) | (starting_packet << 6) | (last_packet << 5) | num_frames;
540     memcpy(media_packet + pos, storage, num_bytes_to_copy);
541     pos += num_bytes_to_copy;
542     *offset = pos;
543 }
544 
545 int a2dp_source_stream_send_media_payload(uint16_t a2dp_cid, uint8_t local_seid, uint8_t * storage, int num_bytes_to_copy, uint8_t num_frames, uint8_t marker){
546     avdtp_stream_endpoint_t * stream_endpoint = avdtp_stream_endpoint_for_seid(local_seid, &a2dp_source_context);
547     if (!stream_endpoint) {
548         log_error("A2DP source: no stream_endpoint with seid %d", local_seid);
549         return 0;
550     }
551     if (a2dp_source_context.avdtp_cid != a2dp_cid){
552         log_error("A2DP source: a2dp cid 0x%02x not known, expected 0x%02x", a2dp_cid, a2dp_source_context.avdtp_cid);
553         return 0;
554     }
555 
556     if (stream_endpoint->l2cap_media_cid == 0){
557         log_error("A2DP source: no media connection for seid %d", local_seid);
558         return 0;
559     }
560 
561     int size = l2cap_get_remote_mtu_for_local_cid(stream_endpoint->l2cap_media_cid);
562     int offset = 0;
563 
564     l2cap_reserve_packet_buffer();
565     uint8_t * media_packet = l2cap_get_outgoing_buffer();
566     //int size = l2cap_get_remote_mtu_for_local_cid(stream_endpoint->l2cap_media_cid);
567     a2dp_source_setup_media_header(media_packet, size, &offset, marker, stream_endpoint->sequence_number);
568     a2dp_source_copy_media_payload(media_packet, size, &offset, storage, num_bytes_to_copy, num_frames);
569     stream_endpoint->sequence_number++;
570     l2cap_send_prepared(stream_endpoint->l2cap_media_cid, offset);
571     return size;
572 }
573