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