xref: /btstack/example/a2dp_source_demo.c (revision 9a658d6ac5e2f726196f0c3f4c06eb1f5a1b9a7d)
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 stream_data_source_t data_source;
114 
115 static int sine_phase;
116 
117 static int hxcmod_initialized;
118 static modcontext mod_context;
119 static tracker_buffer_state trkbuf;
120 
121 static void a2dp_demo_send_media_packet(void){
122     int num_bytes_in_frame = btstack_sbc_encoder_sbc_buffer_length();
123     int bytes_in_storage = media_tracker.sbc_storage_count;
124     uint8_t num_frames = bytes_in_storage / num_bytes_in_frame;
125     a2dp_source_stream_send_media_payload(media_tracker.local_seid, media_tracker.sbc_storage, bytes_in_storage, num_frames, 0);
126     media_tracker.sbc_storage_count = 0;
127     media_tracker.sbc_ready_to_send = 0;
128 }
129 
130 static void produce_sine_audio(int16_t * pcm_buffer, int num_samples_to_write){
131     int count;
132     for (count = 0; count < num_samples_to_write ; count++){
133         pcm_buffer[count * 2]     = sine_int16[sine_phase];
134         pcm_buffer[count * 2 + 1] = sine_int16[sine_phase];
135         sine_phase++;
136         if (sine_phase >= TABLE_SIZE_441HZ){
137             sine_phase -= TABLE_SIZE_441HZ;
138         }
139     }
140 }
141 
142 static void produce_mod_audio(int16_t * pcm_buffer, int num_samples_to_write){
143     hxcmod_fillbuffer(&mod_context, (unsigned short *) &pcm_buffer[0], num_samples_to_write, &trkbuf);
144 }
145 
146 static void produce_audio(int16_t * pcm_buffer, int num_samples){
147     switch (data_source){
148         case STREAM_SINE:
149             produce_sine_audio(pcm_buffer, num_samples);
150             break;
151         case STREAM_MOD:
152             produce_mod_audio(pcm_buffer, num_samples);
153             break;
154     }
155 }
156 
157 static int a2dp_demo_fill_sbc_audio_buffer(a2dp_media_sending_context_t * context){
158     // perform sbc encodin
159     int total_num_bytes_read = 0;
160     int num_audio_samples_per_sbc_buffer = btstack_sbc_encoder_num_audio_frames();
161     while (context->samples_ready >= num_audio_samples_per_sbc_buffer
162         && (context->max_media_payload_size - context->sbc_storage_count) >= btstack_sbc_encoder_sbc_buffer_length()){
163 
164         uint8_t pcm_frame[256*BYTES_PER_AUDIO_SAMPLE];
165 
166         produce_audio((int16_t *) pcm_frame, num_audio_samples_per_sbc_buffer);
167         btstack_sbc_encoder_process_data((int16_t *) pcm_frame);
168 
169         uint16_t sbc_frame_size = btstack_sbc_encoder_sbc_buffer_length();
170         uint8_t * sbc_frame = btstack_sbc_encoder_sbc_buffer();
171 
172         total_num_bytes_read += num_audio_samples_per_sbc_buffer;
173         memcpy(&context->sbc_storage[context->sbc_storage_count], sbc_frame, sbc_frame_size);
174         context->sbc_storage_count += sbc_frame_size;
175         context->samples_ready -= num_audio_samples_per_sbc_buffer;
176     }
177     return total_num_bytes_read;
178 }
179 
180 static void a2dp_demo_audio_timeout_handler(btstack_timer_source_t * timer){
181     a2dp_media_sending_context_t * context = (a2dp_media_sending_context_t *) btstack_run_loop_get_timer_context(timer);
182     btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
183     btstack_run_loop_add_timer(&context->audio_timer);
184     uint32_t now = btstack_run_loop_get_time_ms();
185 
186     uint32_t update_period_ms = AUDIO_TIMEOUT_MS;
187     if (context->time_audio_data_sent > 0){
188         update_period_ms = now - context->time_audio_data_sent;
189     }
190 
191     uint32_t num_samples = (update_period_ms * A2DP_SAMPLE_RATE) / 1000;
192     context->acc_num_missed_samples += (update_period_ms * A2DP_SAMPLE_RATE) % 1000;
193 
194     while (context->acc_num_missed_samples >= 1000){
195         num_samples++;
196         context->acc_num_missed_samples -= 1000;
197     }
198     context->time_audio_data_sent = now;
199     context->samples_ready += num_samples;
200 
201     if (context->sbc_ready_to_send) return;
202 
203     a2dp_demo_fill_sbc_audio_buffer(context);
204 
205     if ((context->sbc_storage_count + btstack_sbc_encoder_sbc_buffer_length()) > context->max_media_payload_size){
206         // schedule sending
207         context->sbc_ready_to_send = 1;
208         a2dp_source_stream_endpoint_request_can_send_now(context->local_seid);
209     }
210 }
211 
212 static void a2dp_demo_timer_start(a2dp_media_sending_context_t * context){
213     context->max_media_payload_size = a2dp_max_media_payload_size(context->local_seid);
214     context->sbc_storage_count = 0;
215     context->sbc_ready_to_send = 0;
216     context->streaming = 1;
217     btstack_run_loop_remove_timer(&context->audio_timer);
218     btstack_run_loop_set_timer_handler(&context->audio_timer, a2dp_demo_audio_timeout_handler);
219     btstack_run_loop_set_timer_context(&context->audio_timer, context);
220     btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
221     btstack_run_loop_add_timer(&context->audio_timer);
222 }
223 
224 static void a2dp_demo_timer_stop(a2dp_media_sending_context_t * context){
225     context->time_audio_data_sent = 0;
226     context->acc_num_missed_samples = 0;
227     context->samples_ready = 0;
228     context->streaming = 1;
229     context->sbc_storage_count = 0;
230     context->sbc_ready_to_send = 0;
231     btstack_run_loop_remove_timer(&context->audio_timer);
232 }
233 
234 static void a2dp_demo_timer_pause(a2dp_media_sending_context_t * context){
235     btstack_run_loop_remove_timer(&context->audio_timer);
236 }
237 
238 
239 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
240     UNUSED(channel);
241     UNUSED(size);
242     uint8_t status;
243     uint8_t local_seid;
244 
245     switch (packet_type) {
246 
247         case HCI_EVENT_PACKET:
248             switch (hci_event_packet_get_type(packet)) {
249                 case HCI_EVENT_A2DP_META:
250                     switch (packet[2]){
251                         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
252                             status = a2dp_subevent_stream_established_get_status(packet);
253                             if (status){
254                                 printf("Stream establishment failed: status 0x%02x.\n", status);
255                                 break;
256                             }
257                             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
258                             if (local_seid != media_tracker.local_seid){
259                                 printf("Stream establishment failed: wrong local seid %d, expected %d.\n", local_seid, media_tracker.local_seid);
260                                 break;
261                             }
262 
263                             media_tracker.a2dp_cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
264                             printf("Stream established: a2dp cid 0x%02x, local seid %d, remote seid %d.\n",
265                                 media_tracker.a2dp_cid, media_tracker.local_seid, a2dp_subevent_stream_established_get_remote_seid(packet));
266                             break;
267 
268                         case A2DP_SUBEVENT_STREAM_STARTED:
269                             a2dp_demo_timer_start(&media_tracker);
270                             printf("Stream started.\n");
271                             break;
272 
273                         case A2DP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW:
274                             a2dp_demo_send_media_packet();
275                             break;
276 
277                         case A2DP_SUBEVENT_STREAM_SUSPENDED:
278                             printf("Stream paused.\n");
279                             a2dp_demo_timer_pause(&media_tracker);
280                             break;
281 
282                         case A2DP_SUBEVENT_STREAM_RELEASED:
283                             printf("Stream released.\n");
284                             a2dp_demo_timer_stop(&media_tracker);
285                             break;
286                         default:
287                             printf("AVDTP Source demo: event 0x%02x is not implemented\n", packet[2]);
288                             break;
289                     }
290                     break;
291                 default:
292                     break;
293             }
294             break;
295         default:
296             // other packet type
297             break;
298     }
299 }
300 
301 #ifdef HAVE_BTSTACK_STDIN
302 
303 static void show_usage(void){
304     bd_addr_t      iut_address;
305     gap_local_bd_addr(iut_address);
306     printf("\n--- Bluetooth A2DP Source Test Console %s ---\n", bd_addr_to_str(iut_address));
307     printf("c      - create connection to addr %s\n", device_addr_string);
308     printf("x      - start streaming sine\n");
309     if (hxcmod_initialized){
310         printf("z      - start streaming '%s'\n", mod_name);
311     }
312     printf("p      - pause streaming\n");
313     printf("C      - disconnect\n");
314     printf("Ctrl-c - exit\n");
315     printf("---\n");
316 }
317 
318 static void stdin_process(char cmd){
319     switch (cmd){
320         case 'c':
321             printf("Creating L2CAP Connection to %s, PSM_AVDTP\n", device_addr_string);
322             a2dp_source_establish_stream(device_addr, media_tracker.local_seid, &media_tracker.a2dp_cid);
323             break;
324         case 'x':
325             printf("Playing sine.\n");
326             data_source = STREAM_SINE;
327             a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
328             break;
329         case 'z':
330             printf("Playing mod.\n");
331             data_source = STREAM_MOD;
332             a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
333             break;
334         case 'p':
335             printf("Pause stream.\n");
336             a2dp_source_pause_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
337             break;
338         case 'C':
339             printf("Disconnect\n");
340             a2dp_source_disconnect(media_tracker.a2dp_cid);
341             break;
342         default:
343             show_usage();
344             break;
345     }
346 }
347 #endif
348 
349 
350 int btstack_main(int argc, const char * argv[]);
351 int btstack_main(int argc, const char * argv[]){
352     UNUSED(argc);
353     (void)argv;
354 
355     l2cap_init();
356     // Initialize AVDTP Source
357     a2dp_source_init();
358     a2dp_source_register_packet_handler(&packet_handler);
359 
360     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));
361 
362     // Initialize SDP
363     sdp_init();
364     memset(sdp_a2dp_source_service_buffer, 0, sizeof(sdp_a2dp_source_service_buffer));
365     a2dp_source_create_sdp_record(sdp_a2dp_source_service_buffer, 0x10002, 1, NULL, NULL);
366     sdp_register_service(sdp_a2dp_source_service_buffer);
367 
368     gap_set_local_name(device_name);
369     gap_discoverable_control(1);
370     gap_set_class_of_device(0x200408);
371 
372     hxcmod_initialized = hxcmod_init(&mod_context);
373     if (hxcmod_initialized){
374         hxcmod_setcfg(&mod_context, A2DP_SAMPLE_RATE, 16, 1, 1, 1);
375         hxcmod_load(&mod_context, (void *) &mod_data, mod_len);
376         printf("loaded mod '%s', size %u\n", mod_name, mod_len);
377     }
378 
379 #ifdef HAVE_BTSTACK_STDIN
380     // parse human readable Bluetooth address
381     sscanf_bd_addr(device_addr_string, device_addr);
382     btstack_stdin_setup(stdin_process);
383 #endif
384     // turn on!
385     hci_power_control(HCI_POWER_ON);
386     return 0;
387 }
388