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