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