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