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