xref: /btstack/example/a2dp_source_demo.c (revision 584803f1655c614f96e570d481e8643b926b5706)
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 #define BTSTACK_FILE__ "a2dp_source_demo.c"
39 
40 /*
41  * a2dp_source_demo.c
42  */
43 
44 // *****************************************************************************
45 /* EXAMPLE_START(a2dp_source_demo): A2DP Source - Stream Audio and Control Volume
46  *
47  * @text This A2DP Source example demonstrates how to send an audio data stream
48  * to a remote A2DP Sink device and how to switch between two audio data sources.
49  * In addition, the AVRCP Target is used to answer queries on currently played media,
50  * as well as to handle remote playback control, i.e. play, stop, repeat, etc. If HAVE_BTSTACK_STDIN
51  * is set, press SPACE on the console to show the available AVDTP and AVRCP commands.
52  *
53  * @text To test with a remote device, e.g. a Bluetooth speaker,
54  * set the device_addr_string to the Bluetooth address of your
55  * remote device in the code, and use the UI to connect and start playback.
56  *
57  * @text For more info on BTstack audio, see our blog post
58  * [A2DP Sink and Source on STM32 F4 Discovery Board](http://bluekitchen-gmbh.com/a2dp-sink-and-source-on-stm32-f4-discovery-board/).
59  *
60  */
61 // *****************************************************************************
62 
63 
64 #include <stdint.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 
69 #include "btstack.h"
70 #include "hxcmod.h"
71 #include "mods/mod.h"
72 
73 // logarithmic volume reduction, samples are divided by 2^x
74 // #define VOLUME_REDUCTION 3
75 // #undef  HAVE_BTSTACK_STDIN
76 
77 //#define AVRCP_BROWSING_ENABLED
78 
79 #define NUM_CHANNELS                2
80 #define BYTES_PER_AUDIO_SAMPLE      (2*NUM_CHANNELS)
81 #define AUDIO_TIMEOUT_MS            10
82 #define TABLE_SIZE_441HZ            100
83 
84 #define SBC_STORAGE_SIZE 1030
85 
86 typedef enum {
87     STREAM_SINE = 0,
88     STREAM_MOD,
89     STREAM_PTS_TEST
90 } stream_data_source_t;
91 
92 typedef struct {
93     uint16_t a2dp_cid;
94     uint8_t  local_seid;
95     uint8_t  remote_seid;
96     uint8_t  stream_opened;
97     uint16_t avrcp_cid;
98 
99     uint32_t time_audio_data_sent; // ms
100     uint32_t acc_num_missed_samples;
101     uint32_t samples_ready;
102     btstack_timer_source_t audio_timer;
103     uint8_t  streaming;
104     int      max_media_payload_size;
105 
106     uint8_t  sbc_storage[SBC_STORAGE_SIZE];
107     uint16_t sbc_storage_count;
108     uint8_t  sbc_ready_to_send;
109 
110     uint16_t volume;
111 } a2dp_media_sending_context_t;
112 
113 static  uint8_t media_sbc_codec_capabilities[] = {
114     (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
115     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
116     2, 53
117 };
118 
119 // input signal: pre-computed int16 sine wave, 44100 Hz at 441 Hz
120 static const int16_t sine_int16_44100[] = {
121      0,    2057,    4107,    6140,    8149,   10126,   12062,   13952,   15786,   17557,
122  19260,   20886,   22431,   23886,   25247,   26509,   27666,   28714,   29648,   30466,
123  31163,   31738,   32187,   32509,   32702,   32767,   32702,   32509,   32187,   31738,
124  31163,   30466,   29648,   28714,   27666,   26509,   25247,   23886,   22431,   20886,
125  19260,   17557,   15786,   13952,   12062,   10126,    8149,    6140,    4107,    2057,
126      0,   -2057,   -4107,   -6140,   -8149,  -10126,  -12062,  -13952,  -15786,  -17557,
127 -19260,  -20886,  -22431,  -23886,  -25247,  -26509,  -27666,  -28714,  -29648,  -30466,
128 -31163,  -31738,  -32187,  -32509,  -32702,  -32767,  -32702,  -32509,  -32187,  -31738,
129 -31163,  -30466,  -29648,  -28714,  -27666,  -26509,  -25247,  -23886,  -22431,  -20886,
130 -19260,  -17557,  -15786,  -13952,  -12062,  -10126,   -8149,   -6140,   -4107,   -2057,
131 };
132 
133 static const int num_samples_sine_int16_44100 = sizeof(sine_int16_44100) / 2;
134 
135 // input signal: pre-computed int16 sine wave, 48000 Hz at 441 Hz
136 static const int16_t sine_int16_48000[] = {
137      0,    1905,    3804,    5690,    7557,    9398,   11207,   12978,   14706,   16383,
138  18006,   19567,   21062,   22486,   23834,   25101,   26283,   27376,   28377,   29282,
139  30087,   30791,   31390,   31884,   32269,   32545,   32712,   32767,   32712,   32545,
140  32269,   31884,   31390,   30791,   30087,   29282,   28377,   27376,   26283,   25101,
141  23834,   22486,   21062,   19567,   18006,   16383,   14706,   12978,   11207,    9398,
142   7557,    5690,    3804,    1905,       0,   -1905,   -3804,   -5690,   -7557,   -9398,
143 -11207,  -12978,  -14706,  -16384,  -18006,  -19567,  -21062,  -22486,  -23834,  -25101,
144 -26283,  -27376,  -28377,  -29282,  -30087,  -30791,  -31390,  -31884,  -32269,  -32545,
145 -32712,  -32767,  -32712,  -32545,  -32269,  -31884,  -31390,  -30791,  -30087,  -29282,
146 -28377,  -27376,  -26283,  -25101,  -23834,  -22486,  -21062,  -19567,  -18006,  -16384,
147 -14706,  -12978,  -11207,   -9398,   -7557,   -5690,   -3804,   -1905,  };
148 
149 static const int num_samples_sine_int16_48000 = sizeof(sine_int16_48000) / 2;
150 
151 typedef struct {
152     int reconfigure;
153 
154     int num_channels;
155     int sampling_frequency;
156     int block_length;
157     int subbands;
158     int min_bitpool_value;
159     int max_bitpool_value;
160     btstack_sbc_channel_mode_t      channel_mode;
161     btstack_sbc_allocation_method_t allocation_method;
162 } media_codec_configuration_sbc_t;
163 
164 static btstack_packet_callback_registration_t hci_event_callback_registration;
165 
166 // pts:             static const char * device_addr_string = "00:1B:DC:08:0A:A5";
167 // pts:             static const char * device_addr_string = "00:1B:DC:08:E2:72";
168 // mac 2013:        static const char * device_addr_string = "84:38:35:65:d1:15";
169 // phone 2013:      static const char * device_addr_string = "D8:BB:2C:DF:F0:F2";
170 // Minijambox:
171 static const char * device_addr_string = "00:21:3C:AC:F7:38";
172 // Philips SHB9100: static const char * device_addr_string = "00:22:37:05:FD:E8";
173 // RT-B6:           static const char * device_addr_string = "00:75:58:FF:C9:7D";
174 // BT dongle:       static const char * device_addr_string = "00:1A:7D:DA:71:0A";
175 // Sony MDR-ZX330BT static const char * device_addr_string = "00:18:09:28:50:18";
176 // Panda (BM6)      static const char * device_addr_string = "4F:3F:66:52:8B:E0";
177 // BeatsX:          static const char * device_addr_string = "DC:D3:A2:89:57:FB";
178 // Green mushroom:  static const char * device_addr_string = "41:42:2A:ED:D6:F3";
179 
180 static bd_addr_t device_addr;
181 
182 static uint8_t sdp_a2dp_source_service_buffer[150];
183 static uint8_t sdp_avrcp_target_service_buffer[200];
184 static uint8_t sdp_avrcp_controller_service_buffer[200];
185 static uint8_t device_id_sdp_service_buffer[100];
186 
187 static media_codec_configuration_sbc_t sbc_configuration;
188 static btstack_sbc_encoder_state_t sbc_encoder_state;
189 
190 static uint8_t media_sbc_codec_configuration[4];
191 static a2dp_media_sending_context_t media_tracker;
192 
193 static stream_data_source_t data_source;
194 
195 static int sine_phase;
196 static int current_sample_rate = 44100;
197 static int new_sample_rate = 44100;
198 
199 static int hxcmod_initialized;
200 static modcontext mod_context;
201 static tracker_buffer_state trkbuf;
202 
203 /* AVRCP Target context START */
204 static const uint8_t subunit_info[] = {
205     0,0,0,0,
206     1,1,1,1,
207     2,2,2,2,
208     3,3,3,3,
209     4,4,4,4,
210     5,5,5,5,
211     6,6,6,6,
212     7,7,7,7
213 };
214 
215 static uint32_t company_id = 0x112233;
216 static uint8_t  companies_num = 1;
217 static uint8_t  companies[] = {
218     0x00, 0x19, 0x58 //BT SIG registered CompanyID
219 };
220 
221 static uint8_t events_num = 6;
222 static uint8_t events[] = {
223     AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED,
224     AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED,
225     AVRCP_NOTIFICATION_EVENT_PLAYER_APPLICATION_SETTING_CHANGED,
226     AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED,
227     AVRCP_NOTIFICATION_EVENT_AVAILABLE_PLAYERS_CHANGED,
228     AVRCP_NOTIFICATION_EVENT_ADDRESSED_PLAYER_CHANGED
229 };
230 
231 typedef struct {
232     uint8_t track_id[8];
233     uint32_t song_length_ms;
234     avrcp_playback_status_t status;
235     uint32_t song_position_ms; // 0xFFFFFFFF if not supported
236 } avrcp_play_status_info_t;
237 
238 // python -c "print('a'*512)"
239 static const char title[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
240 
241 avrcp_track_t tracks[] = {
242     {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, 1, "Sine", "Generated", "A2DP Source Demo", "monotone", 12345},
243     {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}, 2, "Nao-deceased", "Decease", "A2DP Source Demo", "vivid", 12345},
244     {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03}, 3, (char *)title, "Decease", "A2DP Source Demo", "vivid", 12345},
245 };
246 int current_track_index;
247 avrcp_play_status_info_t play_info;
248 
249 /* AVRCP Target context END */
250 
251 /* @section Main Application Setup
252  *
253  * @text The Listing MainConfiguration shows how to setup AD2P Source and AVRCP services.
254  * Besides calling init() method for each service, you'll also need to register several packet handlers:
255  * - hci_packet_handler - handles legacy pairing, here by using fixed '0000' pin code.
256  * - a2dp_source_packet_handler - handles events on stream connection status (established, released), the media codec configuration, and, the commands on stream itself (open, pause, stopp).
257  * - avrcp_packet_handler - receives connect/disconnect event.
258  * - avrcp_controller_packet_handler - receives answers for sent AVRCP commands.
259  * - avrcp_target_packet_handler - receives AVRCP commands, and registered notifications.
260  * - stdin_process - used to trigger AVRCP commands to the A2DP Source device, such are get now playing info, start, stop, volume control. Requires HAVE_BTSTACK_STDIN.
261  *
262  * @text To announce A2DP Source and AVRCP services, you need to create corresponding
263  * SDP records and register them with the SDP service.
264  */
265 
266 /* LISTING_START(MainConfiguration): Setup Audio Source and AVRCP Target services */
267 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
268 static void a2dp_source_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * event, uint16_t event_size);
269 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
270 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
271 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
272 #ifdef HAVE_BTSTACK_STDIN
273 static void stdin_process(char cmd);
274 #endif
275 
276 static void a2dp_demo_hexcmod_configure_sample_rate(int sample_rate);
277 
278 static int a2dp_source_and_avrcp_services_init(void){
279     // Request role change on reconnecting headset to always use them in slave mode
280     hci_set_master_slave_policy(0);
281 
282     l2cap_init();
283     // Initialize  A2DP Source
284     a2dp_source_init();
285     a2dp_source_register_packet_handler(&a2dp_source_packet_handler);
286 
287     // Create stream endpoint
288     avdtp_stream_endpoint_t * local_stream_endpoint = 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));
289     if (!local_stream_endpoint){
290         printf("A2DP Source: not enough memory to create local stream endpoint\n");
291         return 1;
292     }
293 
294     // Store stream enpoint's SEP ID, as it is used by A2DP API to indentify the stream endpoint
295     media_tracker.local_seid = avdtp_local_seid(local_stream_endpoint);
296     avdtp_source_register_delay_reporting_category(media_tracker.local_seid);
297 
298     // Initialize AVRCP Service
299     avrcp_init();
300     avrcp_register_packet_handler(&avrcp_packet_handler);
301     // Initialize AVRCP Target
302     avrcp_target_init();
303     avrcp_target_register_packet_handler(&avrcp_target_packet_handler);
304     // Initialize AVRCP Controller
305     avrcp_controller_init();
306     avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler);
307 
308     // Initialize SDP,
309     sdp_init();
310 
311     // Create A2DP Source service record and register it with SDP
312     memset(sdp_a2dp_source_service_buffer, 0, sizeof(sdp_a2dp_source_service_buffer));
313     a2dp_source_create_sdp_record(sdp_a2dp_source_service_buffer, 0x10001, AVDTP_SOURCE_FEATURE_MASK_PLAYER, NULL, NULL);
314     sdp_register_service(sdp_a2dp_source_service_buffer);
315 
316     // Create AVRCP target service record and register it with SDP
317     memset(sdp_avrcp_target_service_buffer, 0, sizeof(sdp_avrcp_target_service_buffer));
318     uint16_t supported_features = AVRCP_FEATURE_MASK_CATEGORY_PLAYER_OR_RECORDER;
319 #ifdef AVRCP_BROWSING_ENABLED
320     supported_features |= AVRCP_FEATURE_MASK_BROWSING;
321 #endif
322     avrcp_target_create_sdp_record(sdp_avrcp_target_service_buffer, 0x10002, supported_features, NULL, NULL);
323     sdp_register_service(sdp_avrcp_target_service_buffer);
324 
325     // Register AVRCP Controller
326     memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
327     uint16_t controller_supported_features = AVRCP_FEATURE_MASK_CATEGORY_PLAYER_OR_RECORDER;
328     avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10003, controller_supported_features, NULL, NULL);
329     sdp_register_service(sdp_avrcp_controller_service_buffer);
330 
331     // Register Device ID (PnP) service SDP record
332     memset(device_id_sdp_service_buffer, 0, sizeof(device_id_sdp_service_buffer));
333     device_id_create_sdp_record(device_id_sdp_service_buffer, 0x10004, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
334     sdp_register_service(device_id_sdp_service_buffer);
335 
336     // Set local name with a template Bluetooth address, that will be automatically
337     // replaced with a actual address once it is available, i.e. when BTstack boots
338     // up and starts talking to a Bluetooth module.
339     gap_set_local_name("A2DP Source 00:00:00:00:00:00");
340     gap_discoverable_control(1);
341     gap_set_class_of_device(0x200408);
342 
343     // Register for HCI events.
344     hci_event_callback_registration.callback = &hci_packet_handler;
345     hci_add_event_handler(&hci_event_callback_registration);
346 
347     a2dp_demo_hexcmod_configure_sample_rate(current_sample_rate);
348 
349 #ifdef HAVE_BTSTACK_STDIN
350     // Parse human readable Bluetooth address.
351     sscanf_bd_addr(device_addr_string, device_addr);
352     btstack_stdin_setup(stdin_process);
353 #endif
354     return 0;
355 }
356 /* LISTING_END */
357 
358 static void a2dp_demo_hexcmod_configure_sample_rate(int sample_rate){
359     if (!hxcmod_initialized){
360         hxcmod_initialized = hxcmod_init(&mod_context);
361         if (!hxcmod_initialized) {
362             printf("could not initialize hxcmod\n");
363             return;
364         }
365     }
366     current_sample_rate = sample_rate;
367     media_tracker.sbc_storage_count = 0;
368     media_tracker.samples_ready = 0;
369     hxcmod_unload(&mod_context);
370     hxcmod_setcfg(&mod_context, current_sample_rate, 16, 1, 1, 1);
371     hxcmod_load(&mod_context, (void *) &mod_data, mod_len);
372 }
373 
374 static void a2dp_demo_send_media_packet(void){
375     int num_bytes_in_frame = btstack_sbc_encoder_sbc_buffer_length();
376     int bytes_in_storage = media_tracker.sbc_storage_count;
377     uint8_t num_frames = bytes_in_storage / num_bytes_in_frame;
378     a2dp_source_stream_send_media_payload(media_tracker.a2dp_cid, media_tracker.local_seid, media_tracker.sbc_storage, bytes_in_storage, num_frames, 0);
379     media_tracker.sbc_storage_count = 0;
380     media_tracker.sbc_ready_to_send = 0;
381 }
382 
383 static void produce_sine_audio(int16_t * pcm_buffer, int num_samples_to_write){
384     int count;
385     for (count = 0; count < num_samples_to_write ; count++){
386         switch (current_sample_rate){
387             case 44100:
388                 pcm_buffer[count * 2]     = sine_int16_44100[sine_phase];
389                 pcm_buffer[count * 2 + 1] = sine_int16_44100[sine_phase];
390                 sine_phase++;
391                 if (sine_phase >= num_samples_sine_int16_44100){
392                     sine_phase -= num_samples_sine_int16_44100;
393                 }
394                 break;
395             case 48000:
396                 pcm_buffer[count * 2]     = sine_int16_48000[sine_phase];
397                 pcm_buffer[count * 2 + 1] = sine_int16_48000[sine_phase];
398                 sine_phase++;
399                 if (sine_phase >= num_samples_sine_int16_48000){
400                     sine_phase -= num_samples_sine_int16_48000;
401                 }
402                 break;
403             default:
404                 break;
405         }
406     }
407 }
408 
409 static void produce_mod_audio(int16_t * pcm_buffer, int num_samples_to_write){
410     hxcmod_fillbuffer(&mod_context, (unsigned short *) &pcm_buffer[0], num_samples_to_write, &trkbuf);
411 }
412 
413 static void produce_audio(int16_t * pcm_buffer, int num_samples){
414     switch (data_source){
415         case STREAM_SINE:
416             produce_sine_audio(pcm_buffer, num_samples);
417             break;
418         case STREAM_MOD:
419             produce_mod_audio(pcm_buffer, num_samples);
420             break;
421         default:
422             break;
423     }
424 #ifdef VOLUME_REDUCTION
425     int i;
426     for (i=0;i<num_samples*2;i++){
427         if (pcm_buffer[i] > 0){
428             pcm_buffer[i] =     pcm_buffer[i]  >> VOLUME_REDUCTION;
429         } else {
430             pcm_buffer[i] = -((-pcm_buffer[i]) >> VOLUME_REDUCTION);
431         }
432     }
433 #endif
434 }
435 
436 static int a2dp_demo_fill_sbc_audio_buffer(a2dp_media_sending_context_t * context){
437     // perform sbc encoding
438     int total_num_bytes_read = 0;
439     unsigned int num_audio_samples_per_sbc_buffer = btstack_sbc_encoder_num_audio_frames();
440     while (context->samples_ready >= num_audio_samples_per_sbc_buffer
441         && (context->max_media_payload_size - context->sbc_storage_count) >= btstack_sbc_encoder_sbc_buffer_length()){
442 
443         int16_t pcm_frame[256*NUM_CHANNELS];
444 
445         produce_audio(pcm_frame, num_audio_samples_per_sbc_buffer);
446         btstack_sbc_encoder_process_data(pcm_frame);
447 
448         uint16_t sbc_frame_size = btstack_sbc_encoder_sbc_buffer_length();
449         uint8_t * sbc_frame = btstack_sbc_encoder_sbc_buffer();
450 
451         total_num_bytes_read += num_audio_samples_per_sbc_buffer;
452         memcpy(&context->sbc_storage[context->sbc_storage_count], sbc_frame, sbc_frame_size);
453         context->sbc_storage_count += sbc_frame_size;
454         context->samples_ready -= num_audio_samples_per_sbc_buffer;
455     }
456     return total_num_bytes_read;
457 }
458 
459 static void a2dp_demo_audio_timeout_handler(btstack_timer_source_t * timer){
460     a2dp_media_sending_context_t * context = (a2dp_media_sending_context_t *) btstack_run_loop_get_timer_context(timer);
461     btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
462     btstack_run_loop_add_timer(&context->audio_timer);
463     uint32_t now = btstack_run_loop_get_time_ms();
464 
465     uint32_t update_period_ms = AUDIO_TIMEOUT_MS;
466     if (context->time_audio_data_sent > 0){
467         update_period_ms = now - context->time_audio_data_sent;
468     }
469 
470     uint32_t num_samples = (update_period_ms * current_sample_rate) / 1000;
471     context->acc_num_missed_samples += (update_period_ms * current_sample_rate) % 1000;
472 
473     while (context->acc_num_missed_samples >= 1000){
474         num_samples++;
475         context->acc_num_missed_samples -= 1000;
476     }
477     context->time_audio_data_sent = now;
478     context->samples_ready += num_samples;
479 
480     if (context->sbc_ready_to_send) return;
481 
482     a2dp_demo_fill_sbc_audio_buffer(context);
483 
484     if ((context->sbc_storage_count + btstack_sbc_encoder_sbc_buffer_length()) > context->max_media_payload_size){
485         // schedule sending
486         context->sbc_ready_to_send = 1;
487         a2dp_source_stream_endpoint_request_can_send_now(context->a2dp_cid, context->local_seid);
488     }
489 }
490 
491 static void a2dp_demo_timer_start(a2dp_media_sending_context_t * context){
492     context->max_media_payload_size = btstack_min(a2dp_max_media_payload_size(context->a2dp_cid, context->local_seid), SBC_STORAGE_SIZE);
493     context->sbc_storage_count = 0;
494     context->sbc_ready_to_send = 0;
495     context->streaming = 1;
496     btstack_run_loop_remove_timer(&context->audio_timer);
497     btstack_run_loop_set_timer_handler(&context->audio_timer, a2dp_demo_audio_timeout_handler);
498     btstack_run_loop_set_timer_context(&context->audio_timer, context);
499     btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
500     btstack_run_loop_add_timer(&context->audio_timer);
501 }
502 
503 static void a2dp_demo_timer_stop(a2dp_media_sending_context_t * context){
504     context->time_audio_data_sent = 0;
505     context->acc_num_missed_samples = 0;
506     context->samples_ready = 0;
507     context->streaming = 1;
508     context->sbc_storage_count = 0;
509     context->sbc_ready_to_send = 0;
510     btstack_run_loop_remove_timer(&context->audio_timer);
511 }
512 
513 static void dump_sbc_configuration(media_codec_configuration_sbc_t * configuration){
514     printf("Received media codec configuration:\n");
515     printf("    - num_channels: %d\n", configuration->num_channels);
516     printf("    - sampling_frequency: %d\n", configuration->sampling_frequency);
517     printf("    - channel_mode: %d\n", configuration->channel_mode);
518     printf("    - block_length: %d\n", configuration->block_length);
519     printf("    - subbands: %d\n", configuration->subbands);
520     printf("    - allocation_method: %d\n", configuration->allocation_method);
521     printf("    - bitpool_value [%d, %d] \n", configuration->min_bitpool_value, configuration->max_bitpool_value);
522 }
523 
524 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
525     UNUSED(channel);
526     UNUSED(size);
527     if (packet_type != HCI_EVENT_PACKET) return;
528 
529 #ifndef HAVE_BTSTACK_STDIN
530     if (hci_event_packet_get_type(packet) == BTSTACK_EVENT_STATE){
531         if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return;
532         printf("Create A2DP Source connection to addr %s.\n", bd_addr_to_str(device_addr));
533         uint8_t status = a2dp_source_establish_stream(device_addr, media_tracker.local_seid, &media_tracker.a2dp_cid);
534         if (status != ERROR_CODE_SUCCESS){
535             printf("Could not perform command, status 0x%2x\n", status);
536         }
537         return;
538     }
539 #endif
540 
541     if (hci_event_packet_get_type(packet) == HCI_EVENT_PIN_CODE_REQUEST) {
542         bd_addr_t address;
543         printf("Pin code request - using '0000'\n");
544         hci_event_pin_code_request_get_bd_addr(packet, address);
545         gap_pin_code_response(address, "0000");
546     }
547 }
548 
549 static void a2dp_source_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
550     UNUSED(channel);
551     UNUSED(size);
552     uint8_t status;
553     uint8_t local_seid;
554     bd_addr_t address;
555     uint16_t cid;
556 
557     uint8_t channel_mode;
558     uint8_t allocation_method;
559 
560     if (packet_type != HCI_EVENT_PACKET) return;
561     if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return;
562 
563     switch (hci_event_a2dp_meta_get_subevent_code(packet)){
564         case A2DP_SUBEVENT_SIGNALING_CONNECTION_ESTABLISHED:
565             a2dp_subevent_signaling_connection_established_get_bd_addr(packet, address);
566             cid = a2dp_subevent_signaling_connection_established_get_a2dp_cid(packet);
567             status = a2dp_subevent_signaling_connection_established_get_status(packet);
568 
569             if (status != ERROR_CODE_SUCCESS){
570                 printf("A2DP Source: Connection failed, status 0x%02x, cid 0x%02x, a2dp_cid 0x%02x \n", status, cid, media_tracker.a2dp_cid);
571                 media_tracker.a2dp_cid = 0;
572                 break;
573             }
574             media_tracker.a2dp_cid = cid;
575             media_tracker.volume = 32;
576 
577             printf("A2DP Source: Connected to address %s, a2dp cid 0x%02x, local seid 0x%02x.\n", bd_addr_to_str(address), media_tracker.a2dp_cid, media_tracker.local_seid);
578             break;
579 
580          case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
581             cid  = avdtp_subevent_signaling_media_codec_sbc_configuration_get_avdtp_cid(packet);
582             if (cid != media_tracker.a2dp_cid) return;
583 
584             media_tracker.remote_seid = a2dp_subevent_signaling_media_codec_sbc_configuration_get_acp_seid(packet);
585 
586             sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
587             sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
588             sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
589             sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
590             sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
591             sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
592             sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
593 
594             channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
595             allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
596 
597             printf("A2DP Source: Received SBC codec configuration, sampling frequency %u, a2dp_cid 0x%02x, local seid 0x%02x, remote seid 0x%02x.\n",
598                 sbc_configuration.sampling_frequency, cid,
599                 a2dp_subevent_signaling_media_codec_sbc_configuration_get_int_seid(packet),
600                 a2dp_subevent_signaling_media_codec_sbc_configuration_get_acp_seid(packet));
601 
602             // Adapt Bluetooth spec definition to SBC Encoder expected input
603             sbc_configuration.allocation_method = (btstack_sbc_allocation_method_t)(allocation_method - 1);
604             sbc_configuration.num_channels = SBC_CHANNEL_MODE_STEREO;
605             switch (channel_mode){
606                 case AVDTP_SBC_JOINT_STEREO:
607                     sbc_configuration.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
608                     break;
609                 case AVDTP_SBC_STEREO:
610                     sbc_configuration.channel_mode = SBC_CHANNEL_MODE_STEREO;
611                     break;
612                 case AVDTP_SBC_DUAL_CHANNEL:
613                     sbc_configuration.channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
614                     break;
615                 case AVDTP_SBC_MONO:
616                     sbc_configuration.channel_mode = SBC_CHANNEL_MODE_MONO;
617                     sbc_configuration.num_channels = 1;
618                     break;
619                 default:
620                     btstack_assert(false);
621                     break;
622             }
623             dump_sbc_configuration(&sbc_configuration);
624 
625             btstack_sbc_encoder_init(&sbc_encoder_state, SBC_MODE_STANDARD,
626                 sbc_configuration.block_length, sbc_configuration.subbands,
627                 sbc_configuration.allocation_method, sbc_configuration.sampling_frequency,
628                 sbc_configuration.max_bitpool_value,
629                 sbc_configuration.channel_mode);
630             break;
631         }
632 
633         case A2DP_SUBEVENT_SIGNALING_DELAY_REPORTING_CAPABILITY:
634             printf("A2DP Source: remote supports delay report, remote seid %d\n",
635                 avdtp_subevent_signaling_delay_reporting_capability_get_remote_seid(packet));
636             break;
637         case A2DP_SUBEVENT_SIGNALING_CAPABILITIES_DONE:
638             printf("A2DP Source: All capabilities reported, remote seid %d\n",
639                 avdtp_subevent_signaling_capabilities_done_get_remote_seid(packet));
640             break;
641 
642         case A2DP_SUBEVENT_SIGNALING_DELAY_REPORT:
643             printf("A2DP Source: Received delay report of %d.%0d ms, local seid %d\n",
644                 avdtp_subevent_signaling_delay_report_get_delay_100us(packet)/10, avdtp_subevent_signaling_delay_report_get_delay_100us(packet)%10,
645                 avdtp_subevent_signaling_delay_report_get_local_seid(packet));
646             break;
647 
648         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
649             a2dp_subevent_stream_established_get_bd_addr(packet, address);
650             status = a2dp_subevent_stream_established_get_status(packet);
651             if (status){
652                 printf("A2DP Source: Stream failed, status 0x%02x.\n", status);
653                 break;
654             }
655 
656             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
657             cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
658 
659             printf("A2DP Source: Stream established a2dp_cid 0x%02x, local_seid 0x%02x, remote_seid 0x%02x\n", cid, local_seid, a2dp_subevent_stream_established_get_remote_seid(packet));
660 
661             a2dp_demo_hexcmod_configure_sample_rate(current_sample_rate);
662             media_tracker.stream_opened = 1;
663             data_source = STREAM_MOD;
664             status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
665             break;
666 
667         case A2DP_SUBEVENT_STREAM_RECONFIGURED:
668             status = a2dp_subevent_stream_reconfigured_get_status(packet);
669             local_seid = a2dp_subevent_stream_reconfigured_get_local_seid(packet);
670             cid = a2dp_subevent_stream_reconfigured_get_a2dp_cid(packet);
671 
672             if (status != ERROR_CODE_SUCCESS){
673                 printf("A2DP Source: Stream reconfiguration failed with status 0x%02x\n", status);
674                 break;
675             }
676 
677             printf("A2DP Source: Stream reconfigured a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
678             a2dp_demo_hexcmod_configure_sample_rate(new_sample_rate);
679             status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
680             break;
681 
682         case A2DP_SUBEVENT_STREAM_STARTED:
683             local_seid = a2dp_subevent_stream_started_get_local_seid(packet);
684             cid = a2dp_subevent_stream_started_get_a2dp_cid(packet);
685 
686             play_info.status = AVRCP_PLAYBACK_STATUS_PLAYING;
687             if (media_tracker.avrcp_cid){
688                 avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, &tracks[data_source], sizeof(tracks)/sizeof(avrcp_track_t));
689                 avrcp_target_set_playback_status(media_tracker.avrcp_cid, AVRCP_PLAYBACK_STATUS_PLAYING);
690             }
691             a2dp_demo_timer_start(&media_tracker);
692             printf("A2DP Source: Stream started, a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
693             break;
694 
695         case A2DP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW:
696             local_seid = a2dp_subevent_streaming_can_send_media_packet_now_get_local_seid(packet);
697             cid = a2dp_subevent_signaling_media_codec_sbc_configuration_get_a2dp_cid(packet);
698             a2dp_demo_send_media_packet();
699             break;
700 
701         case A2DP_SUBEVENT_STREAM_SUSPENDED:
702             local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet);
703             cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet);
704 
705             play_info.status = AVRCP_PLAYBACK_STATUS_PAUSED;
706             if (media_tracker.avrcp_cid){
707                 avrcp_target_set_playback_status(media_tracker.avrcp_cid, AVRCP_PLAYBACK_STATUS_PAUSED);
708             }
709             printf("A2DP Source: Stream paused, a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
710 
711             a2dp_demo_timer_stop(&media_tracker);
712             break;
713 
714         case A2DP_SUBEVENT_STREAM_RELEASED:
715             play_info.status = AVRCP_PLAYBACK_STATUS_STOPPED;
716             cid = a2dp_subevent_stream_released_get_a2dp_cid(packet);
717             local_seid = a2dp_subevent_stream_released_get_local_seid(packet);
718 
719             printf("A2DP Source: Stream released, a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
720 
721             if (cid == media_tracker.a2dp_cid) {
722                 media_tracker.stream_opened = 0;
723                 printf("A2DP Source: Stream released.\n");
724             }
725             if (media_tracker.avrcp_cid){
726                 avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, NULL, sizeof(tracks)/sizeof(avrcp_track_t));
727                 avrcp_target_set_playback_status(media_tracker.avrcp_cid, AVRCP_PLAYBACK_STATUS_STOPPED);
728             }
729             a2dp_demo_timer_stop(&media_tracker);
730             break;
731         case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
732             cid = a2dp_subevent_signaling_connection_released_get_a2dp_cid(packet);
733             if (cid == media_tracker.a2dp_cid) {
734                 media_tracker.avrcp_cid = 0;
735                 media_tracker.a2dp_cid = 0;
736                 printf("A2DP Source: Signaling released.\n\n");
737             }
738             break;
739         default:
740             break;
741     }
742 }
743 
744 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
745     UNUSED(channel);
746     UNUSED(size);
747     bd_addr_t event_addr;
748     uint16_t local_cid;
749     uint8_t  status = ERROR_CODE_SUCCESS;
750 
751     if (packet_type != HCI_EVENT_PACKET) return;
752     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
753 
754     switch (packet[2]){
755         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED:
756             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
757             status = avrcp_subevent_connection_established_get_status(packet);
758             if (status != ERROR_CODE_SUCCESS){
759                 printf("AVRCP: Connection failed, local cid 0x%02x, status 0x%02x\n", local_cid, status);
760                 return;
761             }
762             media_tracker.avrcp_cid = local_cid;
763             avrcp_subevent_connection_established_get_bd_addr(packet, event_addr);
764 
765             avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, NULL, sizeof(tracks)/sizeof(avrcp_track_t));
766             avrcp_target_set_unit_info(media_tracker.avrcp_cid, AVRCP_SUBUNIT_TYPE_AUDIO, company_id);
767             avrcp_target_set_subunit_info(media_tracker.avrcp_cid, AVRCP_SUBUNIT_TYPE_AUDIO, (uint8_t *)subunit_info, sizeof(subunit_info));
768 
769             avrcp_controller_get_supported_events(media_tracker.avrcp_cid);
770 
771             printf("AVRCP: Channel successfully opened:  media_tracker.avrcp_cid 0x%02x\n", media_tracker.avrcp_cid);
772             return;
773 
774         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
775             printf("AVRCP Target: Disconnected, avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
776             media_tracker.avrcp_cid = 0;
777             return;
778         default:
779             break;
780     }
781 
782     if (status != ERROR_CODE_SUCCESS){
783         printf("Responding to event 0x%02x failed with status 0x%02x\n", packet[2], status);
784     }
785 }
786 
787 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
788     UNUSED(channel);
789     UNUSED(size);
790     uint8_t  status = ERROR_CODE_SUCCESS;
791 
792     if (packet_type != HCI_EVENT_PACKET) return;
793     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
794 
795     switch (packet[2]){
796         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
797             media_tracker.volume = avrcp_subevent_notification_volume_changed_get_absolute_volume(packet);
798             printf("AVRCP Target: Volume set to %d%% (%d)\n", media_tracker.volume * 127/100, media_tracker.volume);
799             break;
800         case AVRCP_SUBEVENT_EVENT_IDS_QUERY:
801             status = avrcp_target_supported_events(media_tracker.avrcp_cid, events_num, events, sizeof(events));
802             break;
803         case AVRCP_SUBEVENT_COMPANY_IDS_QUERY:
804             status = avrcp_target_supported_companies(media_tracker.avrcp_cid, companies_num, companies, sizeof(companies));
805             break;
806         case AVRCP_SUBEVENT_PLAY_STATUS_QUERY:
807             status = avrcp_target_play_status(media_tracker.avrcp_cid, play_info.song_length_ms, play_info.song_position_ms, play_info.status);
808             break;
809         // case AVRCP_SUBEVENT_NOW_PLAYING_INFO_QUERY:
810         //     status = avrcp_target_now_playing_info(avrcp_cid);
811         //     break;
812         case AVRCP_SUBEVENT_OPERATION:{
813             avrcp_operation_id_t operation_id = avrcp_subevent_operation_get_operation_id(packet);
814             switch (operation_id){
815                 case AVRCP_OPERATION_ID_PLAY:
816                     printf("AVRCP Target: PLAY\n");
817                     status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
818                     break;
819                 case AVRCP_OPERATION_ID_PAUSE:
820                     printf("AVRCP Target: PAUSE\n");
821                     status = a2dp_source_pause_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
822                     break;
823                 case AVRCP_OPERATION_ID_STOP:
824                     printf("AVRCP Target: STOP\n");
825                     status = a2dp_source_disconnect(media_tracker.a2dp_cid);
826                     break;
827                 default:
828                     printf("AVRCP Target: operation 0x%2x is not handled\n", operation_id);
829                     return;
830             }
831             break;
832         }
833 
834         default:
835             break;
836     }
837 
838     if (status != ERROR_CODE_SUCCESS){
839         printf("Responding to event 0x%02x failed with status 0x%02x\n", packet[2], status);
840     }
841 }
842 
843 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
844     UNUSED(channel);
845     UNUSED(size);
846     uint8_t  status = 0xFF;
847 
848     if (packet_type != HCI_EVENT_PACKET) return;
849     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
850 
851     status = packet[5];
852     if (!media_tracker.avrcp_cid) return;
853 
854     // ignore INTERIM status
855     if (status == AVRCP_CTYPE_RESPONSE_INTERIM) return;
856 
857     switch (packet[2]){
858         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
859             printf("AVRCP Controller: notification absolute volume changed %d %%\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet) * 100 / 127);
860             break;
861         case AVRCP_SUBEVENT_GET_CAPABILITY_EVENT_ID:
862             printf("Remote supports EVENT_ID 0x%02x\n", avrcp_subevent_get_capability_event_id_get_event_id(packet));
863             break;
864         case AVRCP_SUBEVENT_GET_CAPABILITY_EVENT_ID_DONE:
865             printf("automatically enable notifications\n");
866             avrcp_controller_enable_notification(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
867             break;
868         default:
869             break;
870     }
871 }
872 
873 #ifdef HAVE_BTSTACK_STDIN
874 static void show_usage(void){
875     bd_addr_t      iut_address;
876     gap_local_bd_addr(iut_address);
877     printf("\n--- Bluetooth  A2DP Source/AVRCP Demo %s ---\n", bd_addr_to_str(iut_address));
878     printf("b      - A2DP Source create connection to addr %s\n", device_addr_string);
879     printf("B      - A2DP Source disconnect\n");
880     printf("c      - AVRCP create connection to addr %s\n", device_addr_string);
881     printf("C      - AVRCP disconnect\n");
882     printf("D      - delete all link keys\n");
883 
884     printf("x      - start streaming sine\n");
885     if (hxcmod_initialized){
886         printf("z      - start streaming '%s'\n", mod_name);
887     }
888     printf("p      - pause streaming\n");
889     printf("w      - reconfigure stream for 44100 Hz\n");
890     printf("e      - reconfigure stream for 48000 Hz\n");
891     printf("t      - volume up\n");
892     printf("T      - volume down\n");
893     printf("v      - volume up (via set absolute volume)\n");
894     printf("V      - volume down (via set absolute volume)\n");
895 
896     printf("---\n");
897 }
898 
899 static void stdin_process(char cmd){
900     uint8_t status = ERROR_CODE_SUCCESS;
901     switch (cmd){
902         case 'b':
903             status = a2dp_source_establish_stream(device_addr, media_tracker.local_seid, &media_tracker.a2dp_cid);
904             printf("%c - Create A2DP Source connection to addr %s, cid 0x%02x.\n", cmd, bd_addr_to_str(device_addr), media_tracker.a2dp_cid);
905             break;
906         case 'B':
907             printf("%c - A2DP Source Disconnect from cid 0x%2x\n", cmd, media_tracker.a2dp_cid);
908             status = a2dp_source_disconnect(media_tracker.a2dp_cid);
909             break;
910         case 'c':
911             printf("%c - Create AVRCP connection to addr %s.\n", cmd, bd_addr_to_str(device_addr));
912             status = avrcp_connect(device_addr, &media_tracker.avrcp_cid);
913             break;
914         case 'C':
915             printf("%c - AVRCP disconnect\n", cmd);
916             status = avrcp_disconnect(media_tracker.avrcp_cid);
917             break;
918         case 'D':
919             printf("Deleting all link keys\n");
920             gap_delete_all_link_keys();
921             break;
922         case '\n':
923         case '\r':
924             break;
925 
926         case 't':
927             printf(" - volume up\n");
928             status = avrcp_controller_volume_up(media_tracker.avrcp_cid);
929             break;
930         case 'T':
931             printf(" - volume down\n");
932             status = avrcp_controller_volume_down(media_tracker.avrcp_cid);
933             break;
934 
935         case 'v':
936             if (media_tracker.volume > 117){
937                 media_tracker.volume = 127;
938             } else {
939                 media_tracker.volume += 10;
940             }
941             printf(" - volume up (via set absolute volume) %d%% (%d)\n",  media_tracker.volume * 127/100,  media_tracker.volume);
942             status = avrcp_controller_set_absolute_volume(media_tracker.avrcp_cid, media_tracker.volume);
943             break;
944         case 'V':
945             if (media_tracker.volume < 10){
946                 media_tracker.volume = 0;
947             } else {
948                 media_tracker.volume -= 10;
949             }
950             printf(" - volume down (via set absolute volume) %d%% (%d)\n",  media_tracker.volume * 127/100,  media_tracker.volume);
951             status = avrcp_controller_set_absolute_volume(media_tracker.avrcp_cid, media_tracker.volume);
952             break;
953 
954         case 'x':
955             if (media_tracker.avrcp_cid){
956                 avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, &tracks[data_source], sizeof(tracks)/sizeof(avrcp_track_t));
957             }
958             printf("%c - Play sine.\n", cmd);
959             data_source = STREAM_SINE;
960             if (!media_tracker.stream_opened) break;
961             status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
962             break;
963         case 'z':
964             if (media_tracker.avrcp_cid){
965                 avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, &tracks[data_source], sizeof(tracks)/sizeof(avrcp_track_t));
966             }
967             printf("%c - Play mod.\n", cmd);
968             data_source = STREAM_MOD;
969             if (!media_tracker.stream_opened) break;
970             status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
971             break;
972 
973         case 'p':
974             if (!media_tracker.stream_opened) break;
975             printf("%c - Pause stream.\n", cmd);
976             status = a2dp_source_pause_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
977             break;
978 
979         case 'w':
980             if (!media_tracker.stream_opened) break;
981             if (play_info.status == AVRCP_PLAYBACK_STATUS_PLAYING){
982                 printf("Stream cannot be reconfigured while playing, please pause stream first\n");
983                 break;
984             }
985             new_sample_rate = 44100;
986             if (current_sample_rate == new_sample_rate){
987                 printf("%c - Stream already configured for %d Hz.\n", cmd, new_sample_rate);
988             } else {
989                 printf("%c - Reconfigure for %d Hz.\n", cmd, new_sample_rate);
990                 status = a2dp_source_reconfigure_stream_sampling_frequency(media_tracker.a2dp_cid, new_sample_rate);
991             }
992             break;
993 
994         case 'e':
995             if (!media_tracker.stream_opened) break;
996             if (play_info.status == AVRCP_PLAYBACK_STATUS_PLAYING){
997                 printf("Stream cannot be reconfigured while playing, please pause stream first\n");
998                 break;
999             }
1000             new_sample_rate = 48000;
1001             if (current_sample_rate == new_sample_rate){
1002                 printf("%c - Stream already configured for %d Hz.\n", cmd, new_sample_rate);
1003             } else {
1004                 printf("%c - Reconfigure for %d Hz.\n", cmd, new_sample_rate);
1005                 status = a2dp_source_reconfigure_stream_sampling_frequency(media_tracker.a2dp_cid, new_sample_rate);
1006             }
1007             break;
1008 
1009         default:
1010             show_usage();
1011             return;
1012     }
1013     if (status != ERROR_CODE_SUCCESS){
1014         printf("Could not perform command \'%c\', status 0x%02x\n", cmd, status);
1015     }
1016 }
1017 #endif
1018 
1019 
1020 int btstack_main(int argc, const char * argv[]);
1021 int btstack_main(int argc, const char * argv[]){
1022     (void)argc;
1023     (void)argv;
1024 
1025     int err = a2dp_source_and_avrcp_services_init();
1026     if (err) return err;
1027     // turn on!
1028     hci_power_control(HCI_POWER_ON);
1029     return 0;
1030 }
1031 /* EXAMPLE_END */
1032