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