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