xref: /btstack/example/a2dp_sink_demo.c (revision c824d78c0a34df89b57d535abafcc7dacf30bb06)
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_sink_demo.c"
39 
40 /*
41  * a2dp_sink_demo.c
42  */
43 
44 // *****************************************************************************
45 /* EXAMPLE_START(a2dp_sink_demo): A2DP Sink - Receive Audio Stream and Control Playback
46  *
47  * @text This A2DP Sink example demonstrates how to use the A2DP Sink service to
48  * receive an audio data stream from a remote A2DP Source device. In addition,
49  * the AVRCP Controller is used to get information on currently played media,
50  * such are title, artist and album, as well as to control the playback,
51  * i.e. to play, stop, repeat, etc. If HAVE_BTSTACK_STDIN is set, press SPACE on
52  * the console to show the available AVDTP and AVRCP commands.
53  *
54  * @text To test with a remote device, e.g. a mobile phone,
55  * pair from the remote device with the demo, then start playing music on the remote device.
56  * Alternatively, set the device_addr_string to the Bluetooth address of your
57  * remote device in the code, and call connect from the UI.
58  *
59  * @text For more info on BTstack audio, see our blog post
60  * [A2DP Sink and Source on STM32 F4 Discovery Board](http://bluekitchen-gmbh.com/a2dp-sink-and-source-on-stm32-f4-discovery-board/).
61  *
62  */
63 // *****************************************************************************
64 
65 #include <inttypes.h>
66 #include <stdint.h>
67 #include <stdio.h>
68 #include <string.h>
69 
70 #include "btstack.h"
71 #include "btstack_resample.h"
72 
73 //#define AVRCP_BROWSING_ENABLED
74 
75 #ifdef HAVE_BTSTACK_STDIN
76 #include "btstack_stdin.h"
77 #endif
78 
79 #include "btstack_ring_buffer.h"
80 
81 #ifdef HAVE_POSIX_FILE_IO
82 #include "wav_util.h"
83 #define STORE_TO_WAV_FILE
84 #endif
85 
86 #define NUM_CHANNELS 2
87 #define BYTES_PER_FRAME     (2*NUM_CHANNELS)
88 #define MAX_SBC_FRAME_SIZE 120
89 
90 #ifdef HAVE_BTSTACK_STDIN
91 static const char * device_addr_string = "5C:F3:70:60:7B:87"; // pts
92 static bd_addr_t device_addr;
93 #endif
94 
95 static btstack_packet_callback_registration_t hci_event_callback_registration;
96 
97 static uint8_t  sdp_avdtp_sink_service_buffer[150];
98 static uint8_t  sdp_avrcp_target_service_buffer[150];
99 static uint8_t  sdp_avrcp_controller_service_buffer[200];
100 static uint8_t  device_id_sdp_service_buffer[100];
101 
102 // we support all configurations with bitpool 2-53
103 static uint8_t media_sbc_codec_capabilities[] = {
104     0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
105     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
106     2, 53
107 };
108 
109 // WAV File
110 #ifdef STORE_TO_WAV_FILE
111 static uint32_t audio_frame_count = 0;
112 static char * wav_filename = "a2dp_sink_demo.wav";
113 #endif
114 
115 // SBC Decoder for WAV file or live playback
116 static btstack_sbc_decoder_state_t state;
117 static btstack_sbc_mode_t mode = SBC_MODE_STANDARD;
118 
119 // ring buffer for SBC Frames
120 // below 30: add samples, 30-40: fine, above 40: drop samples
121 #define OPTIMAL_FRAMES_MIN 30
122 #define OPTIMAL_FRAMES_MAX 40
123 #define ADDITIONAL_FRAMES  20
124 static uint8_t sbc_frame_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE];
125 static btstack_ring_buffer_t sbc_frame_ring_buffer;
126 static unsigned int sbc_frame_size;
127 
128 // overflow buffer for not fully used sbc frames, with additional frames for resampling
129 static uint8_t decoded_audio_storage[(128+16) * BYTES_PER_FRAME];
130 static btstack_ring_buffer_t decoded_audio_ring_buffer;
131 
132 static int media_initialized = 0;
133 static int audio_stream_started;
134 static btstack_resample_t resample_instance;
135 
136 // temp storage of lower-layer request for audio samples
137 static int16_t * request_buffer;
138 static int       request_frames;
139 
140 // sink state
141 static int volume_percentage = 0;
142 static avrcp_battery_status_t battery_status = AVRCP_BATTERY_STATUS_WARNING;
143 
144 typedef struct {
145     uint8_t  reconfigure;
146     uint8_t  num_channels;
147     uint16_t sampling_frequency;
148     uint8_t  block_length;
149     uint8_t  subbands;
150     uint8_t  min_bitpool_value;
151     uint8_t  max_bitpool_value;
152     btstack_sbc_channel_mode_t      channel_mode;
153     btstack_sbc_allocation_method_t allocation_method;
154 } media_codec_configuration_sbc_t;
155 
156 typedef enum {
157     STREAM_STATE_CLOSED,
158     STREAM_STATE_OPEN,
159     STREAM_STATE_PLAYING,
160     STREAM_STATE_PAUSED,
161 } stream_state_t;
162 
163 typedef struct {
164     uint8_t  a2dp_local_seid;
165     uint8_t  media_sbc_codec_configuration[4];
166 } a2dp_sink_demo_stream_endpoint_t;
167 static a2dp_sink_demo_stream_endpoint_t a2dp_sink_demo_stream_endpoint;
168 
169 typedef struct {
170     bd_addr_t addr;
171     uint16_t  a2dp_cid;
172     uint8_t   a2dp_local_seid;
173     stream_state_t stream_state;
174     media_codec_configuration_sbc_t sbc_configuration;
175 } a2dp_sink_demo_a2dp_connection_t;
176 static a2dp_sink_demo_a2dp_connection_t a2dp_sink_demo_a2dp_connection;
177 
178 typedef struct {
179     bd_addr_t addr;
180     uint16_t  avrcp_cid;
181     bool playing;
182 } a2dp_sink_demo_avrcp_connection_t;
183 static a2dp_sink_demo_avrcp_connection_t a2dp_sink_demo_avrcp_connection;
184 
185 /* @section Main Application Setup
186  *
187  * @text The Listing MainConfiguration shows how to set up AD2P Sink and AVRCP services.
188  * Besides calling init() method for each service, you'll also need to register several packet handlers:
189  * - hci_packet_handler - handles legacy pairing, here by using fixed '0000' pin code.
190  * - a2dp_sink_packet_handler - handles events on stream connection status (established, released), the media codec configuration, and, the status of the stream itself (opened, paused, stopped).
191  * - handle_l2cap_media_data_packet - used to receive streaming data. If STORE_TO_WAV_FILE directive (check btstack_config.h) is used, the SBC decoder will be used to decode the SBC data into PCM frames. The resulting PCM frames are then processed in the SBC Decoder callback.
192  * - avrcp_packet_handler - receives connect/disconnect event.
193  * - avrcp_controller_packet_handler - receives answers for sent AVRCP commands.
194  * - avrcp_target_packet_handler - receives AVRCP commands, and registered notifications.
195  * - 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.
196  *
197  * @text To announce A2DP Sink and AVRCP services, you need to create corresponding
198  * SDP records and register them with the SDP service.
199  *
200  * @text Note, currently only the SBC codec is supported.
201  * If you want to store the audio data in a file, you'll need to define STORE_TO_WAV_FILE.
202  * If STORE_TO_WAV_FILE directive is defined, the SBC decoder needs to get initialized when a2dp_sink_packet_handler receives event A2DP_SUBEVENT_STREAM_STARTED.
203  * The initialization of the SBC decoder requires a callback that handles PCM data:
204  * - handle_pcm_data - handles PCM audio frames. Here, they are stored in a wav file if STORE_TO_WAV_FILE is defined, and/or played using the audio library.
205  */
206 
207 /* LISTING_START(MainConfiguration): Setup Audio Sink and AVRCP services */
208 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
209 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t event_size);
210 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size);
211 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
212 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
213 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
214 #ifdef HAVE_BTSTACK_STDIN
215 static void stdin_process(char cmd);
216 #endif
217 
218 static int a2dp_and_avrcp_setup(void){
219 
220     l2cap_init();
221 
222 #ifdef ENABLE_BLE
223     // Initialize LE Security Manager. Needed for cross-transport key derivation
224     sm_init();
225 #endif
226 
227     // Initialize AVDTP Sink
228     a2dp_sink_init();
229     a2dp_sink_register_packet_handler(&a2dp_sink_packet_handler);
230     a2dp_sink_register_media_handler(&handle_l2cap_media_data_packet);
231 
232     // Create stream endpoint
233     a2dp_sink_demo_stream_endpoint_t * stream_endpoint = &a2dp_sink_demo_stream_endpoint;
234     avdtp_stream_endpoint_t * local_stream_endpoint = a2dp_sink_create_stream_endpoint(AVDTP_AUDIO,
235                                                                                        AVDTP_CODEC_SBC, media_sbc_codec_capabilities, sizeof(media_sbc_codec_capabilities),
236                                                                                        stream_endpoint->media_sbc_codec_configuration, sizeof(stream_endpoint->media_sbc_codec_configuration));
237     if (!local_stream_endpoint){
238         printf("A2DP Sink: not enough memory to create local stream endpoint\n");
239         return 1;
240     }
241 
242     // Store stream enpoint's SEP ID, as it is used by A2DP API to identify the stream endpoint
243     stream_endpoint->a2dp_local_seid = avdtp_local_seid(local_stream_endpoint);
244 
245     // Initialize AVRCP service
246     avrcp_init();
247     avrcp_register_packet_handler(&avrcp_packet_handler);
248 
249     // Initialize AVRCP Controller
250     avrcp_controller_init();
251     avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler);
252 
253      // Initialize AVRCP Target
254     avrcp_target_init();
255     avrcp_target_register_packet_handler(&avrcp_target_packet_handler);
256 
257     // Initialize SDP
258     sdp_init();
259 
260     // Create A2DP Sink service record and register it with SDP
261     memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer));
262     a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, 0x10001, AVDTP_SINK_FEATURE_MASK_HEADPHONE, NULL, NULL);
263     sdp_register_service(sdp_avdtp_sink_service_buffer);
264 
265     // Create AVRCP Controller service record and register it with SDP. We send Category 1 commands to the media player, e.g. play/pause
266     memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
267     uint16_t controller_supported_features = AVRCP_FEATURE_MASK_CATEGORY_PLAYER_OR_RECORDER;
268 #ifdef AVRCP_BROWSING_ENABLED
269     controller_supported_features |= AVRCP_FEATURE_MASK_BROWSING;
270 #endif
271     avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10002, controller_supported_features, NULL, NULL);
272     sdp_register_service(sdp_avrcp_controller_service_buffer);
273 
274     // Create AVRCP Target service record and register it with SDP. We receive Category 2 commands from the media player, e.g. volume up/down
275     memset(sdp_avrcp_target_service_buffer, 0, sizeof(sdp_avrcp_target_service_buffer));
276     uint16_t target_supported_features = AVRCP_FEATURE_MASK_CATEGORY_MONITOR_OR_AMPLIFIER;
277     avrcp_target_create_sdp_record(sdp_avrcp_target_service_buffer, 0x10003, target_supported_features, NULL, NULL);
278     sdp_register_service(sdp_avrcp_target_service_buffer);
279 
280     // Create Device ID (PnP) service record and register it with SDP
281     memset(device_id_sdp_service_buffer, 0, sizeof(device_id_sdp_service_buffer));
282     device_id_create_sdp_record(device_id_sdp_service_buffer, 0x10004, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
283     sdp_register_service(device_id_sdp_service_buffer);
284 
285     // Set local name with a template Bluetooth address, that will be automatically
286     // replaced with an actual address once it is available, i.e. when BTstack boots
287     // up and starts talking to a Bluetooth module.
288     gap_set_local_name("A2DP Sink Demo 00:00:00:00:00:00");
289 
290     // allot to show up in Bluetooth inquiry
291     gap_discoverable_control(1);
292 
293     // Service Class: Audio, Major Device Class: Audio, Minor: Loudspeaker
294     gap_set_class_of_device(0x200414);
295 
296     // allow for role switch in general and sniff mode
297     gap_set_default_link_policy_settings( LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE );
298 
299     // allow for role switch on outgoing connections - this allows A2DP Source, e.g. smartphone, to become master when we re-connect to it
300     gap_set_allow_role_switch(true);
301 
302     // Register for HCI events
303     hci_event_callback_registration.callback = &hci_packet_handler;
304     hci_add_event_handler(&hci_event_callback_registration);
305 
306 #ifdef HAVE_POSIX_FILE_IO
307     if (!btstack_audio_sink_get_instance()){
308         printf("No audio playback.\n");
309     } else {
310         printf("Audio playback supported.\n");
311     }
312 #ifdef STORE_TO_WAV_FILE
313    printf("Audio will be stored to \'%s\' file.\n",  wav_filename);
314 #endif
315 #endif
316     return 0;
317 }
318 /* LISTING_END */
319 
320 static void playback_handler(int16_t * buffer, uint16_t num_audio_frames){
321 
322 #ifdef STORE_TO_WAV_FILE
323     int       wav_samples = num_audio_frames * NUM_CHANNELS;
324     int16_t * wav_buffer  = buffer;
325 #endif
326 
327     // called from lower-layer but guaranteed to be on main thread
328     if (sbc_frame_size == 0){
329         memset(buffer, 0, num_audio_frames * BYTES_PER_FRAME);
330         return;
331     }
332 
333     // first fill from resampled audio
334     uint32_t bytes_read;
335     btstack_ring_buffer_read(&decoded_audio_ring_buffer, (uint8_t *) buffer, num_audio_frames * BYTES_PER_FRAME, &bytes_read);
336     buffer          += bytes_read / NUM_CHANNELS;
337     num_audio_frames   -= bytes_read / BYTES_PER_FRAME;
338 
339     // then start decoding sbc frames using request_* globals
340     request_buffer = buffer;
341     request_frames = num_audio_frames;
342     while (request_frames && btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) >= sbc_frame_size){
343         // decode frame
344         uint8_t sbc_frame[MAX_SBC_FRAME_SIZE];
345         btstack_ring_buffer_read(&sbc_frame_ring_buffer, sbc_frame, sbc_frame_size, &bytes_read);
346         btstack_sbc_decoder_process_data(&state, 0, sbc_frame, sbc_frame_size);
347     }
348 
349 #ifdef STORE_TO_WAV_FILE
350     audio_frame_count += num_audio_frames;
351     wav_writer_write_int16(wav_samples, wav_buffer);
352 #endif
353 }
354 
355 static void handle_pcm_data(int16_t * data, int num_audio_frames, int num_channels, int sample_rate, void * context){
356     UNUSED(sample_rate);
357     UNUSED(context);
358     UNUSED(num_channels);   // must be stereo == 2
359 
360     const btstack_audio_sink_t * audio_sink = btstack_audio_sink_get_instance();
361     if (!audio_sink){
362 #ifdef STORE_TO_WAV_FILE
363         audio_frame_count += num_audio_frames;
364         wav_writer_write_int16(num_audio_frames * NUM_CHANNELS, data);
365 #endif
366         return;
367     }
368 
369     // resample into request buffer - add some additional space for resampling
370     int16_t  output_buffer[(128+16) * NUM_CHANNELS]; // 16 * 8 * 2
371     uint32_t resampled_frames = btstack_resample_block(&resample_instance, data, num_audio_frames, output_buffer);
372 
373     // store data in btstack_audio buffer first
374     int frames_to_copy = btstack_min(resampled_frames, request_frames);
375     memcpy(request_buffer, output_buffer, frames_to_copy * BYTES_PER_FRAME);
376     request_frames  -= frames_to_copy;
377     request_buffer  += frames_to_copy * NUM_CHANNELS;
378 
379     // and rest in ring buffer
380     int frames_to_store = resampled_frames - frames_to_copy;
381     if (frames_to_store){
382         int status = btstack_ring_buffer_write(&decoded_audio_ring_buffer, (uint8_t *)&output_buffer[frames_to_copy * NUM_CHANNELS], frames_to_store * BYTES_PER_FRAME);
383         if (status){
384             printf("Error storing samples in PCM ring buffer!!!\n");
385         }
386     }
387 }
388 
389 static int media_processing_init(media_codec_configuration_sbc_t * configuration){
390     if (media_initialized) return 0;
391 
392     btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL);
393 
394 #ifdef STORE_TO_WAV_FILE
395     wav_writer_open(wav_filename, configuration->num_channels, configuration->sampling_frequency);
396 #endif
397 
398     btstack_ring_buffer_init(&sbc_frame_ring_buffer, sbc_frame_storage, sizeof(sbc_frame_storage));
399     btstack_ring_buffer_init(&decoded_audio_ring_buffer, decoded_audio_storage, sizeof(decoded_audio_storage));
400     btstack_resample_init(&resample_instance, configuration->num_channels);
401 
402     // setup audio playback
403     const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance();
404     if (audio){
405         audio->init(NUM_CHANNELS, configuration->sampling_frequency, &playback_handler);
406     }
407 
408     audio_stream_started = 0;
409     media_initialized = 1;
410     return 0;
411 }
412 
413 static void media_processing_start(void){
414     if (!media_initialized) return;
415     // setup audio playback
416     const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance();
417     if (audio){
418         audio->start_stream();
419     }
420     audio_stream_started = 1;
421 }
422 
423 static void media_processing_pause(void){
424     if (!media_initialized) return;
425     // stop audio playback
426     audio_stream_started = 0;
427     const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance();
428     if (audio){
429         audio->stop_stream();
430     }
431 }
432 
433 static void media_processing_close(void){
434     if (!media_initialized) return;
435     media_initialized = 0;
436     audio_stream_started = 0;
437     sbc_frame_size = 0;
438 
439 #ifdef STORE_TO_WAV_FILE
440     wav_writer_close();
441     uint32_t total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr;
442 
443     printf("WAV Writer: Decoding done. Processed %u SBC frames:\n - %d good\n - %d bad\n", total_frames_nr, state.good_frames_nr, total_frames_nr - state.good_frames_nr);
444     printf("WAV Writer: Wrote %u audio frames to wav file: %s\n", audio_frame_count, wav_filename);
445 #endif
446 
447     // stop audio playback
448     const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance();
449     if (audio){
450         printf("close stream\n");
451         audio->close();
452     }
453 }
454 
455 /* @section Handle Media Data Packet
456  *
457  * @text Here the audio data, are received through the handle_l2cap_media_data_packet callback.
458  * Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet.
459  * The SBC frame will be stored in a ring buffer for later processing (instead of decoding it to PCM right away which would require a much larger buffer).
460  * If the audio stream wasn't started already and there are enough SBC frames in the ring buffer, start playback.
461  */
462 
463 static int read_media_data_header(uint8_t * packet, int size, int * offset, avdtp_media_packet_header_t * media_header);
464 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header);
465 
466 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size){
467     UNUSED(seid);
468     int pos = 0;
469 
470     avdtp_media_packet_header_t media_header;
471     if (!read_media_data_header(packet, size, &pos, &media_header)) return;
472 
473     avdtp_sbc_codec_header_t sbc_header;
474     if (!read_sbc_header(packet, size, &pos, &sbc_header)) return;
475 
476     const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance();
477     // process data right away if there's no audio implementation active, e.g. on posix systems to store as .wav
478     if (!audio){
479         btstack_sbc_decoder_process_data(&state, 0, packet+pos, size-pos);
480         return;
481     }
482 
483     // store sbc frame size for buffer management
484     sbc_frame_size = (size-pos)/ sbc_header.num_frames;
485 
486     int status = btstack_ring_buffer_write(&sbc_frame_ring_buffer, packet+pos, size-pos);
487     if (status != ERROR_CODE_SUCCESS){
488         printf("Error storing samples in SBC ring buffer!!!\n");
489     }
490 
491     // decide on audio sync drift based on number of sbc frames in queue
492     int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) / sbc_frame_size;
493     uint32_t resampling_factor;
494 
495     // nominal factor (fixed-point 2^16) and compensation offset
496     uint32_t nominal_factor = 0x10000;
497     uint32_t compensation   = 0x00100;
498 
499     if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){
500     	resampling_factor = nominal_factor - compensation;    // stretch samples
501     } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){
502     	resampling_factor = nominal_factor;                   // nothing to do
503     } else {
504     	resampling_factor = nominal_factor + compensation;    // compress samples
505     }
506 
507     btstack_resample_set_factor(&resample_instance, resampling_factor);
508 
509     // start stream if enough frames buffered
510     if (!audio_stream_started && sbc_frames_in_buffer >= OPTIMAL_FRAMES_MIN){
511         media_processing_start();
512     }
513 }
514 
515 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header){
516     int sbc_header_len = 12; // without crc
517     int pos = *offset;
518 
519     if (size - pos < sbc_header_len){
520         printf("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size-pos);
521         return 0;
522     }
523 
524     sbc_header->fragmentation = get_bit16(packet[pos], 7);
525     sbc_header->starting_packet = get_bit16(packet[pos], 6);
526     sbc_header->last_packet = get_bit16(packet[pos], 5);
527     sbc_header->num_frames = packet[pos] & 0x0f;
528     pos++;
529     *offset = pos;
530     return 1;
531 }
532 
533 static int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header){
534     int media_header_len = 12; // without crc
535     int pos = *offset;
536 
537     if (size - pos < media_header_len){
538         printf("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size-pos);
539         return 0;
540     }
541 
542     media_header->version = packet[pos] & 0x03;
543     media_header->padding = get_bit16(packet[pos],2);
544     media_header->extension = get_bit16(packet[pos],3);
545     media_header->csrc_count = (packet[pos] >> 4) & 0x0F;
546     pos++;
547 
548     media_header->marker = get_bit16(packet[pos],0);
549     media_header->payload_type  = (packet[pos] >> 1) & 0x7F;
550     pos++;
551 
552     media_header->sequence_number = big_endian_read_16(packet, pos);
553     pos+=2;
554 
555     media_header->timestamp = big_endian_read_32(packet, pos);
556     pos+=4;
557 
558     media_header->synchronization_source = big_endian_read_32(packet, pos);
559     pos+=4;
560     *offset = pos;
561     return 1;
562 }
563 
564 static void dump_sbc_configuration(media_codec_configuration_sbc_t * configuration){
565     printf("    - num_channels: %d\n", configuration->num_channels);
566     printf("    - sampling_frequency: %d\n", configuration->sampling_frequency);
567     printf("    - channel_mode: %d\n", configuration->channel_mode);
568     printf("    - block_length: %d\n", configuration->block_length);
569     printf("    - subbands: %d\n", configuration->subbands);
570     printf("    - allocation_method: %d\n", configuration->allocation_method);
571     printf("    - bitpool_value [%d, %d] \n", configuration->min_bitpool_value, configuration->max_bitpool_value);
572     printf("\n");
573 }
574 
575 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
576     UNUSED(channel);
577     UNUSED(size);
578     uint16_t local_cid;
579     uint8_t  status;
580     bd_addr_t address;
581 
582     a2dp_sink_demo_avrcp_connection_t * connection = &a2dp_sink_demo_avrcp_connection;
583 
584     if (packet_type != HCI_EVENT_PACKET) return;
585     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
586     switch (packet[2]){
587         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
588             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
589             status = avrcp_subevent_connection_established_get_status(packet);
590             if (status != ERROR_CODE_SUCCESS){
591                 printf("AVRCP: Connection failed: status 0x%02x\n", status);
592                 connection->avrcp_cid = 0;
593                 return;
594             }
595 
596             connection->avrcp_cid = local_cid;
597             avrcp_subevent_connection_established_get_bd_addr(packet, address);
598             printf("AVRCP: Connected to %s, cid 0x%02x\n", bd_addr_to_str(address), connection->avrcp_cid);
599 
600             avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
601             avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_BATT_STATUS_CHANGED);
602             avrcp_target_battery_status_changed(connection->avrcp_cid, battery_status);
603 
604             // automatically enable notifications
605             avrcp_controller_enable_notification(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
606             avrcp_controller_enable_notification(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
607             avrcp_controller_enable_notification(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
608             return;
609         }
610 
611         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
612             printf("AVRCP: Channel released: cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
613             connection->avrcp_cid = 0;
614             return;
615         default:
616             break;
617     }
618 }
619 
620 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
621     UNUSED(channel);
622     UNUSED(size);
623 
624     // helper to print c strings
625     uint8_t  avrcp_subevent_value[256];
626     uint8_t play_status;
627 
628     a2dp_sink_demo_avrcp_connection_t * avrcp_connection = &a2dp_sink_demo_avrcp_connection;
629 
630     if (packet_type != HCI_EVENT_PACKET) return;
631     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
632     if (avrcp_connection->avrcp_cid == 0) return;
633 
634     memset(avrcp_subevent_value, 0, sizeof(avrcp_subevent_value));
635     switch (packet[2]){
636         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:
637             printf("AVRCP Controller: Playback position changed, position %d ms\n", (unsigned int) avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet));
638             break;
639         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
640             printf("AVRCP Controller: Playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
641             play_status = avrcp_subevent_notification_playback_status_changed_get_play_status(packet);
642             switch (play_status){
643                 case AVRCP_PLAYBACK_STATUS_PLAYING:
644                     avrcp_connection->playing = true;
645                     break;
646                 default:
647                     avrcp_connection->playing = false;
648                     break;
649             }
650             printf("AVRCP Controller: Playback status changed %s\n", avrcp_play_status2str(play_status));            return;
651         case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
652             printf("AVRCP Controller: Playing content changed\n");
653             return;
654         case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
655             printf("AVRCP Controller: Track changed\n");
656             return;
657         case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
658             printf("AVRCP Controller: Changed\n");
659             return;
660         case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{
661             uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
662             uint8_t repeat_mode  = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
663             printf("AVRCP Controller: %s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
664             break;
665         }
666         case AVRCP_SUBEVENT_NOW_PLAYING_TRACK_INFO:
667             printf("AVRCP Controller:     Track: %d\n", avrcp_subevent_now_playing_track_info_get_track(packet));
668             break;
669 
670         case AVRCP_SUBEVENT_NOW_PLAYING_TOTAL_TRACKS_INFO:
671             printf("AVRCP Controller:     Total Tracks: %d\n", avrcp_subevent_now_playing_total_tracks_info_get_total_tracks(packet));
672             break;
673 
674         case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO:
675             if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0){
676                 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet));
677                 printf("AVRCP Controller:     Title: %s\n", avrcp_subevent_value);
678             }
679             break;
680 
681         case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO:
682             if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0){
683                 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet));
684                 printf("AVRCP Controller:     Artist: %s\n", avrcp_subevent_value);
685             }
686             break;
687 
688         case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO:
689             if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0){
690                 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet));
691                 printf("AVRCP Controller:     Album: %s\n", avrcp_subevent_value);
692             }
693             break;
694 
695         case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO:
696             if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0){
697                 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet));
698                 printf("AVRCP Controller:     Genre: %s\n", avrcp_subevent_value);
699             }
700             break;
701 
702         case AVRCP_SUBEVENT_PLAY_STATUS:
703             printf("AVRCP Controller: Song length %"PRIu32" ms, Song position %"PRIu32" ms, Play status %s\n",
704                 avrcp_subevent_play_status_get_song_length(packet),
705                 avrcp_subevent_play_status_get_song_position(packet),
706                 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
707             break;
708 
709         case AVRCP_SUBEVENT_OPERATION_COMPLETE:
710             printf("AVRCP Controller: %s complete\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
711             break;
712 
713         case AVRCP_SUBEVENT_OPERATION_START:
714             printf("AVRCP Controller: %s start\n", avrcp_operation2str(avrcp_subevent_operation_start_get_operation_id(packet)));
715             break;
716 
717         case AVRCP_SUBEVENT_NOTIFICATION_EVENT_TRACK_REACHED_END:
718             printf("AVRCP Controller: Track reached end\n");
719             break;
720 
721         case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
722             printf("AVRCP Controller: Set Player App Value %s\n", avrcp_ctype2str(avrcp_subevent_player_application_value_response_get_command_type(packet)));
723             break;
724 
725         default:
726             break;
727     }
728 }
729 
730 static void avrcp_volume_changed(uint8_t volume){
731     const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance();
732     if (audio){
733         audio->set_volume(volume);
734     }
735 }
736 
737 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
738     UNUSED(channel);
739     UNUSED(size);
740 
741     if (packet_type != HCI_EVENT_PACKET) return;
742     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
743 
744     uint8_t volume;
745     char const * button_state;
746     avrcp_operation_id_t operation_id;
747 
748     switch (packet[2]){
749         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
750             volume = avrcp_subevent_notification_volume_changed_get_absolute_volume(packet);
751             volume_percentage = volume * 100 / 127;
752             printf("AVRCP Target    : Volume set to %d%% (%d)\n", volume_percentage, volume);
753             avrcp_volume_changed(volume);
754             break;
755 
756         case AVRCP_SUBEVENT_OPERATION:
757             operation_id = avrcp_subevent_operation_get_operation_id(packet);
758             button_state = avrcp_subevent_operation_get_button_pressed(packet) > 0 ? "PRESS" : "RELEASE";
759             switch (operation_id){
760                 case AVRCP_OPERATION_ID_VOLUME_UP:
761                     printf("AVRCP Target    : VOLUME UP (%s)\n", button_state);
762                     break;
763                 case AVRCP_OPERATION_ID_VOLUME_DOWN:
764                     printf("AVRCP Target    : VOLUME DOWN (%s)\n", button_state);
765                     break;
766                 default:
767                     return;
768             }
769             break;
770         default:
771             printf("AVRCP Target    : Event 0x%02x is not parsed\n", packet[2]);
772             break;
773     }
774 }
775 
776 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
777     UNUSED(channel);
778     UNUSED(size);
779     if (packet_type != HCI_EVENT_PACKET) return;
780     if (hci_event_packet_get_type(packet) == HCI_EVENT_PIN_CODE_REQUEST) {
781         bd_addr_t address;
782         printf("Pin code request - using '0000'\n");
783         hci_event_pin_code_request_get_bd_addr(packet, address);
784         gap_pin_code_response(address, "0000");
785     }
786 }
787 
788 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
789     UNUSED(channel);
790     UNUSED(size);
791     bd_addr_t address;
792     uint8_t status;
793 
794     uint8_t allocation_method;
795 
796     if (packet_type != HCI_EVENT_PACKET) return;
797     if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return;
798 
799     a2dp_sink_demo_a2dp_connection_t * a2dp_conn = &a2dp_sink_demo_a2dp_connection;
800 
801     switch (packet[2]){
802         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
803             printf("A2DP  Sink      : Received non SBC codec - not implemented\n");
804             break;
805         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
806             printf("A2DP  Sink      : Received SBC codec configuration\n");
807             a2dp_conn->sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
808             a2dp_conn->sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
809             a2dp_conn->sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
810             a2dp_conn->sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
811             a2dp_conn->sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
812             a2dp_conn->sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
813             a2dp_conn->sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
814 
815             allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
816 
817             // Adapt Bluetooth spec definition to SBC Encoder expected input
818             a2dp_conn->sbc_configuration.allocation_method = (btstack_sbc_allocation_method_t)(allocation_method - 1);
819 
820             switch (a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet)){
821                 case AVDTP_CHANNEL_MODE_JOINT_STEREO:
822                     a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
823                     break;
824                 case AVDTP_CHANNEL_MODE_STEREO:
825                     a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_STEREO;
826                     break;
827                 case AVDTP_CHANNEL_MODE_DUAL_CHANNEL:
828                     a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
829                     break;
830                 case AVDTP_CHANNEL_MODE_MONO:
831                     a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_MONO;
832                     break;
833                 default:
834                     btstack_assert(false);
835                     break;
836             }
837             dump_sbc_configuration(&a2dp_conn->sbc_configuration);
838             break;
839         }
840         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
841             a2dp_subevent_stream_established_get_bd_addr(packet, a2dp_conn->addr);
842 
843             status = a2dp_subevent_stream_established_get_status(packet);
844             if (status != ERROR_CODE_SUCCESS){
845                 printf("A2DP  Sink      : Streaming connection failed, status 0x%02x\n", status);
846                 break;
847             }
848 
849             a2dp_conn->a2dp_cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
850             a2dp_conn->stream_state = STREAM_STATE_OPEN;
851 
852             printf("A2DP  Sink      : Streaming connection is established, address %s, cid 0x%02X, local seid %d\n",
853                    bd_addr_to_str(address), a2dp_conn->a2dp_cid, a2dp_conn->a2dp_local_seid);
854 #ifdef HAVE_BTSTACK_STDIN
855             // use address for outgoing connections
856             memcpy(device_addr, address, 6);
857 #endif
858             break;
859 
860 #ifdef ENABLE_AVDTP_ACCEPTOR_EXPLICIT_START_STREAM_CONFIRMATION
861         case A2DP_SUBEVENT_START_STREAM_REQUESTED:
862             printf("A2DP  Sink      : Explicit Accept to start stream, local_seid 0x%02x\n", a2dp_subevent_start_stream_requested_get_local_seid(packet));
863             a2dp_sink_start_stream_accept(a2dp_cid, a2dp_local_seid);
864             break;
865 #endif
866         case A2DP_SUBEVENT_STREAM_STARTED:
867             printf("A2DP  Sink      : Stream started\n");
868             a2dp_conn->stream_state = STREAM_STATE_PLAYING;
869             if (a2dp_conn->sbc_configuration.reconfigure){
870                 media_processing_close();
871             }
872             // prepare media processing
873             media_processing_init(&a2dp_conn->sbc_configuration);
874             // audio stream is started when buffer reaches minimal level
875             break;
876 
877         case A2DP_SUBEVENT_STREAM_SUSPENDED:
878             printf("A2DP  Sink      : Stream paused\n");
879             a2dp_conn->stream_state = STREAM_STATE_PAUSED;
880             media_processing_pause();
881             break;
882 
883         case A2DP_SUBEVENT_STREAM_RELEASED:
884             printf("A2DP  Sink      : Stream released\n");
885             a2dp_conn->stream_state = STREAM_STATE_CLOSED;
886             media_processing_close();
887             break;
888 
889         case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
890             printf("A2DP  Sink      : Signaling connection released\n");
891             a2dp_conn->a2dp_cid = 0;
892             media_processing_close();
893             break;
894 
895         default:
896             break;
897     }
898 }
899 
900 #ifdef HAVE_BTSTACK_STDIN
901 static void show_usage(void){
902     bd_addr_t      iut_address;
903     gap_local_bd_addr(iut_address);
904     printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address));
905     printf("b      - AVDTP Sink create  connection to addr %s\n", bd_addr_to_str(device_addr));
906     printf("B      - AVDTP Sink disconnect\n");
907     printf("c      - AVRCP create connection to addr %s\n", bd_addr_to_str(device_addr));
908     printf("C      - AVRCP disconnect\n");
909 
910     printf("w - delay report\n");
911 
912     printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address));
913     printf("O - get play status\n");
914     printf("j - get now playing info\n");
915     printf("k - play\n");
916     printf("K - stop\n");
917     printf("L - pause\n");
918     printf("u - start fast forward\n");
919     printf("U - stop  fast forward\n");
920     printf("n - start rewind\n");
921     printf("N - stop rewind\n");
922     printf("i - forward\n");
923     printf("I - backward\n");
924     printf("M - mute\n");
925     printf("r - skip\n");
926     printf("q - query repeat and shuffle mode\n");
927     printf("v - repeat single track\n");
928     printf("x - repeat all tracks\n");
929     printf("X - disable repeat mode\n");
930     printf("z - shuffle all tracks\n");
931     printf("Z - disable shuffle mode\n");
932 
933     printf("a/A - register/deregister TRACK_CHANGED\n");
934     printf("R/P - register/deregister PLAYBACK_POS_CHANGED\n");
935 
936     printf("s/S - send/release long button press REWIND\n");
937 
938     printf("\n--- Volume and Battery Control ---\n");
939     printf("t - volume up   for 10 percent\n");
940     printf("T - volume down for 10 percent\n");
941     printf("V - toggle Battery status from AVRCP_BATTERY_STATUS_NORMAL to AVRCP_BATTERY_STATUS_FULL_CHARGE\n");
942     printf("---\n");
943 }
944 #endif
945 
946 #ifdef HAVE_BTSTACK_STDIN
947 static void stdin_process(char cmd){
948     uint8_t status = ERROR_CODE_SUCCESS;
949     uint8_t volume;
950     avrcp_battery_status_t old_battery_status;
951 
952     a2dp_sink_demo_stream_endpoint_t *  stream_endpoint  = &a2dp_sink_demo_stream_endpoint;
953     a2dp_sink_demo_a2dp_connection_t *  a2dp_connection  = &a2dp_sink_demo_a2dp_connection;
954     a2dp_sink_demo_avrcp_connection_t * avrcp_connection = &a2dp_sink_demo_avrcp_connection;
955 
956     switch (cmd){
957         case 'b':
958             status = a2dp_sink_establish_stream(device_addr, stream_endpoint->a2dp_local_seid, &a2dp_connection->a2dp_cid);
959             printf(" - Create AVDTP connection to addr %s, and local seid %d, expected cid 0x%02x.\n",
960                    bd_addr_to_str(device_addr), a2dp_connection->a2dp_local_seid, a2dp_connection->a2dp_cid);
961             break;
962         case 'B':
963             printf(" - AVDTP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
964             a2dp_sink_disconnect(a2dp_connection->a2dp_cid);
965             break;
966         case 'c':
967             printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr));
968             status = avrcp_connect(device_addr, &avrcp_connection->avrcp_cid);
969             break;
970         case 'C':
971             printf(" - AVRCP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
972             status = avrcp_disconnect(avrcp_connection->avrcp_cid);
973             break;
974 
975         case '\n':
976         case '\r':
977             break;
978         case 'w':
979             printf("Send delay report\n");
980             avdtp_sink_delay_report(a2dp_connection->a2dp_cid, a2dp_connection->a2dp_local_seid, 100);
981             break;
982         // Volume Control
983         case 't':
984             volume_percentage = volume_percentage <= 90 ? volume_percentage + 10 : 100;
985             volume = volume_percentage * 127 / 100;
986             printf(" - volume up   for 10 percent, %d%% (%d) \n", volume_percentage, volume);
987             status = avrcp_target_volume_changed(avrcp_connection->avrcp_cid, volume);
988             avrcp_volume_changed(volume);
989             break;
990         case 'T':
991             volume_percentage = volume_percentage >= 10 ? volume_percentage - 10 : 0;
992             volume = volume_percentage * 127 / 100;
993             printf(" - volume down for 10 percent, %d%% (%d) \n", volume_percentage, volume);
994             status = avrcp_target_volume_changed(avrcp_connection->avrcp_cid, volume);
995             avrcp_volume_changed(volume);
996             break;
997         case 'V':
998             old_battery_status = battery_status;
999 
1000             if (battery_status < AVRCP_BATTERY_STATUS_FULL_CHARGE){
1001                 battery_status = (avrcp_battery_status_t)((uint8_t) battery_status + 1);
1002             } else {
1003                 battery_status = AVRCP_BATTERY_STATUS_NORMAL;
1004             }
1005             printf(" - toggle battery value, old %d, new %d\n", old_battery_status, battery_status);
1006             status = avrcp_target_battery_status_changed(avrcp_connection->avrcp_cid, battery_status);
1007             break;
1008         case 'O':
1009             printf(" - get play status\n");
1010             status = avrcp_controller_get_play_status(avrcp_connection->avrcp_cid);
1011             break;
1012         case 'j':
1013             printf(" - get now playing info\n");
1014             status = avrcp_controller_get_now_playing_info(avrcp_connection->avrcp_cid);
1015             break;
1016         case 'k':
1017             printf(" - play\n");
1018             status = avrcp_controller_play(avrcp_connection->avrcp_cid);
1019             break;
1020         case 'K':
1021             printf(" - stop\n");
1022             status = avrcp_controller_stop(avrcp_connection->avrcp_cid);
1023             break;
1024         case 'L':
1025             printf(" - pause\n");
1026             status = avrcp_controller_pause(avrcp_connection->avrcp_cid);
1027             break;
1028         case 'u':
1029             printf(" - start fast forward\n");
1030             status = avrcp_controller_press_and_hold_fast_forward(avrcp_connection->avrcp_cid);
1031             break;
1032         case 'U':
1033             printf(" - stop fast forward\n");
1034             status = avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid);
1035             break;
1036         case 'n':
1037             printf(" - start rewind\n");
1038             status = avrcp_controller_press_and_hold_rewind(avrcp_connection->avrcp_cid);
1039             break;
1040         case 'N':
1041             printf(" - stop rewind\n");
1042             status = avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid);
1043             break;
1044         case 'i':
1045             printf(" - forward\n");
1046             status = avrcp_controller_forward(avrcp_connection->avrcp_cid);
1047             break;
1048         case 'I':
1049             printf(" - backward\n");
1050             status = avrcp_controller_backward(avrcp_connection->avrcp_cid);
1051             break;
1052         case 'M':
1053             printf(" - mute\n");
1054             status = avrcp_controller_mute(avrcp_connection->avrcp_cid);
1055             break;
1056         case 'r':
1057             printf(" - skip\n");
1058             status = avrcp_controller_skip(avrcp_connection->avrcp_cid);
1059             break;
1060         case 'q':
1061             printf(" - query repeat and shuffle mode\n");
1062             status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_connection->avrcp_cid);
1063             break;
1064         case 'v':
1065             printf(" - repeat single track\n");
1066             status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK);
1067             break;
1068         case 'x':
1069             printf(" - repeat all tracks\n");
1070             status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS);
1071             break;
1072         case 'X':
1073             printf(" - disable repeat mode\n");
1074             status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_OFF);
1075             break;
1076         case 'z':
1077             printf(" - shuffle all tracks\n");
1078             status = avrcp_controller_set_shuffle_mode(avrcp_connection->avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS);
1079             break;
1080         case 'Z':
1081             printf(" - disable shuffle mode\n");
1082             status = avrcp_controller_set_shuffle_mode(avrcp_connection->avrcp_cid, AVRCP_SHUFFLE_MODE_OFF);
1083             break;
1084         case 'a':
1085             printf("AVRCP: enable notification TRACK_CHANGED\n");
1086             avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
1087             break;
1088         case 'A':
1089             printf("AVRCP: disable notification TRACK_CHANGED\n");
1090             avrcp_controller_disable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
1091             break;
1092         case 'R':
1093             printf("AVRCP: enable notification PLAYBACK_POS_CHANGED\n");
1094             avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
1095             break;
1096         case 'P':
1097             printf("AVRCP: disable notification PLAYBACK_POS_CHANGED\n");
1098             avrcp_controller_disable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
1099             break;
1100          case 's':
1101             printf("AVRCP: send long button press REWIND\n");
1102             avrcp_controller_start_press_and_hold_cmd(avrcp_connection->avrcp_cid, AVRCP_OPERATION_ID_REWIND);
1103             break;
1104         case 'S':
1105             printf("AVRCP: release long button press REWIND\n");
1106             avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid);
1107             break;
1108         default:
1109             show_usage();
1110             return;
1111     }
1112     if (status != ERROR_CODE_SUCCESS){
1113         printf("Could not perform command, status 0x%02x\n", status);
1114     }
1115 }
1116 #endif
1117 
1118 int btstack_main(int argc, const char * argv[]);
1119 int btstack_main(int argc, const char * argv[]){
1120     UNUSED(argc);
1121     (void)argv;
1122 
1123     a2dp_and_avrcp_setup();
1124 
1125 #ifdef HAVE_BTSTACK_STDIN
1126     // parse human-readable Bluetooth address
1127     sscanf_bd_addr(device_addr_string, device_addr);
1128     btstack_stdin_setup(stdin_process);
1129 #endif
1130 
1131     // turn on!
1132     printf("Starting BTstack ...\n");
1133     hci_power_control(HCI_POWER_ON);
1134     return 0;
1135 }
1136 /* EXAMPLE_END */
1137