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