xref: /btstack/example/a2dp_sink_demo.c (revision ce00c6755aa0c7568bf39210f83eaf2f9fd1b438)
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 MATTHIAS
24  * RINGWALD 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): Receive audio stream and control its 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.
52  *
53  * @test To test with a remote device, e.g. a mobile phone,
54  * pair from the remote device with the demo, then start playing music on the remote device.
55  * Alternatively, set the device_addr_string to the Bluetooth address of your
56  * remote device in the code, and call connect from the UI.
57  *
58  * @test To controll the playback, tap SPACE on the console to show the available
59  * AVRCP commands.
60  */
61 // *****************************************************************************
62 
63 #include <inttypes.h>
64 #include <stdint.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 
69 #include "btstack.h"
70 
71 //#define AVRCP_BROWSING_ENABLED
72 
73 #ifdef HAVE_BTSTACK_STDIN
74 #include "btstack_stdin.h"
75 #endif
76 
77 #include "btstack_ring_buffer.h"
78 
79 #ifdef HAVE_POSIX_FILE_IO
80 #include "wav_util.h"
81 #define STORE_SBC_TO_SBC_FILE
82 #define STORE_SBC_TO_WAV_FILE
83 #endif
84 
85 #define NUM_CHANNELS 2
86 #define BYTES_PER_FRAME     (2*NUM_CHANNELS)
87 #define MAX_SBC_FRAME_SIZE 120
88 
89 // SBC Decoder for WAV file or live playback
90 static btstack_sbc_decoder_state_t state;
91 static btstack_sbc_mode_t mode = SBC_MODE_STANDARD;
92 
93 // ring buffer for SBC Frames
94 // below 30: add samples, 30-40: fine, above 40: drop samples
95 #define OPTIMAL_FRAMES_MIN 30
96 #define OPTIMAL_FRAMES_MAX 40
97 #define ADDITIONAL_FRAMES  10
98 static uint8_t sbc_frame_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE];
99 static btstack_ring_buffer_t sbc_frame_ring_buffer;
100 static unsigned int sbc_frame_size;
101 static int sbc_samples_fix;
102 
103 // ring buffer for not fully used sbc frames
104 #define MAX_NUM_SBC_SAMPLES 128
105 static uint8_t decoded_audio_storage[(MAX_NUM_SBC_SAMPLES+4) * BYTES_PER_FRAME];
106 static btstack_ring_buffer_t decoded_audio_ring_buffer;
107 
108 //
109 static int audio_stream_started;
110 
111 // temp storage of lower-layer request
112 static int16_t * request_buffer;
113 static int       request_samples;
114 
115 // WAV File
116 #ifdef STORE_SBC_TO_WAV_FILE
117 static int frame_count = 0;
118 static char * wav_filename = "avdtp_sink.wav";
119 #endif
120 
121 #ifdef STORE_SBC_TO_SBC_FILE
122 static FILE * sbc_file;
123 static char * sbc_filename = "avdtp_sink.sbc";
124 #endif
125 
126 typedef struct {
127     // bitmaps
128     uint8_t sampling_frequency_bitmap;
129     uint8_t channel_mode_bitmap;
130     uint8_t block_length_bitmap;
131     uint8_t subbands_bitmap;
132     uint8_t allocation_method_bitmap;
133     uint8_t min_bitpool_value;
134     uint8_t max_bitpool_value;
135 } adtvp_media_codec_information_sbc_t;
136 
137 typedef struct {
138     int reconfigure;
139     int num_channels;
140     int sampling_frequency;
141     int channel_mode;
142     int block_length;
143     int subbands;
144     int allocation_method;
145     int min_bitpool_value;
146     int max_bitpool_value;
147     int frames_per_buffer;
148 } avdtp_media_codec_configuration_sbc_t;
149 
150 #ifdef HAVE_BTSTACK_STDIN
151 // pts: static bd_addr_t remote = {0x00, 0x1B, 0xDC, 0x08, 0x0A, 0xA5};
152 // mac 2013: static const char * device_addr_string = "84:38:35:65:d1:15";
153 // iPhone 5S:
154 static const char * device_addr_string = "54:E4:3A:26:A2:39";
155 #endif
156 
157 static uint8_t  sdp_avdtp_sink_service_buffer[150];
158 static avdtp_media_codec_configuration_sbc_t sbc_configuration;
159 static uint16_t a2dp_cid = 0;
160 static uint8_t  local_seid = 0;
161 static uint8_t  value[100];
162 
163 static btstack_packet_callback_registration_t hci_event_callback_registration;
164 
165 static int media_initialized = 0;
166 
167 #ifdef HAVE_BTSTACK_STDIN
168 static bd_addr_t device_addr;
169 #endif
170 
171 static uint16_t a2dp_sink_connected = 0;
172 static uint16_t avrcp_cid = 0;
173 static uint8_t  avrcp_connected = 0;
174 static uint8_t  sdp_avrcp_controller_service_buffer[200];
175 
176 static uint8_t media_sbc_codec_capabilities[] = {
177     0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
178     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
179     2, 53
180 };
181 
182 static uint8_t media_sbc_codec_configuration[] = {
183     (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
184     (AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
185     2, 53
186 };
187 
188 
189 /* @section Main Application Setup
190  *
191  * @text The Listing MainConfiguration shows how to setup AD2P Sink and AVRCP controller services.
192  * To announce A2DP Sink and AVRCP Controller services, you need to create corresponding
193  * SDP records and register them with the SDP service.
194  * You'll also need to register several packet handlers:
195  * - 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).
196  * - handle_l2cap_media_data_packet - used to receive streaming data. If HAVE_PORTAUDIO or STORE_SBC_TO_WAV_FILE directives (check btstack_config.h) are 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.
197  * - stdin_process callback - used to trigger AVRCP commands to the A2DP Source device, such are get now playing info, start, stop, volume control. Requires HAVE_BTSTACK_STDIN.
198  * - avrcp_controller_packet_handler - used to receive answers for AVRCP commands,
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_SBC_TO_WAV_FILE. The HAVE_PORTAUDIO directive indicates if the audio is played back via PortAudio.
202  * If HAVE_PORTAUDIO or STORE_SBC_TO_WAV_FILE directives 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 a in wav file if STORE_SBC_TO_WAV_FILE is defined, and/or played using the PortAudio library if HAVE_PORTAUDIO is defined.
205  */
206 
207 /* LISTING_START(MainConfiguration): Setup Audio Sink and AVRCP Controller services */
208 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * event, uint16_t event_size);
209 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
210 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
211 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size);
212 
213 static int a2dp_and_avrcp_setup(void){
214 
215     l2cap_init();
216     // Initialize AVDTP Sink
217     a2dp_sink_init();
218     a2dp_sink_register_packet_handler(&a2dp_sink_packet_handler);
219     a2dp_sink_register_media_handler(&handle_l2cap_media_data_packet);
220 
221     uint8_t status = a2dp_sink_create_stream_endpoint(AVDTP_AUDIO, AVDTP_CODEC_SBC, media_sbc_codec_capabilities, sizeof(media_sbc_codec_capabilities), media_sbc_codec_configuration, sizeof(media_sbc_codec_configuration), &local_seid);
222     if (status != ERROR_CODE_SUCCESS){
223         printf("A2DP Sink: not enough memory to create local stream endpoint\n");
224         return 1;
225     }
226     // Initialize AVRCP COntroller
227     avrcp_controller_init();
228     avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler);
229 
230     // Initialize SDP
231     sdp_init();
232     // setup AVDTP sink
233     memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer));
234     a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, 0x10001, 1, NULL, NULL);
235     sdp_register_service(sdp_avdtp_sink_service_buffer);
236 
237     // setup AVRCP
238     memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
239 
240     uint16_t supported_features = (1 << AVRCP_CONTROLLER_SUPPORTED_FEATURE_CATEGORY_PLAYER_OR_RECORDER);
241 #ifdef AVRCP_BROWSING_ENABLED
242     supported_features |= (1 << AVRCP_CONTROLLER_SUPPORTED_FEATURE_BROWSING);
243 #endif
244     avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10001, supported_features, NULL, NULL);
245     sdp_register_service(sdp_avrcp_controller_service_buffer);
246 
247     gap_set_local_name("A2DP Sink Demo 00:00:00:00:00:00");
248     gap_discoverable_control(1);
249     gap_set_class_of_device(0x200408);
250 
251     /* Register for HCI events */
252     hci_event_callback_registration.callback = &hci_packet_handler;
253     hci_add_event_handler(&hci_event_callback_registration);
254 
255     return 0;
256 }
257 
258 static void playback_handler(int16_t * buffer, uint16_t num_samples){
259 
260     // called from lower-layer but guaranteed to be on main thread
261 
262     // first fill from decoded_audio
263     uint32_t bytes_read;
264     btstack_ring_buffer_read(&decoded_audio_ring_buffer, (uint8_t *) buffer, num_samples * BYTES_PER_FRAME, &bytes_read);
265     buffer          += bytes_read / NUM_CHANNELS;
266     num_samples     -= bytes_read / BYTES_PER_FRAME;
267 
268     // then start decoding sbc frames using request_* globals
269     request_buffer = buffer;
270     request_samples = num_samples;
271     while (request_samples && btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) >= sbc_frame_size){
272         // log_info("buffer %06u bytes -- need %d", btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer), request_samples);
273         // decode frame
274         uint8_t frame[MAX_SBC_FRAME_SIZE];
275         btstack_ring_buffer_read(&sbc_frame_ring_buffer, frame, sbc_frame_size, &bytes_read);
276         btstack_sbc_decoder_process_data(&state, 0, frame, sbc_frame_size);
277     }
278 }
279 
280 static void handle_pcm_data(int16_t * data, int num_samples, int num_channels, int sample_rate, void * context){
281     UNUSED(sample_rate);
282     UNUSED(context);
283     UNUSED(num_channels);   // must be stereo == 2
284 
285 #ifdef STORE_SBC_TO_WAV_FILE
286     wav_writer_write_int16(num_samples * NUM_CHANNELS, data);
287     frame_count++;
288 #endif
289 
290     int sbc_samples_fix_applied = 0;
291 
292     // drop audio frame to fix drift
293     if (sbc_samples_fix < 0){
294         num_samples--;
295         data += NUM_CHANNELS;
296         sbc_samples_fix_applied = 1;
297     }
298 
299     // store data in btstack_audio buffer first
300     if (request_samples){
301 
302         // add audio frame to fix drift
303         if (!sbc_samples_fix_applied && sbc_samples_fix > 0){
304             memcpy(request_buffer, data, BYTES_PER_FRAME);
305             request_samples--;
306             request_buffer += NUM_CHANNELS;
307             sbc_samples_fix_applied = 1;
308         }
309 
310         int samples_to_copy = btstack_min(num_samples, request_samples);
311         memcpy(request_buffer, data, samples_to_copy * BYTES_PER_FRAME);
312         num_samples     -= samples_to_copy;
313         request_samples -= samples_to_copy;
314         data            += samples_to_copy * NUM_CHANNELS;
315         request_buffer  += samples_to_copy * NUM_CHANNELS;
316     }
317 
318     // and rest in ring buffer
319     if (num_samples){
320 
321         // add audio frame to fix drift
322         if (!sbc_samples_fix_applied && sbc_samples_fix > 0){
323             btstack_ring_buffer_write(&decoded_audio_ring_buffer, (uint8_t *) data, BYTES_PER_FRAME);
324             sbc_samples_fix_applied = 1;
325         }
326 
327         btstack_ring_buffer_write(&decoded_audio_ring_buffer, (uint8_t *) data, num_samples * BYTES_PER_FRAME);
328     }
329 }
330 
331 static int media_processing_init(avdtp_media_codec_configuration_sbc_t configuration){
332     if (media_initialized) return 0;
333 
334     btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL);
335 
336 #ifdef STORE_SBC_TO_WAV_FILE
337     wav_writer_open(wav_filename, configuration.num_channels, configuration.sampling_frequency);
338 #endif
339 
340 #ifdef STORE_SBC_TO_SBC_FILE
341    sbc_file = fopen(sbc_filename, "wb");
342 #endif
343 
344     btstack_ring_buffer_init(&sbc_frame_ring_buffer, sbc_frame_storage, sizeof(sbc_frame_storage));
345     btstack_ring_buffer_init(&decoded_audio_ring_buffer, decoded_audio_storage, sizeof(decoded_audio_storage));
346 
347     // setup audio playback
348     const btstack_audio_t * audio = btstack_audio_get_instance();
349     if (audio){
350         audio->init(NUM_CHANNELS, configuration.sampling_frequency, &playback_handler, NULL);
351     }
352 
353     audio_stream_started = 0;
354     media_initialized = 1;
355     return 0;
356 }
357 
358 static void media_processing_close(void){
359 
360     if (!media_initialized) return;
361     media_initialized = 0;
362     audio_stream_started = 0;
363 
364 #ifdef STORE_SBC_TO_WAV_FILE
365     wav_writer_close();
366     int total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr;
367 
368     printf("WAV Writer: Decoding done. Processed totaly %d frames:\n - %d good\n - %d bad\n", total_frames_nr, state.good_frames_nr, total_frames_nr - state.good_frames_nr);
369     printf("WAV Writer: Written %d frames to wav file: %s\n", frame_count, wav_filename);
370 #endif
371 
372 #ifdef STORE_SBC_TO_SBC_FILE
373     fclose(sbc_file);
374 #endif
375 
376     // stop audio playback
377     const btstack_audio_t * audio = btstack_audio_get_instance();
378     if (audio){
379         audio->close();
380     }
381 }
382 
383 /* @section Handle Media Data Packet
384  *
385  * @text Media data packets, in this case the audio data, are received through the handle_l2cap_media_data_packet callback.
386  * Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet.
387  * 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)
388  * If the audio stream wasn't started already and there are enough SBC frames in the ring buffer, start playback.
389  */
390 
391 static int read_media_data_header(uint8_t * packet, int size, int * offset, avdtp_media_packet_header_t * media_header);
392 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header);
393 
394 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size){
395     UNUSED(seid);
396     int pos = 0;
397 
398     avdtp_media_packet_header_t media_header;
399     if (!read_media_data_header(packet, size, &pos, &media_header)) return;
400 
401     avdtp_sbc_codec_header_t sbc_header;
402     if (!read_sbc_header(packet, size, &pos, &sbc_header)) return;
403 
404     const btstack_audio_t * audio = btstack_audio_get_instance();
405 
406     // process data right away if there's no audio implementation active, e.g. on posix systems to store as .wav
407     if (!audio){
408         btstack_sbc_decoder_process_data(&state, 0, packet+pos, size-pos);
409         return;
410     }
411 
412     // store sbc frame size for buffer management
413     sbc_frame_size = (size-pos)/ sbc_header.num_frames;
414 
415     btstack_ring_buffer_write(&sbc_frame_ring_buffer, packet+pos, size-pos);
416 
417     // decide on audio sync drift based on number of sbc frames in queue
418     int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) / sbc_frame_size;
419     if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){
420     	sbc_samples_fix = 1;	// duplicate last sample
421     } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){
422     	sbc_samples_fix = 0;	// nothing to do
423     } else {
424     	sbc_samples_fix = -1;	// drop last sample
425     }
426 
427     // dump
428     // printf("%6u %03u %d\n",  (int) btstack_run_loop_get_time_ms(), sbc_frames_in_buffer, sbc_samples_fix);
429     // log_info("%03u %d", sbc_frames_in_buffer, sbc_samples_fix);
430 
431 #ifdef STORE_SBC_TO_SBC_FILE
432     fwrite(packet+pos, size-pos, 1, sbc_file);
433 #endif
434 
435     // start stream if enough frames buffered
436     if (!audio_stream_started && sbc_frames_in_buffer >= (OPTIMAL_FRAMES_MAX+OPTIMAL_FRAMES_MIN)/2){
437         audio_stream_started = 1;
438         // setup audio playback
439         if (audio){
440             audio->start_stream();
441         }
442     }
443 }
444 
445 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header){
446     int sbc_header_len = 12; // without crc
447     int pos = *offset;
448 
449     if (size - pos < sbc_header_len){
450         printf("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size-pos);
451         return 0;
452     }
453 
454     sbc_header->fragmentation = get_bit16(packet[pos], 7);
455     sbc_header->starting_packet = get_bit16(packet[pos], 6);
456     sbc_header->last_packet = get_bit16(packet[pos], 5);
457     sbc_header->num_frames = packet[pos] & 0x0f;
458     pos++;
459     // printf("SBC HEADER: num_frames %u, fragmented %u, start %u, stop %u\n", sbc_header.num_frames, sbc_header.fragmentation, sbc_header.starting_packet, sbc_header.last_packet);
460     *offset = pos;
461     return 1;
462 }
463 
464 static int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header){
465     int media_header_len = 12; // without crc
466     int pos = *offset;
467 
468     if (size - pos < media_header_len){
469         printf("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size-pos);
470         return 0;
471     }
472 
473     media_header->version = packet[pos] & 0x03;
474     media_header->padding = get_bit16(packet[pos],2);
475     media_header->extension = get_bit16(packet[pos],3);
476     media_header->csrc_count = (packet[pos] >> 4) & 0x0F;
477     pos++;
478 
479     media_header->marker = get_bit16(packet[pos],0);
480     media_header->payload_type  = (packet[pos] >> 1) & 0x7F;
481     pos++;
482 
483     media_header->sequence_number = big_endian_read_16(packet, pos);
484     pos+=2;
485 
486     media_header->timestamp = big_endian_read_32(packet, pos);
487     pos+=4;
488 
489     media_header->synchronization_source = big_endian_read_32(packet, pos);
490     pos+=4;
491     *offset = pos;
492     // TODO: read csrc list
493 
494     // printf_hexdump( packet, pos );
495     // printf("MEDIA HEADER: %u timestamp, version %u, padding %u, extension %u, csrc_count %u\n",
496     //     media_header->timestamp, media_header->version, media_header->padding, media_header->extension, media_header->csrc_count);
497     // printf("MEDIA HEADER: marker %02x, payload_type %02x, sequence_number %u, synchronization_source %u\n",
498     //     media_header->marker, media_header->payload_type, media_header->sequence_number, media_header->synchronization_source);
499     return 1;
500 }
501 
502 static void dump_sbc_configuration(avdtp_media_codec_configuration_sbc_t configuration){
503     printf("Received SBC configuration:\n");
504     printf("    - num_channels: %d\n", configuration.num_channels);
505     printf("    - sampling_frequency: %d\n", configuration.sampling_frequency);
506     printf("    - channel_mode: %d\n", configuration.channel_mode);
507     printf("    - block_length: %d\n", configuration.block_length);
508     printf("    - subbands: %d\n", configuration.subbands);
509     printf("    - allocation_method: %d\n", configuration.allocation_method);
510     printf("    - bitpool_value [%d, %d] \n", configuration.min_bitpool_value, configuration.max_bitpool_value);
511     printf("\n");
512 }
513 
514 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
515     UNUSED(channel);
516     UNUSED(size);
517     uint16_t local_cid;
518     uint8_t  status = 0xFF;
519     bd_addr_t adress;
520 
521     if (packet_type != HCI_EVENT_PACKET) return;
522     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
523     switch (packet[2]){
524         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
525             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
526             if (avrcp_cid != 0 && avrcp_cid != local_cid) {
527                 printf("AVRCP demo: Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_cid, local_cid);
528                 return;
529             }
530 
531             status = avrcp_subevent_connection_established_get_status(packet);
532             if (status != ERROR_CODE_SUCCESS){
533                 printf("AVRCP demo: Connection failed: status 0x%02x\n", status);
534                 avrcp_cid = 0;
535                 return;
536             }
537 
538             avrcp_cid = local_cid;
539             avrcp_connected = 1;
540             avrcp_subevent_connection_established_get_bd_addr(packet, adress);
541             printf("AVRCP demo: Channel successfully opened: %s, avrcp_cid 0x%02x\n", bd_addr_to_str(adress), avrcp_cid);
542 
543             // automatically enable notifications
544             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
545             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
546             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
547             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
548             return;
549         }
550         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
551             printf("AVRCP demo: Channel released: avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
552             avrcp_cid = 0;
553             avrcp_connected = 0;
554             return;
555         default:
556             break;
557     }
558 
559     status = packet[5];
560     if (!avrcp_cid) return;
561 
562     // ignore INTERIM status
563     if (status == AVRCP_CTYPE_RESPONSE_INTERIM){
564         switch (packet[2]){
565             case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:{
566                 uint32_t playback_position_ms = avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet);
567                 if (playback_position_ms == AVRCP_NO_TRACK_SELECTED_PLAYBACK_POSITION_CHANGED){
568                     printf("notification, playback position changed, no track is selected\n");
569                 }
570                 break;
571             }
572             default:
573                 printf(" INTERIM response \n");
574                 break;
575         }
576         return;
577     }
578 
579     printf("AVRCP demo: command status: %s, ", avrcp_ctype2str(status));
580     switch (packet[2]){
581         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:
582             printf("notification, playback position changed, position %d ms\n", (unsigned int) avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet));
583             break;
584         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
585             printf("notification, playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
586             return;
587         case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
588             printf("notification, playing content changed\n");
589             return;
590         case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
591             printf("notification track changed\n");
592             return;
593         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
594             printf("notification absolute volume changed %d\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet));
595             return;
596         case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
597             printf("notification changed\n");
598             return;
599         case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{
600             uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
601             uint8_t repeat_mode  = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
602             printf("%s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
603             break;
604         }
605         case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO:
606             if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0){
607                 memcpy(value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet));
608                 printf("    Title: %s\n", value);
609             }
610             break;
611 
612         case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO:
613             if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0){
614                 memcpy(value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet));
615                 printf("    Artist: %s\n", value);
616             }
617             break;
618 
619         case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO:
620             if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0){
621                 memcpy(value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet));
622                 printf("    Album: %s\n", value);
623             }
624             break;
625 
626         case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO:
627             if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0){
628                 memcpy(value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet));
629                 printf("    Genre: %s\n", value);
630             }
631             break;
632 
633         case AVRCP_SUBEVENT_PLAY_STATUS:
634             printf("song length: %"PRIu32" ms, song position: %"PRIu32" ms, play status: %s\n",
635                 avrcp_subevent_play_status_get_song_length(packet),
636                 avrcp_subevent_play_status_get_song_position(packet),
637                 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
638             break;
639         case AVRCP_SUBEVENT_OPERATION_COMPLETE:
640             printf("operation done %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
641             break;
642         case AVRCP_SUBEVENT_OPERATION_START:
643             printf("operation start %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
644             break;
645         case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
646             // response to set shuffle and repeat mode
647             printf("\n");
648             break;
649         default:
650             printf("AVRCP demo: event is not parsed\n");
651             break;
652     }
653 }
654 
655 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
656     UNUSED(channel);
657     UNUSED(size);
658     if (packet_type != HCI_EVENT_PACKET) return;
659     if (hci_event_packet_get_type(packet) == HCI_EVENT_PIN_CODE_REQUEST) {
660         bd_addr_t address;
661         printf("Pin code request - using '0000'\n");
662         hci_event_pin_code_request_get_bd_addr(packet, address);
663         gap_pin_code_response(address, "0000");
664     }
665 }
666 
667 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
668     UNUSED(channel);
669     UNUSED(size);
670     uint16_t cid;
671     bd_addr_t address;
672     uint8_t status;
673 
674     if (packet_type != HCI_EVENT_PACKET) return;
675     if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return;
676 
677     switch (packet[2]){
678         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
679             printf("A2DP Sink demo: received non SBC codec. not implemented.\n");
680             break;
681         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
682             printf("A2DP Sink demo: received SBC codec configuration.\n");
683             sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
684             sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
685             sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
686             sbc_configuration.channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
687             sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
688             sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
689             sbc_configuration.allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
690             sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
691             sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
692             sbc_configuration.frames_per_buffer = sbc_configuration.subbands * sbc_configuration.block_length;
693             dump_sbc_configuration(sbc_configuration);
694 
695             if (sbc_configuration.reconfigure){
696                 media_processing_close();
697             }
698             // prepare media processing
699             media_processing_init(sbc_configuration);
700             break;
701         }
702         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
703             a2dp_subevent_stream_established_get_bd_addr(packet, address);
704             status = a2dp_subevent_stream_established_get_status(packet);
705             cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
706             printf("A2DP_SUBEVENT_STREAM_ESTABLISHED %d, %d \n", cid, a2dp_cid);
707             if (!a2dp_cid){
708                 // incoming connection
709                 a2dp_cid = cid;
710             } else if (cid != a2dp_cid) {
711                 break;
712             }
713             if (status){
714                 a2dp_sink_connected = 0;
715                 printf("A2DP Sink demo: streaming connection failed, status 0x%02x\n", status);
716                 break;
717             }
718             printf("A2DP Sink demo: streaming connection is established, address %s, a2dp cid 0x%02X, local_seid %d\n", bd_addr_to_str(address), a2dp_cid, local_seid);
719 
720             memcpy(device_addr, address, 6);
721 
722             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
723             a2dp_sink_connected = 1;
724             break;
725 
726         case A2DP_SUBEVENT_STREAM_STARTED:
727             cid = a2dp_subevent_stream_started_get_a2dp_cid(packet);
728             if (cid != a2dp_cid) break;
729             local_seid = a2dp_subevent_stream_started_get_local_seid(packet);
730             printf("A2DP Sink demo: stream started, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
731             // started
732             media_processing_init(sbc_configuration);
733             break;
734 
735         case A2DP_SUBEVENT_STREAM_SUSPENDED:
736             cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet);
737             if (cid != a2dp_cid) break;
738             local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet);
739             printf("A2DP Sink demo: stream paused, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
740             media_processing_close();
741             break;
742 
743         case A2DP_SUBEVENT_STREAM_RELEASED:
744             local_seid = a2dp_subevent_stream_released_get_local_seid(packet);
745             printf("A2DP Sink demo: stream released, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
746             media_processing_close();
747             break;
748         case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
749             cid = a2dp_subevent_signaling_connection_released_get_a2dp_cid(packet);
750             a2dp_sink_connected = 0;
751             printf("A2DP Sink demo: signaling connection released\n");
752             media_processing_close();
753             break;
754         default:
755             printf("A2DP Sink demo: not parsed 0x%02x\n", packet[2]);
756             break;
757     }
758 }
759 
760 #ifdef HAVE_BTSTACK_STDIN
761 static void show_usage(void){
762     bd_addr_t      iut_address;
763     gap_local_bd_addr(iut_address);
764     printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address));
765     printf("b      - AVDTP Sink create  connection to addr %s\n", bd_addr_to_str(device_addr));
766     printf("B      - AVDTP Sink disconnect\n");
767     printf("c      - AVRCP create connection to addr %s\n", bd_addr_to_str(device_addr));
768     printf("C      - AVRCP disconnect\n");
769 
770     printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address));
771     printf("O - get play status\n");
772     printf("j - get now playing info\n");
773     printf("k - play\n");
774     printf("K - stop\n");
775     printf("L - pause\n");
776     printf("u - start fast forward\n");
777     printf("U - stop  fast forward\n");
778     printf("n - start rewind\n");
779     printf("N - stop rewind\n");
780     printf("i - forward\n");
781     printf("I - backward\n");
782     printf("t - volume up\n");
783     printf("T - volume down\n");
784     printf("p - absolute volume of 50 percent\n");
785     printf("M - mute\n");
786     printf("r - skip\n");
787     printf("q - query repeat and shuffle mode\n");
788     printf("v - repeat single track\n");
789     printf("x - repeat all tracks\n");
790     printf("X - disable repeat mode\n");
791     printf("z - shuffle all tracks\n");
792     printf("Z - disable shuffle mode\n");
793 
794     printf("a/A - register/deregister TRACK_CHANGED\n");
795     printf("d/D - register/deregister PLAYBACK_POS_CHANGED\n");
796 
797     printf("---\n");
798 }
799 #endif
800 
801 #ifdef HAVE_BTSTACK_STDIN
802 static void stdin_process(char cmd){
803     uint8_t status = ERROR_CODE_SUCCESS;
804     if (!avrcp_connected){
805         switch (cmd){
806             case 'b':
807             case 'c':
808                 break;
809             case '\n':
810             case '\r':
811             case ' ':
812                 show_usage();
813                 return;
814             default:
815                 printf("Not connected. Please use 'c' to establish an AVRCP connection with device (addr %s).\n", bd_addr_to_str(device_addr));
816                 return;
817         }
818     }
819 
820     switch (cmd){
821         case 'b':
822             status = a2dp_sink_establish_stream(device_addr, local_seid, &a2dp_cid);
823             printf(" - Create AVDTP connection to addr %s, and local seid %d, expected cid 0x%02x.\n", bd_addr_to_str(device_addr), local_seid, a2dp_cid);
824             break;
825         case 'B':
826             printf(" - AVDTP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
827             status = avdtp_sink_disconnect(a2dp_cid);
828             break;
829         case 'c':
830             printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr));
831             status = avrcp_controller_connect(device_addr, &avrcp_cid);
832             break;
833         case 'C':
834             printf(" - AVRCP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
835             status = avrcp_controller_disconnect(avrcp_cid);
836             break;
837 
838         case '\n':
839         case '\r':
840             break;
841         case 'O':
842             printf(" - get play status\n");
843             status = avrcp_controller_get_play_status(avrcp_cid);
844             break;
845         case 'j':
846             printf(" - get now playing info\n");
847             status = avrcp_controller_get_now_playing_info(avrcp_cid);
848             break;
849         case 'k':
850             printf(" - play\n");
851             status = avrcp_controller_play(avrcp_cid);
852             break;
853         case 'K':
854             printf(" - stop\n");
855             status = avrcp_controller_stop(avrcp_cid);
856             break;
857         case 'L':
858             printf(" - pause\n");
859             status = avrcp_controller_pause(avrcp_cid);
860             break;
861         case 'u':
862             printf(" - start fast forward\n");
863             status = avrcp_controller_press_and_hold_fast_forward(avrcp_cid);
864             break;
865         case 'U':
866             printf(" - stop fast forward\n");
867             status = avrcp_controller_release_press_and_hold_cmd(avrcp_cid);
868             break;
869         case 'n':
870             printf(" - start rewind\n");
871             status = avrcp_controller_press_and_hold_rewind(avrcp_cid);
872             break;
873         case 'N':
874             printf(" - stop rewind\n");
875             status = avrcp_controller_release_press_and_hold_cmd(avrcp_cid);
876             break;
877         case 'i':
878             printf(" - forward\n");
879             status = avrcp_controller_forward(avrcp_cid);
880             break;
881         case 'I':
882             printf(" - backward\n");
883             status = avrcp_controller_backward(avrcp_cid);
884             break;
885         case 't':
886             printf(" - volume up\n");
887             status = avrcp_controller_volume_up(avrcp_cid);
888             break;
889         case 'T':
890             printf(" - volume down\n");
891             status = avrcp_controller_volume_down(avrcp_cid);
892             break;
893         case 'p':
894             printf(" - absolute volume of 50 percent\n");
895             status = avrcp_controller_set_absolute_volume(avrcp_cid, 50);
896             break;
897         case 'M':
898             printf(" - mute\n");
899             status = avrcp_controller_mute(avrcp_cid);
900             break;
901         case 'r':
902             printf(" - skip\n");
903             status = avrcp_controller_skip(avrcp_cid);
904             break;
905         case 'q':
906             printf(" - query repeat and shuffle mode\n");
907             status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_cid);
908             break;
909         case 'v':
910             printf(" - repeat single track\n");
911             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK);
912             break;
913         case 'x':
914             printf(" - repeat all tracks\n");
915             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS);
916             break;
917         case 'X':
918             printf(" - disable repeat mode\n");
919             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_OFF);
920             break;
921         case 'z':
922             printf(" - shuffle all tracks\n");
923             status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS);
924             break;
925         case 'Z':
926             printf(" - disable shuffle mode\n");
927             status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_OFF);
928             break;
929         case 'a':
930             printf("AVRCP: enable notification TRACK_CHANGED\n");
931             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
932             break;
933         case 'A':
934             printf("AVRCP: disable notification TRACK_CHANGED\n");
935             avrcp_controller_disable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
936             break;
937         case 'd':
938             printf("AVRCP: enable notification PLAYBACK_POS_CHANGED\n");
939             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
940             break;
941         case 'D':
942             printf("AVRCP: disable notification PLAYBACK_POS_CHANGED\n");
943             avrcp_controller_disable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
944             break;
945 
946         default:
947             show_usage();
948             return;
949     }
950     if (status != ERROR_CODE_SUCCESS){
951         printf("Could not perform command, status 0x%2x\n", status);
952     }
953 }
954 #endif
955 
956 int btstack_main(int argc, const char * argv[]);
957 int btstack_main(int argc, const char * argv[]){
958     UNUSED(argc);
959     (void)argv;
960 
961     a2dp_and_avrcp_setup();
962 
963 #ifdef HAVE_BTSTACK_STDIN
964     // parse human readable Bluetooth address
965     sscanf_bd_addr(device_addr_string, device_addr);
966     btstack_stdin_setup(stdin_process);
967 #endif
968 
969     // turn on!
970     printf("Starting BTstack ...\n");
971     hci_power_control(HCI_POWER_ON);
972     return 0;
973 }
974