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