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