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