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