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