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