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