xref: /btstack/example/a2dp_sink_demo.c (revision 9248d4da92a5270b9b323093b9f36845fa0e124d)
1 /*
2  * Copyright (C) 2016 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "a2dp_sink_demo.c"
39 
40 /*
41  * a2dp_sink_demo.c
42  */
43 
44 // *****************************************************************************
45 /* EXAMPLE_START(a2dp_sink_demo): A2DP Sink - Receive Audio Stream and Control Playback
46  *
47  * @text This A2DP Sink example demonstrates how to use the A2DP Sink service to
48  * receive an audio data stream from a remote A2DP Source device. In addition,
49  * the AVRCP Controller is used to get information on currently played media,
50  * such are title, artist and album, as well as to control the playback,
51  * i.e. to play, stop, repeat, etc. If HAVE_BTSTACK_STDIN is set, press SPACE on
52  * the console to show the available AVDTP and AVRCP commands.
53  *
54  * @text To test with a remote device, e.g. a mobile phone,
55  * pair from the remote device with the demo, then start playing music on the remote device.
56  * Alternatively, set the device_addr_string to the Bluetooth address of your
57  * remote device in the code, and call connect from the UI.
58  *
59  * @text For more info on BTstack audio, see our blog post
60  * [A2DP Sink and Source on STM32 F4 Discovery Board](http://bluekitchen-gmbh.com/a2dp-sink-and-source-on-stm32-f4-discovery-board/).
61  *
62  */
63 // *****************************************************************************
64 
65 #include <inttypes.h>
66 #include <stdint.h>
67 #include <stdio.h>
68 #include <string.h>
69 
70 #include "btstack.h"
71 #include "btstack_resample.h"
72 
73 //#define AVRCP_BROWSING_ENABLED
74 
75 #ifdef HAVE_BTSTACK_STDIN
76 #include "btstack_stdin.h"
77 #endif
78 
79 #include "btstack_ring_buffer.h"
80 
81 #ifdef HAVE_POSIX_FILE_IO
82 #include "wav_util.h"
83 #define STORE_TO_WAV_FILE
84 #endif
85 
86 #define NUM_CHANNELS 2
87 #define BYTES_PER_FRAME     (2*NUM_CHANNELS)
88 #define MAX_SBC_FRAME_SIZE 120
89 
90 #ifdef HAVE_BTSTACK_STDIN
91 static const char * device_addr_string = "5C:F3:70:60:7B:87"; // pts
92 static bd_addr_t device_addr;
93 #endif
94 
95 static btstack_packet_callback_registration_t hci_event_callback_registration;
96 
97 static uint8_t  sdp_avdtp_sink_service_buffer[150];
98 static uint8_t  sdp_avrcp_target_service_buffer[150];
99 static uint8_t  sdp_avrcp_controller_service_buffer[200];
100 static uint8_t  device_id_sdp_service_buffer[100];
101 
102 // we support all configurations with bitpool 2-53
103 static uint8_t media_sbc_codec_capabilities[] = {
104     0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
105     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
106     2, 53
107 };
108 
109 // WAV File
110 #ifdef STORE_TO_WAV_FILE
111 static uint32_t audio_frame_count = 0;
112 static char * wav_filename = "a2dp_sink_demo.wav";
113 #endif
114 
115 // SBC Decoder for WAV file or live playback
116 static btstack_sbc_decoder_state_t state;
117 static btstack_sbc_mode_t mode = SBC_MODE_STANDARD;
118 
119 // ring buffer for SBC Frames
120 // below 30: add samples, 30-40: fine, above 40: drop samples
121 #define OPTIMAL_FRAMES_MIN 30
122 #define OPTIMAL_FRAMES_MAX 40
123 #define ADDITIONAL_FRAMES  20
124 static uint8_t sbc_frame_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE];
125 static btstack_ring_buffer_t sbc_frame_ring_buffer;
126 static unsigned int sbc_frame_size;
127 
128 // overflow buffer for not fully used sbc frames, with additional frames for resampling
129 static uint8_t decoded_audio_storage[(128+16) * BYTES_PER_FRAME];
130 static btstack_ring_buffer_t decoded_audio_ring_buffer;
131 
132 static int media_initialized = 0;
133 static int audio_stream_started;
134 static btstack_resample_t resample_instance;
135 
136 // temp storage of lower-layer request for audio samples
137 static int16_t * request_buffer;
138 static int       request_frames;
139 
140 // sink state
141 static int volume_percentage = 0;
142 static avrcp_battery_status_t battery_status = AVRCP_BATTERY_STATUS_WARNING;
143 
144 typedef struct {
145     uint8_t  reconfigure;
146     uint8_t  num_channels;
147     uint16_t sampling_frequency;
148     uint8_t  block_length;
149     uint8_t  subbands;
150     uint8_t  min_bitpool_value;
151     uint8_t  max_bitpool_value;
152     btstack_sbc_channel_mode_t      channel_mode;
153     btstack_sbc_allocation_method_t allocation_method;
154 } media_codec_configuration_sbc_t;
155 
156 typedef 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 }
550 
551 static void media_processing_close(void){
552     if (!media_initialized) return;
553     media_initialized = 0;
554     audio_stream_started = 0;
555     sbc_frame_size = 0;
556 
557 #ifdef STORE_TO_WAV_FILE
558     wav_writer_close();
559     uint32_t total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr;
560 
561     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);
562     printf("WAV Writer: Wrote %u audio frames to wav file: %s\n", audio_frame_count, wav_filename);
563 #endif
564 
565     // stop audio playback
566     const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance();
567     if (audio){
568         printf("close stream\n");
569         audio->close();
570     }
571 }
572 
573 /* @section Handle Media Data Packet
574  *
575  * @text Here the audio data, are received through the handle_l2cap_media_data_packet callback.
576  * Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet.
577  * 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).
578  * If the audio stream wasn't started already and there are enough SBC frames in the ring buffer, start playback.
579  */
580 
581 static int read_media_data_header(uint8_t * packet, int size, int * offset, avdtp_media_packet_header_t * media_header);
582 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header);
583 
584 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size){
585     UNUSED(seid);
586     int pos = 0;
587 
588     avdtp_media_packet_header_t media_header;
589     if (!read_media_data_header(packet, size, &pos, &media_header)) return;
590 
591     avdtp_sbc_codec_header_t sbc_header;
592     if (!read_sbc_header(packet, size, &pos, &sbc_header)) return;
593 
594     // update sample rate compensation
595     ratio_measure_update( &sample_rate_adaption, sbc_header.num_frames*128 );
596 
597     const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance();
598     // process data right away if there's no audio implementation active, e.g. on posix systems to store as .wav
599     if (!audio){
600         btstack_sbc_decoder_process_data(&state, 0, packet+pos, size-pos);
601         return;
602     }
603 
604     // store sbc frame size for buffer management
605     sbc_frame_size = (size-pos)/ sbc_header.num_frames;
606 
607     int status = btstack_ring_buffer_write(&sbc_frame_ring_buffer, packet+pos, size-pos);
608     if (status != ERROR_CODE_SUCCESS){
609         printf("Error storing samples in SBC ring buffer!!!\n");
610     }
611 
612     // decide on audio sync drift based on number of sbc frames in queue
613     int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) / sbc_frame_size;
614 #if 0
615     uint32_t resampling_factor;
616 
617     // nominal factor (fixed-point 2^16) and compensation offset
618     uint32_t nominal_factor = 0x10000;
619     uint32_t compensation   = 0x00100;
620 
621     if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){
622     	resampling_factor = nominal_factor - compensation;    // stretch samples
623     } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){
624     	resampling_factor = nominal_factor;                   // nothing to do
625     } else {
626     	resampling_factor = nominal_factor + compensation;    // compress samples
627     }
628 
629     btstack_resample_set_factor(&resample_instance, resampling_factor);
630 #endif
631     // start stream if enough frames buffered
632     if (!audio_stream_started && sbc_frames_in_buffer >= OPTIMAL_FRAMES_MIN){
633         media_processing_start();
634     }
635 }
636 
637 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header){
638     int sbc_header_len = 12; // without crc
639     int pos = *offset;
640 
641     if (size - pos < sbc_header_len){
642         printf("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size-pos);
643         return 0;
644     }
645 
646     sbc_header->fragmentation = get_bit16(packet[pos], 7);
647     sbc_header->starting_packet = get_bit16(packet[pos], 6);
648     sbc_header->last_packet = get_bit16(packet[pos], 5);
649     sbc_header->num_frames = packet[pos] & 0x0f;
650     pos++;
651     *offset = pos;
652     return 1;
653 }
654 
655 static int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header){
656     int media_header_len = 12; // without crc
657     int pos = *offset;
658 
659     if (size - pos < media_header_len){
660         printf("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size-pos);
661         return 0;
662     }
663 
664     media_header->version = packet[pos] & 0x03;
665     media_header->padding = get_bit16(packet[pos],2);
666     media_header->extension = get_bit16(packet[pos],3);
667     media_header->csrc_count = (packet[pos] >> 4) & 0x0F;
668     pos++;
669 
670     media_header->marker = get_bit16(packet[pos],0);
671     media_header->payload_type  = (packet[pos] >> 1) & 0x7F;
672     pos++;
673 
674     media_header->sequence_number = big_endian_read_16(packet, pos);
675     pos+=2;
676 
677     media_header->timestamp = big_endian_read_32(packet, pos);
678     pos+=4;
679 
680     media_header->synchronization_source = big_endian_read_32(packet, pos);
681     pos+=4;
682     *offset = pos;
683     return 1;
684 }
685 
686 static void dump_sbc_configuration(media_codec_configuration_sbc_t * configuration){
687     printf("    - num_channels: %d\n", configuration->num_channels);
688     printf("    - sampling_frequency: %d\n", configuration->sampling_frequency);
689     printf("    - channel_mode: %d\n", configuration->channel_mode);
690     printf("    - block_length: %d\n", configuration->block_length);
691     printf("    - subbands: %d\n", configuration->subbands);
692     printf("    - allocation_method: %d\n", configuration->allocation_method);
693     printf("    - bitpool_value [%d, %d] \n", configuration->min_bitpool_value, configuration->max_bitpool_value);
694     printf("\n");
695 }
696 
697 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
698     UNUSED(channel);
699     UNUSED(size);
700     uint16_t local_cid;
701     uint8_t  status;
702     bd_addr_t address;
703 
704     a2dp_sink_demo_avrcp_connection_t * connection = &a2dp_sink_demo_avrcp_connection;
705 
706     if (packet_type != HCI_EVENT_PACKET) return;
707     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
708     switch (packet[2]){
709         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
710             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
711             status = avrcp_subevent_connection_established_get_status(packet);
712             if (status != ERROR_CODE_SUCCESS){
713                 printf("AVRCP: Connection failed, status 0x%02x\n", status);
714                 connection->avrcp_cid = 0;
715                 return;
716             }
717 
718             connection->avrcp_cid = local_cid;
719             avrcp_subevent_connection_established_get_bd_addr(packet, address);
720             printf("AVRCP: Connected to %s, cid 0x%02x\n", bd_addr_to_str(address), connection->avrcp_cid);
721 
722             avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
723             avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_BATT_STATUS_CHANGED);
724             avrcp_target_battery_status_changed(connection->avrcp_cid, battery_status);
725 
726             // automatically enable notifications
727             avrcp_controller_enable_notification(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
728             avrcp_controller_enable_notification(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
729             avrcp_controller_enable_notification(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
730             return;
731         }
732 
733         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
734             printf("AVRCP: Channel released: cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
735             connection->avrcp_cid = 0;
736             return;
737         default:
738             break;
739     }
740 }
741 
742 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
743     UNUSED(channel);
744     UNUSED(size);
745 
746     // helper to print c strings
747     uint8_t  avrcp_subevent_value[256];
748     uint8_t play_status;
749 
750     a2dp_sink_demo_avrcp_connection_t * avrcp_connection = &a2dp_sink_demo_avrcp_connection;
751 
752     if (packet_type != HCI_EVENT_PACKET) return;
753     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
754     if (avrcp_connection->avrcp_cid == 0) return;
755 
756     memset(avrcp_subevent_value, 0, sizeof(avrcp_subevent_value));
757     switch (packet[2]){
758         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:
759             printf("AVRCP Controller: Playback position changed, position %d ms\n", (unsigned int) avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet));
760             break;
761         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
762             printf("AVRCP Controller: Playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
763             play_status = avrcp_subevent_notification_playback_status_changed_get_play_status(packet);
764             switch (play_status){
765                 case AVRCP_PLAYBACK_STATUS_PLAYING:
766                     avrcp_connection->playing = true;
767                     break;
768                 default:
769                     avrcp_connection->playing = false;
770                     break;
771             }
772             printf("AVRCP Controller: Playback status changed %s\n", avrcp_play_status2str(play_status));            return;
773         case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
774             printf("AVRCP Controller: Playing content changed\n");
775             return;
776         case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
777             printf("AVRCP Controller: Track changed\n");
778             return;
779         case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
780             printf("AVRCP Controller: Changed\n");
781             return;
782         case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{
783             uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
784             uint8_t repeat_mode  = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
785             printf("AVRCP Controller: %s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
786             break;
787         }
788         case AVRCP_SUBEVENT_NOW_PLAYING_TRACK_INFO:
789             printf("AVRCP Controller:     Track: %d\n", avrcp_subevent_now_playing_track_info_get_track(packet));
790             break;
791 
792         case AVRCP_SUBEVENT_NOW_PLAYING_TOTAL_TRACKS_INFO:
793             printf("AVRCP Controller:     Total Tracks: %d\n", avrcp_subevent_now_playing_total_tracks_info_get_total_tracks(packet));
794             break;
795 
796         case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO:
797             if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0){
798                 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet));
799                 printf("AVRCP Controller:     Title: %s\n", avrcp_subevent_value);
800             }
801             break;
802 
803         case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO:
804             if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0){
805                 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet));
806                 printf("AVRCP Controller:     Artist: %s\n", avrcp_subevent_value);
807             }
808             break;
809 
810         case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO:
811             if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0){
812                 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet));
813                 printf("AVRCP Controller:     Album: %s\n", avrcp_subevent_value);
814             }
815             break;
816 
817         case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO:
818             if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0){
819                 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet));
820                 printf("AVRCP Controller:     Genre: %s\n", avrcp_subevent_value);
821             }
822             break;
823 
824         case AVRCP_SUBEVENT_PLAY_STATUS:
825             printf("AVRCP Controller: Song length %"PRIu32" ms, Song position %"PRIu32" ms, Play status %s\n",
826                 avrcp_subevent_play_status_get_song_length(packet),
827                 avrcp_subevent_play_status_get_song_position(packet),
828                 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
829             break;
830 
831         case AVRCP_SUBEVENT_OPERATION_COMPLETE:
832             printf("AVRCP Controller: %s complete\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
833             break;
834 
835         case AVRCP_SUBEVENT_OPERATION_START:
836             printf("AVRCP Controller: %s start\n", avrcp_operation2str(avrcp_subevent_operation_start_get_operation_id(packet)));
837             break;
838 
839         case AVRCP_SUBEVENT_NOTIFICATION_EVENT_TRACK_REACHED_END:
840             printf("AVRCP Controller: Track reached end\n");
841             break;
842 
843         case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
844             printf("AVRCP Controller: Set Player App Value %s\n", avrcp_ctype2str(avrcp_subevent_player_application_value_response_get_command_type(packet)));
845             break;
846 
847         default:
848             break;
849     }
850 }
851 
852 static void avrcp_volume_changed(uint8_t volume){
853     const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance();
854     if (audio){
855         audio->set_volume(volume);
856     }
857 }
858 
859 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
860     UNUSED(channel);
861     UNUSED(size);
862 
863     if (packet_type != HCI_EVENT_PACKET) return;
864     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
865 
866     uint8_t volume;
867     char const * button_state;
868     avrcp_operation_id_t operation_id;
869 
870     switch (packet[2]){
871         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
872             volume = avrcp_subevent_notification_volume_changed_get_absolute_volume(packet);
873             volume_percentage = volume * 100 / 127;
874             printf("AVRCP Target    : Volume set to %d%% (%d)\n", volume_percentage, volume);
875             avrcp_volume_changed(volume);
876             break;
877 
878         case AVRCP_SUBEVENT_OPERATION:
879             operation_id = avrcp_subevent_operation_get_operation_id(packet);
880             button_state = avrcp_subevent_operation_get_button_pressed(packet) > 0 ? "PRESS" : "RELEASE";
881             switch (operation_id){
882                 case AVRCP_OPERATION_ID_VOLUME_UP:
883                     printf("AVRCP Target    : VOLUME UP (%s)\n", button_state);
884                     break;
885                 case AVRCP_OPERATION_ID_VOLUME_DOWN:
886                     printf("AVRCP Target    : VOLUME DOWN (%s)\n", button_state);
887                     break;
888                 default:
889                     return;
890             }
891             break;
892         default:
893             printf("AVRCP Target    : Event 0x%02x is not parsed\n", packet[2]);
894             break;
895     }
896 }
897 
898 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
899     UNUSED(channel);
900     UNUSED(size);
901     if (packet_type != HCI_EVENT_PACKET) return;
902     if (hci_event_packet_get_type(packet) == HCI_EVENT_PIN_CODE_REQUEST) {
903         bd_addr_t address;
904         printf("Pin code request - using '0000'\n");
905         hci_event_pin_code_request_get_bd_addr(packet, address);
906         gap_pin_code_response(address, "0000");
907     }
908 }
909 
910 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
911     UNUSED(channel);
912     UNUSED(size);
913     bd_addr_t address;
914     uint8_t status;
915 
916     uint8_t allocation_method;
917 
918     if (packet_type != HCI_EVENT_PACKET) return;
919     if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return;
920 
921     a2dp_sink_demo_a2dp_connection_t * a2dp_conn = &a2dp_sink_demo_a2dp_connection;
922 
923     switch (packet[2]){
924         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
925             printf("A2DP  Sink      : Received non SBC codec - not implemented\n");
926             break;
927         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
928             printf("A2DP  Sink      : Received SBC codec configuration\n");
929             a2dp_conn->sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
930             a2dp_conn->sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
931             a2dp_conn->sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
932             a2dp_conn->sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
933             a2dp_conn->sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
934             a2dp_conn->sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
935             a2dp_conn->sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
936 
937             allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
938 
939             // Adapt Bluetooth spec definition to SBC Encoder expected input
940             a2dp_conn->sbc_configuration.allocation_method = (btstack_sbc_allocation_method_t)(allocation_method - 1);
941 
942             switch (a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet)){
943                 case AVDTP_CHANNEL_MODE_JOINT_STEREO:
944                     a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
945                     break;
946                 case AVDTP_CHANNEL_MODE_STEREO:
947                     a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_STEREO;
948                     break;
949                 case AVDTP_CHANNEL_MODE_DUAL_CHANNEL:
950                     a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
951                     break;
952                 case AVDTP_CHANNEL_MODE_MONO:
953                     a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_MONO;
954                     break;
955                 default:
956                     btstack_assert(false);
957                     break;
958             }
959             dump_sbc_configuration(&a2dp_conn->sbc_configuration);
960             break;
961         }
962 
963         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
964             a2dp_subevent_stream_established_get_bd_addr(packet, a2dp_conn->addr);
965 
966             status = a2dp_subevent_stream_established_get_status(packet);
967             if (status != ERROR_CODE_SUCCESS){
968                 printf("A2DP  Sink      : Streaming connection failed, status 0x%02x\n", status);
969                 break;
970             }
971 
972             a2dp_conn->a2dp_cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
973             a2dp_conn->stream_state = STREAM_STATE_OPEN;
974 
975             printf("A2DP  Sink      : Streaming connection is established, address %s, cid 0x%02x, local seid %d\n",
976                    bd_addr_to_str(address), a2dp_conn->a2dp_cid, a2dp_conn->a2dp_local_seid);
977 #ifdef HAVE_BTSTACK_STDIN
978             // use address for outgoing connections
979             memcpy(device_addr, address, 6);
980 #endif
981             break;
982 
983 #ifdef ENABLE_AVDTP_ACCEPTOR_EXPLICIT_START_STREAM_CONFIRMATION
984         case A2DP_SUBEVENT_START_STREAM_REQUESTED:
985             printf("A2DP  Sink      : Explicit Accept to start stream, local_seid %d\n", a2dp_subevent_start_stream_requested_get_local_seid(packet));
986             a2dp_sink_start_stream_accept(a2dp_cid, a2dp_local_seid);
987             break;
988 #endif
989         case A2DP_SUBEVENT_STREAM_STARTED:
990             printf("A2DP  Sink      : Stream started\n");
991             a2dp_conn->stream_state = STREAM_STATE_PLAYING;
992             if (a2dp_conn->sbc_configuration.reconfigure){
993                 media_processing_close();
994             }
995             // prepare media processing
996             media_processing_init(&a2dp_conn->sbc_configuration);
997             // audio stream is started when buffer reaches minimal level
998             break;
999 
1000         case A2DP_SUBEVENT_STREAM_SUSPENDED:
1001             printf("A2DP  Sink      : Stream paused\n");
1002             a2dp_conn->stream_state = STREAM_STATE_PAUSED;
1003             media_processing_pause();
1004             break;
1005 
1006         case A2DP_SUBEVENT_STREAM_RELEASED:
1007             printf("A2DP  Sink      : Stream released\n");
1008             a2dp_conn->stream_state = STREAM_STATE_CLOSED;
1009             media_processing_close();
1010             break;
1011 
1012         case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
1013             printf("A2DP  Sink      : Signaling connection released\n");
1014             a2dp_conn->a2dp_cid = 0;
1015             media_processing_close();
1016             break;
1017 
1018         default:
1019             break;
1020     }
1021 }
1022 
1023 #ifdef HAVE_BTSTACK_STDIN
1024 static void show_usage(void){
1025     bd_addr_t      iut_address;
1026     gap_local_bd_addr(iut_address);
1027     printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address));
1028     printf("b      - AVDTP Sink create  connection to addr %s\n", bd_addr_to_str(device_addr));
1029     printf("B      - AVDTP Sink disconnect\n");
1030     printf("c      - AVRCP create connection to addr %s\n", bd_addr_to_str(device_addr));
1031     printf("C      - AVRCP disconnect\n");
1032 
1033     printf("w - delay report\n");
1034 
1035     printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address));
1036     printf("O - get play status\n");
1037     printf("j - get now playing info\n");
1038     printf("k - play\n");
1039     printf("K - stop\n");
1040     printf("L - pause\n");
1041     printf("u - start fast forward\n");
1042     printf("U - stop  fast forward\n");
1043     printf("n - start rewind\n");
1044     printf("N - stop rewind\n");
1045     printf("i - forward\n");
1046     printf("I - backward\n");
1047     printf("M - mute\n");
1048     printf("r - skip\n");
1049     printf("q - query repeat and shuffle mode\n");
1050     printf("v - repeat single track\n");
1051     printf("x - repeat all tracks\n");
1052     printf("X - disable repeat mode\n");
1053     printf("z - shuffle all tracks\n");
1054     printf("Z - disable shuffle mode\n");
1055 
1056     printf("a/A - register/deregister TRACK_CHANGED\n");
1057     printf("R/P - register/deregister PLAYBACK_POS_CHANGED\n");
1058 
1059     printf("s/S - send/release long button press REWIND\n");
1060 
1061     printf("\n--- Volume and Battery Control ---\n");
1062     printf("t - volume up   for 10 percent\n");
1063     printf("T - volume down for 10 percent\n");
1064     printf("V - toggle Battery status from AVRCP_BATTERY_STATUS_NORMAL to AVRCP_BATTERY_STATUS_FULL_CHARGE\n");
1065     printf("---\n");
1066 }
1067 #endif
1068 
1069 #ifdef HAVE_BTSTACK_STDIN
1070 static void stdin_process(char cmd){
1071     uint8_t status = ERROR_CODE_SUCCESS;
1072     uint8_t volume;
1073     avrcp_battery_status_t old_battery_status;
1074 
1075     a2dp_sink_demo_stream_endpoint_t *  stream_endpoint  = &a2dp_sink_demo_stream_endpoint;
1076     a2dp_sink_demo_a2dp_connection_t *  a2dp_connection  = &a2dp_sink_demo_a2dp_connection;
1077     a2dp_sink_demo_avrcp_connection_t * avrcp_connection = &a2dp_sink_demo_avrcp_connection;
1078 
1079     switch (cmd){
1080         case 'b':
1081             status = a2dp_sink_establish_stream(device_addr, stream_endpoint->a2dp_local_seid, &a2dp_connection->a2dp_cid);
1082             printf(" - Create AVDTP connection to addr %s, and local seid %d, cid 0x%02x.\n",
1083                    bd_addr_to_str(device_addr), a2dp_connection->a2dp_local_seid, a2dp_connection->a2dp_cid);
1084             break;
1085         case 'B':
1086             printf(" - AVDTP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
1087             a2dp_sink_disconnect(a2dp_connection->a2dp_cid);
1088             break;
1089         case 'c':
1090             printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr));
1091             status = avrcp_connect(device_addr, &avrcp_connection->avrcp_cid);
1092             break;
1093         case 'C':
1094             printf(" - AVRCP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
1095             status = avrcp_disconnect(avrcp_connection->avrcp_cid);
1096             break;
1097 
1098         case '\n':
1099         case '\r':
1100             break;
1101         case 'w':
1102             printf("Send delay report\n");
1103             avdtp_sink_delay_report(a2dp_connection->a2dp_cid, a2dp_connection->a2dp_local_seid, 100);
1104             break;
1105         // Volume Control
1106         case 't':
1107             volume_percentage = volume_percentage <= 90 ? volume_percentage + 10 : 100;
1108             volume = volume_percentage * 127 / 100;
1109             printf(" - volume up   for 10 percent, %d%% (%d) \n", volume_percentage, volume);
1110             status = avrcp_target_volume_changed(avrcp_connection->avrcp_cid, volume);
1111             avrcp_volume_changed(volume);
1112             break;
1113         case 'T':
1114             volume_percentage = volume_percentage >= 10 ? volume_percentage - 10 : 0;
1115             volume = volume_percentage * 127 / 100;
1116             printf(" - volume down for 10 percent, %d%% (%d) \n", volume_percentage, volume);
1117             status = avrcp_target_volume_changed(avrcp_connection->avrcp_cid, volume);
1118             avrcp_volume_changed(volume);
1119             break;
1120         case 'V':
1121             old_battery_status = battery_status;
1122 
1123             if (battery_status < AVRCP_BATTERY_STATUS_FULL_CHARGE){
1124                 battery_status = (avrcp_battery_status_t)((uint8_t) battery_status + 1);
1125             } else {
1126                 battery_status = AVRCP_BATTERY_STATUS_NORMAL;
1127             }
1128             printf(" - toggle battery value, old %d, new %d\n", old_battery_status, battery_status);
1129             status = avrcp_target_battery_status_changed(avrcp_connection->avrcp_cid, battery_status);
1130             break;
1131         case 'O':
1132             printf(" - get play status\n");
1133             status = avrcp_controller_get_play_status(avrcp_connection->avrcp_cid);
1134             break;
1135         case 'j':
1136             printf(" - get now playing info\n");
1137             status = avrcp_controller_get_now_playing_info(avrcp_connection->avrcp_cid);
1138             break;
1139         case 'k':
1140             printf(" - play\n");
1141             status = avrcp_controller_play(avrcp_connection->avrcp_cid);
1142             break;
1143         case 'K':
1144             printf(" - stop\n");
1145             status = avrcp_controller_stop(avrcp_connection->avrcp_cid);
1146             break;
1147         case 'L':
1148             printf(" - pause\n");
1149             status = avrcp_controller_pause(avrcp_connection->avrcp_cid);
1150             break;
1151         case 'u':
1152             printf(" - start fast forward\n");
1153             status = avrcp_controller_press_and_hold_fast_forward(avrcp_connection->avrcp_cid);
1154             break;
1155         case 'U':
1156             printf(" - stop fast forward\n");
1157             status = avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid);
1158             break;
1159         case 'n':
1160             printf(" - start rewind\n");
1161             status = avrcp_controller_press_and_hold_rewind(avrcp_connection->avrcp_cid);
1162             break;
1163         case 'N':
1164             printf(" - stop rewind\n");
1165             status = avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid);
1166             break;
1167         case 'i':
1168             printf(" - forward\n");
1169             status = avrcp_controller_forward(avrcp_connection->avrcp_cid);
1170             break;
1171         case 'I':
1172             printf(" - backward\n");
1173             status = avrcp_controller_backward(avrcp_connection->avrcp_cid);
1174             break;
1175         case 'M':
1176             printf(" - mute\n");
1177             status = avrcp_controller_mute(avrcp_connection->avrcp_cid);
1178             break;
1179         case 'r':
1180             printf(" - skip\n");
1181             status = avrcp_controller_skip(avrcp_connection->avrcp_cid);
1182             break;
1183         case 'q':
1184             printf(" - query repeat and shuffle mode\n");
1185             status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_connection->avrcp_cid);
1186             break;
1187         case 'v':
1188             printf(" - repeat single track\n");
1189             status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK);
1190             break;
1191         case 'x':
1192             printf(" - repeat all tracks\n");
1193             status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS);
1194             break;
1195         case 'X':
1196             printf(" - disable repeat mode\n");
1197             status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_OFF);
1198             break;
1199         case 'z':
1200             printf(" - shuffle all tracks\n");
1201             status = avrcp_controller_set_shuffle_mode(avrcp_connection->avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS);
1202             break;
1203         case 'Z':
1204             printf(" - disable shuffle mode\n");
1205             status = avrcp_controller_set_shuffle_mode(avrcp_connection->avrcp_cid, AVRCP_SHUFFLE_MODE_OFF);
1206             break;
1207         case 'a':
1208             printf("AVRCP: enable notification TRACK_CHANGED\n");
1209             avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
1210             break;
1211         case 'A':
1212             printf("AVRCP: disable notification TRACK_CHANGED\n");
1213             avrcp_controller_disable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
1214             break;
1215         case 'R':
1216             printf("AVRCP: enable notification PLAYBACK_POS_CHANGED\n");
1217             avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
1218             break;
1219         case 'P':
1220             printf("AVRCP: disable notification PLAYBACK_POS_CHANGED\n");
1221             avrcp_controller_disable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
1222             break;
1223          case 's':
1224             printf("AVRCP: send long button press REWIND\n");
1225             avrcp_controller_start_press_and_hold_cmd(avrcp_connection->avrcp_cid, AVRCP_OPERATION_ID_REWIND);
1226             break;
1227         case 'S':
1228             printf("AVRCP: release long button press REWIND\n");
1229             avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid);
1230             break;
1231         default:
1232             show_usage();
1233             return;
1234     }
1235     if (status != ERROR_CODE_SUCCESS){
1236         printf("Could not perform command, status 0x%02x\n", status);
1237     }
1238 }
1239 #endif
1240 
1241 int btstack_main(int argc, const char * argv[]);
1242 int btstack_main(int argc, const char * argv[]){
1243     UNUSED(argc);
1244     (void)argv;
1245 
1246     a2dp_and_avrcp_setup();
1247 
1248 #ifdef HAVE_BTSTACK_STDIN
1249     // parse human-readable Bluetooth address
1250     sscanf_bd_addr(device_addr_string, device_addr);
1251     btstack_stdin_setup(stdin_process);
1252 #endif
1253 
1254     // turn on!
1255     printf("Starting BTstack ...\n");
1256     hci_power_control(HCI_POWER_ON);
1257     return 0;
1258 }
1259 /* EXAMPLE_END */
1260