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