xref: /btstack/example/a2dp_source_demo.c (revision d40c3de009bce6994e726da5a427e08951b353d9)
1 /*
2  * Copyright (C) 2016 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 
39 #include <stdint.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #include "btstack.h"
45 
46 #include "hxcmod.h"
47 #include "mods/mod.h"
48 
49 #define NUM_CHANNELS                2
50 #define A2DP_SAMPLE_RATE            44100
51 #define BYTES_PER_AUDIO_SAMPLE      (2*NUM_CHANNELS)
52 #define AUDIO_TIMEOUT_MS            10
53 #define TABLE_SIZE_441HZ            100
54 
55 typedef enum {
56     STREAM_SINE,
57     STREAM_MOD
58 } stream_data_source_t;
59 
60 typedef struct {
61     uint16_t a2dp_cid;
62     uint8_t  local_seid;
63 
64     uint32_t time_audio_data_sent; // ms
65     uint32_t acc_num_missed_samples;
66     uint32_t samples_ready;
67     btstack_timer_source_t audio_timer;
68     uint8_t  streaming;
69     int      max_media_payload_size;
70 
71     uint8_t  sbc_storage[1030];
72     uint16_t sbc_storage_count;
73     uint8_t  sbc_ready_to_send;
74 } a2dp_media_sending_context_t;
75 
76 static  uint8_t media_sbc_codec_capabilities[] = {
77     (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
78     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
79     2, 53
80 };
81 
82 static const int16_t sine_int16[] = {
83      0,    2057,    4107,    6140,    8149,   10126,   12062,   13952,   15786,   17557,
84  19260,   20886,   22431,   23886,   25247,   26509,   27666,   28714,   29648,   30466,
85  31163,   31738,   32187,   32509,   32702,   32767,   32702,   32509,   32187,   31738,
86  31163,   30466,   29648,   28714,   27666,   26509,   25247,   23886,   22431,   20886,
87  19260,   17557,   15786,   13952,   12062,   10126,    8149,    6140,    4107,    2057,
88      0,   -2057,   -4107,   -6140,   -8149,  -10126,  -12062,  -13952,  -15786,  -17557,
89 -19260,  -20886,  -22431,  -23886,  -25247,  -26509,  -27666,  -28714,  -29648,  -30466,
90 -31163,  -31738,  -32187,  -32509,  -32702,  -32767,  -32702,  -32509,  -32187,  -31738,
91 -31163,  -30466,  -29648,  -28714,  -27666,  -26509,  -25247,  -23886,  -22431,  -20886,
92 -19260,  -17557,  -15786,  -13952,  -12062,  -10126,   -8149,   -6140,   -4107,   -2057,
93 };
94 
95 static char * device_name = "A2DP Source BTstack";
96 
97 #ifdef HAVE_BTSTACK_STDIN
98 // mac 2011:    static const char * device_addr_string = "04:0C:CE:E4:85:D3";
99 // pts:         static const char * device_addr_string = "00:1B:DC:08:0A:A5";
100 // mac 2013:    static const char * device_addr_string = "84:38:35:65:d1:15";
101 // phone 2013:  static const char * device_addr_string = "D8:BB:2C:DF:F0:F2";
102 // minijambox:
103 static const char * device_addr_string = "00:21:3C:AC:F7:38";
104 // head phones: static const char * device_addr_string = "00:18:09:28:50:18";
105 // bt dongle:   static const char * device_addr_string = "00:15:83:5F:9D:46";
106 #endif
107 
108 static bd_addr_t device_addr;
109 static uint8_t sdp_a2dp_source_service_buffer[150];
110 static uint8_t media_sbc_codec_configuration[4];
111 static a2dp_media_sending_context_t media_tracker;
112 
113 static uint16_t avrcp_cid;
114 
115 static stream_data_source_t data_source;
116 
117 static int sine_phase;
118 
119 static int hxcmod_initialized;
120 static modcontext mod_context;
121 static tracker_buffer_state trkbuf;
122 
123 static void a2dp_demo_send_media_packet(void){
124     int num_bytes_in_frame = btstack_sbc_encoder_sbc_buffer_length();
125     int bytes_in_storage = media_tracker.sbc_storage_count;
126     uint8_t num_frames = bytes_in_storage / num_bytes_in_frame;
127     a2dp_source_stream_send_media_payload(media_tracker.local_seid, media_tracker.sbc_storage, bytes_in_storage, num_frames, 0);
128     media_tracker.sbc_storage_count = 0;
129     media_tracker.sbc_ready_to_send = 0;
130 }
131 
132 static void produce_sine_audio(int16_t * pcm_buffer, int num_samples_to_write){
133     int count;
134     for (count = 0; count < num_samples_to_write ; count++){
135         pcm_buffer[count * 2]     = sine_int16[sine_phase];
136         pcm_buffer[count * 2 + 1] = sine_int16[sine_phase];
137         sine_phase++;
138         if (sine_phase >= TABLE_SIZE_441HZ){
139             sine_phase -= TABLE_SIZE_441HZ;
140         }
141     }
142 }
143 
144 static void produce_mod_audio(int16_t * pcm_buffer, int num_samples_to_write){
145     hxcmod_fillbuffer(&mod_context, (unsigned short *) &pcm_buffer[0], num_samples_to_write, &trkbuf);
146 }
147 
148 static void produce_audio(int16_t * pcm_buffer, int num_samples){
149     switch (data_source){
150         case STREAM_SINE:
151             produce_sine_audio(pcm_buffer, num_samples);
152             break;
153         case STREAM_MOD:
154             produce_mod_audio(pcm_buffer, num_samples);
155             break;
156     }
157 }
158 
159 static int a2dp_demo_fill_sbc_audio_buffer(a2dp_media_sending_context_t * context){
160     // perform sbc encodin
161     int total_num_bytes_read = 0;
162     int num_audio_samples_per_sbc_buffer = btstack_sbc_encoder_num_audio_frames();
163     while (context->samples_ready >= num_audio_samples_per_sbc_buffer
164         && (context->max_media_payload_size - context->sbc_storage_count) >= btstack_sbc_encoder_sbc_buffer_length()){
165 
166         uint8_t pcm_frame[256*BYTES_PER_AUDIO_SAMPLE];
167 
168         produce_audio((int16_t *) pcm_frame, num_audio_samples_per_sbc_buffer);
169         btstack_sbc_encoder_process_data((int16_t *) pcm_frame);
170 
171         uint16_t sbc_frame_size = btstack_sbc_encoder_sbc_buffer_length();
172         uint8_t * sbc_frame = btstack_sbc_encoder_sbc_buffer();
173 
174         total_num_bytes_read += num_audio_samples_per_sbc_buffer;
175         memcpy(&context->sbc_storage[context->sbc_storage_count], sbc_frame, sbc_frame_size);
176         context->sbc_storage_count += sbc_frame_size;
177         context->samples_ready -= num_audio_samples_per_sbc_buffer;
178     }
179     return total_num_bytes_read;
180 }
181 
182 static void a2dp_demo_audio_timeout_handler(btstack_timer_source_t * timer){
183     a2dp_media_sending_context_t * context = (a2dp_media_sending_context_t *) btstack_run_loop_get_timer_context(timer);
184     btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
185     btstack_run_loop_add_timer(&context->audio_timer);
186     uint32_t now = btstack_run_loop_get_time_ms();
187 
188     uint32_t update_period_ms = AUDIO_TIMEOUT_MS;
189     if (context->time_audio_data_sent > 0){
190         update_period_ms = now - context->time_audio_data_sent;
191     }
192 
193     uint32_t num_samples = (update_period_ms * A2DP_SAMPLE_RATE) / 1000;
194     context->acc_num_missed_samples += (update_period_ms * A2DP_SAMPLE_RATE) % 1000;
195 
196     while (context->acc_num_missed_samples >= 1000){
197         num_samples++;
198         context->acc_num_missed_samples -= 1000;
199     }
200     context->time_audio_data_sent = now;
201     context->samples_ready += num_samples;
202 
203     if (context->sbc_ready_to_send) return;
204 
205     a2dp_demo_fill_sbc_audio_buffer(context);
206 
207     if ((context->sbc_storage_count + btstack_sbc_encoder_sbc_buffer_length()) > context->max_media_payload_size){
208         // schedule sending
209         context->sbc_ready_to_send = 1;
210         a2dp_source_stream_endpoint_request_can_send_now(context->local_seid);
211     }
212 }
213 
214 static void a2dp_demo_timer_start(a2dp_media_sending_context_t * context){
215     context->max_media_payload_size = a2dp_max_media_payload_size(context->local_seid);
216     context->sbc_storage_count = 0;
217     context->sbc_ready_to_send = 0;
218     context->streaming = 1;
219     btstack_run_loop_remove_timer(&context->audio_timer);
220     btstack_run_loop_set_timer_handler(&context->audio_timer, a2dp_demo_audio_timeout_handler);
221     btstack_run_loop_set_timer_context(&context->audio_timer, context);
222     btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
223     btstack_run_loop_add_timer(&context->audio_timer);
224 }
225 
226 static void a2dp_demo_timer_stop(a2dp_media_sending_context_t * context){
227     context->time_audio_data_sent = 0;
228     context->acc_num_missed_samples = 0;
229     context->samples_ready = 0;
230     context->streaming = 1;
231     context->sbc_storage_count = 0;
232     context->sbc_ready_to_send = 0;
233     btstack_run_loop_remove_timer(&context->audio_timer);
234 }
235 
236 static void a2dp_demo_timer_pause(a2dp_media_sending_context_t * context){
237     btstack_run_loop_remove_timer(&context->audio_timer);
238 }
239 
240 
241 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
242     UNUSED(channel);
243     UNUSED(size);
244     uint8_t status;
245     uint8_t local_seid;
246 
247     switch (packet_type) {
248 
249         case HCI_EVENT_PACKET:
250             switch (hci_event_packet_get_type(packet)) {
251                 case HCI_EVENT_A2DP_META:
252                     switch (packet[2]){
253                         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
254                             status = a2dp_subevent_stream_established_get_status(packet);
255                             if (status){
256                                 printf("Stream establishment failed: status 0x%02x.\n", status);
257                                 break;
258                             }
259                             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
260                             if (local_seid != media_tracker.local_seid){
261                                 printf("Stream establishment failed: wrong local seid %d, expected %d.\n", local_seid, media_tracker.local_seid);
262                                 break;
263                             }
264 
265                             media_tracker.a2dp_cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
266                             printf("Stream established: a2dp cid 0x%02x, local seid %d, remote seid %d.\n",
267                                 media_tracker.a2dp_cid, media_tracker.local_seid, a2dp_subevent_stream_established_get_remote_seid(packet));
268                             break;
269 
270                         case A2DP_SUBEVENT_STREAM_STARTED:
271                             a2dp_demo_timer_start(&media_tracker);
272                             printf("Stream started.\n");
273                             break;
274 
275                         case A2DP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW:
276                             a2dp_demo_send_media_packet();
277                             break;
278 
279                         case A2DP_SUBEVENT_STREAM_SUSPENDED:
280                             printf("Stream paused.\n");
281                             a2dp_demo_timer_pause(&media_tracker);
282                             break;
283 
284                         case A2DP_SUBEVENT_STREAM_RELEASED:
285                             printf("Stream released.\n");
286                             a2dp_demo_timer_stop(&media_tracker);
287                             break;
288                         default:
289                             printf("AVDTP Source demo: event 0x%02x is not implemented\n", packet[2]);
290                             break;
291                     }
292                     break;
293                 default:
294                     break;
295             }
296             break;
297         default:
298             // other packet type
299             break;
300     }
301 }
302 
303 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
304     UNUSED(channel);
305     UNUSED(size);
306     bd_addr_t event_addr;
307     uint16_t local_cid;
308     uint8_t  status = 0xFF;
309 
310     if (packet_type != HCI_EVENT_PACKET) return;
311     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
312     switch (packet[2]){
313         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
314             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
315             if (avrcp_cid != 0 && avrcp_cid != local_cid) {
316                 printf("AVRCP Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_cid, local_cid);
317                 return;
318             }
319 
320             status = avrcp_subevent_connection_established_get_status(packet);
321             if (status != ERROR_CODE_SUCCESS){
322                 printf("AVRCP Connection failed: status 0x%02x\n", status);
323                 avrcp_cid = 0;
324                 return;
325             }
326             avrcp_cid = local_cid;
327             avrcp_subevent_connection_established_get_bd_addr(packet, event_addr);
328             printf("Channel successfully opened: %s, avrcp_cid 0x%02x\n", bd_addr_to_str(event_addr), local_cid);
329             return;
330         }
331         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
332             printf("Channel released: avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
333             avrcp_cid = 0;
334             return;
335         default:
336             printf("A2DP Source/AVRCP Target event not parsed %02x\n", packet[2]);
337             break;
338     }
339 }
340 
341 #ifdef HAVE_BTSTACK_STDIN
342 static void show_usage(void){
343     bd_addr_t      iut_address;
344     gap_local_bd_addr(iut_address);
345     printf("\n--- Bluetooth A2DP Source/AVRCP Target Demo %s ---\n", bd_addr_to_str(iut_address));
346     printf("b      - AVDTP Source create  connection to addr %s\n", device_addr_string);
347     printf("B      - AVDTP Source disconnect\n");
348     printf("c      - AVRCP Target create connection to addr %s\n", device_addr_string);
349     printf("C      - AVRCP Target disconnect\n");
350 
351     printf("x      - start streaming sine\n");
352     if (hxcmod_initialized){
353         printf("z      - start streaming '%s'\n", mod_name);
354     }
355     printf("p      - pause streaming\n");
356 
357     printf("\n--- Bluetooth  AVRCP Target Commands %s ---\n", bd_addr_to_str(iut_address));
358     printf("Ctrl-c - exit\n");
359     printf("---\n");
360 }
361 
362 static void stdin_process(char cmd){
363     switch (cmd){
364         case 'b':
365             printf(" - Create AVDTP Source connection to addr %s.\n", bd_addr_to_str(device_addr));
366             a2dp_source_establish_stream(device_addr, media_tracker.local_seid, &media_tracker.a2dp_cid);
367             break;
368         case 'B':
369             printf(" - AVDTP Source Disconnect\n");
370             a2dp_source_disconnect(media_tracker.a2dp_cid);
371             break;
372         case 'c':
373             printf(" - Create AVRCP Target connection to addr %s.\n", bd_addr_to_str(device_addr));
374             avrcp_target_connect(device_addr, &avrcp_cid);
375             printf(" assigned avrcp cid 0x%02x\n", avrcp_cid);
376             break;
377         case 'C':
378             printf(" - AVRCP Target disconnect\n");
379             avrcp_target_disconnect(avrcp_cid);
380             break;
381 
382         case '\n':
383         case '\r':
384             break;
385 
386         case 'x':
387             printf("Playing sine.\n");
388             data_source = STREAM_SINE;
389             a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
390             break;
391         case 'z':
392             printf("Playing mod.\n");
393             data_source = STREAM_MOD;
394             a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
395             break;
396         case 'p':
397             printf("Pause stream.\n");
398             a2dp_source_pause_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
399             break;
400 
401         default:
402             show_usage();
403             break;
404     }
405 }
406 #endif
407 
408 
409 int btstack_main(int argc, const char * argv[]);
410 int btstack_main(int argc, const char * argv[]){
411     UNUSED(argc);
412     (void)argv;
413 
414     l2cap_init();
415     // Initialize AVDTP Source
416     a2dp_source_init();
417     a2dp_source_register_packet_handler(&packet_handler);
418 
419     media_tracker.local_seid = a2dp_source_create_stream_endpoint(AVDTP_AUDIO, AVDTP_CODEC_SBC, media_sbc_codec_capabilities, sizeof(media_sbc_codec_capabilities), media_sbc_codec_configuration, sizeof(media_sbc_codec_configuration));
420 
421     // Initialize AVRCP Target
422     avrcp_target_init();
423     avrcp_target_register_packet_handler(&avrcp_target_packet_handler);
424 
425     // Initialize SDP
426     sdp_init();
427     memset(sdp_a2dp_source_service_buffer, 0, sizeof(sdp_a2dp_source_service_buffer));
428     a2dp_source_create_sdp_record(sdp_a2dp_source_service_buffer, 0x10002, 1, NULL, NULL);
429     sdp_register_service(sdp_a2dp_source_service_buffer);
430 
431     gap_set_local_name(device_name);
432     gap_discoverable_control(1);
433     gap_set_class_of_device(0x200408);
434 
435     hxcmod_initialized = hxcmod_init(&mod_context);
436     if (hxcmod_initialized){
437         hxcmod_setcfg(&mod_context, A2DP_SAMPLE_RATE, 16, 1, 1, 1);
438         hxcmod_load(&mod_context, (void *) &mod_data, mod_len);
439         printf("loaded mod '%s', size %u\n", mod_name, mod_len);
440     }
441 
442 #ifdef HAVE_BTSTACK_STDIN
443     // parse human readable Bluetooth address
444     sscanf_bd_addr(device_addr_string, device_addr);
445     btstack_stdin_setup(stdin_process);
446 #endif
447     // turn on!
448     hci_power_control(HCI_POWER_ON);
449     return 0;
450 }
451