xref: /btstack/example/a2dp_sink_demo.c (revision 630ffdd469bbec3276322f46b93e6cfdfcb21c27)
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     if (media_initialized) return 0;
327 
328     btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL);
329 
330 #ifdef STORE_SBC_TO_WAV_FILE
331     wav_writer_open(wav_filename, configuration.num_channels, configuration.sampling_frequency);
332 #endif
333 
334 #ifdef STORE_SBC_TO_SBC_FILE
335    sbc_file = fopen(sbc_filename, "wb");
336 #endif
337 
338     btstack_ring_buffer_init(&sbc_frame_ring_buffer, sbc_frame_storage, sizeof(sbc_frame_storage));
339     btstack_ring_buffer_init(&decoded_audio_ring_buffer, decoded_audio_storage, sizeof(decoded_audio_storage));
340 
341     // setup audio playback
342     const btstack_audio_t * audio = btstack_audio_get_instance();
343     if (audio){
344         audio->init(NUM_CHANNELS, configuration.sampling_frequency, &playback_handler, NULL);
345     }
346 
347     audio_stream_started = 0;
348     media_initialized = 1;
349     return 0;
350 }
351 
352 static void media_processing_close(void){
353 
354     if (!media_initialized) return;
355     media_initialized = 0;
356     audio_stream_started = 0;
357 
358 #ifdef STORE_SBC_TO_WAV_FILE
359     wav_writer_close();
360     int total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr;
361 
362     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);
363     printf("WAV Writer: Written %d frames to wav file: %s\n", frame_count, wav_filename);
364 #endif
365 
366 #ifdef STORE_SBC_TO_SBC_FILE
367     fclose(sbc_file);
368 #endif
369 
370     // stop audio playback
371     const btstack_audio_t * audio = btstack_audio_get_instance();
372     if (audio){
373         audio->close();
374     }
375 }
376 
377 /* @section Handle Media Data Packet
378  *
379  * @text Media data packets, in this case the audio data, are received through the handle_l2cap_media_data_packet callback.
380  * Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet.
381  * 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)
382  * If the audio stream wasn't started already and there are enough SBC frames in the ring buffer, start playback.
383  */
384 
385 static int read_media_data_header(uint8_t * packet, int size, int * offset, avdtp_media_packet_header_t * media_header);
386 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header);
387 
388 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size){
389     UNUSED(seid);
390     int pos = 0;
391 
392     avdtp_media_packet_header_t media_header;
393     if (!read_media_data_header(packet, size, &pos, &media_header)) return;
394 
395     avdtp_sbc_codec_header_t sbc_header;
396     if (!read_sbc_header(packet, size, &pos, &sbc_header)) return;
397 
398     const btstack_audio_t * audio = btstack_audio_get_instance();
399 
400     // process data right away if there's no audio implementation active, e.g. on posix systems to store as .wav
401     if (!audio){
402         btstack_sbc_decoder_process_data(&state, 0, packet+pos, size-pos);
403         return;
404     }
405 
406     // store sbc frame size for buffer management
407     sbc_frame_size = (size-pos)/ sbc_header.num_frames;
408 
409     btstack_ring_buffer_write(&sbc_frame_ring_buffer, packet+pos, size-pos);
410 
411     // decide on audio sync drift based on number of sbc frames in queue
412     int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) / sbc_frame_size;
413     if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){
414     	sbc_samples_fix = 1;	// duplicate last sample
415     } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){
416     	sbc_samples_fix = 0;	// nothing to do
417     } else {
418     	sbc_samples_fix = -1;	// drop last sample
419     }
420 
421     // dump
422     // printf("%6u %03u %d\n",  (int) btstack_run_loop_get_time_ms(), sbc_frames_in_buffer, sbc_samples_fix);
423     // log_info("%03u %d", sbc_frames_in_buffer, sbc_samples_fix);
424 
425 #ifdef STORE_SBC_TO_SBC_FILE
426     fwrite(packet+pos, size-pos, 1, sbc_file);
427 #endif
428 
429     // start stream if enough frames buffered
430     if (!audio_stream_started && sbc_frames_in_buffer >= (OPTIMAL_FRAMES_MAX+OPTIMAL_FRAMES_MIN)/2){
431         audio_stream_started = 1;
432         // setup audio playback
433         if (audio){
434             audio->start_stream();
435         }
436     }
437 }
438 
439 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header){
440     int sbc_header_len = 12; // without crc
441     int pos = *offset;
442 
443     if (size - pos < sbc_header_len){
444         printf("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size-pos);
445         return 0;
446     }
447 
448     sbc_header->fragmentation = get_bit16(packet[pos], 7);
449     sbc_header->starting_packet = get_bit16(packet[pos], 6);
450     sbc_header->last_packet = get_bit16(packet[pos], 5);
451     sbc_header->num_frames = packet[pos] & 0x0f;
452     pos++;
453     // 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);
454     *offset = pos;
455     return 1;
456 }
457 
458 static int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header){
459     int media_header_len = 12; // without crc
460     int pos = *offset;
461 
462     if (size - pos < media_header_len){
463         printf("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size-pos);
464         return 0;
465     }
466 
467     media_header->version = packet[pos] & 0x03;
468     media_header->padding = get_bit16(packet[pos],2);
469     media_header->extension = get_bit16(packet[pos],3);
470     media_header->csrc_count = (packet[pos] >> 4) & 0x0F;
471     pos++;
472 
473     media_header->marker = get_bit16(packet[pos],0);
474     media_header->payload_type  = (packet[pos] >> 1) & 0x7F;
475     pos++;
476 
477     media_header->sequence_number = big_endian_read_16(packet, pos);
478     pos+=2;
479 
480     media_header->timestamp = big_endian_read_32(packet, pos);
481     pos+=4;
482 
483     media_header->synchronization_source = big_endian_read_32(packet, pos);
484     pos+=4;
485     *offset = pos;
486     // TODO: read csrc list
487 
488     // printf_hexdump( packet, pos );
489     // printf("MEDIA HEADER: %u timestamp, version %u, padding %u, extension %u, csrc_count %u\n",
490     //     media_header->timestamp, media_header->version, media_header->padding, media_header->extension, media_header->csrc_count);
491     // printf("MEDIA HEADER: marker %02x, payload_type %02x, sequence_number %u, synchronization_source %u\n",
492     //     media_header->marker, media_header->payload_type, media_header->sequence_number, media_header->synchronization_source);
493     return 1;
494 }
495 
496 static void dump_sbc_configuration(avdtp_media_codec_configuration_sbc_t configuration){
497     printf("Received SBC configuration:\n");
498     printf("    - num_channels: %d\n", configuration.num_channels);
499     printf("    - sampling_frequency: %d\n", configuration.sampling_frequency);
500     printf("    - channel_mode: %d\n", configuration.channel_mode);
501     printf("    - block_length: %d\n", configuration.block_length);
502     printf("    - subbands: %d\n", configuration.subbands);
503     printf("    - allocation_method: %d\n", configuration.allocation_method);
504     printf("    - bitpool_value [%d, %d] \n", configuration.min_bitpool_value, configuration.max_bitpool_value);
505     printf("\n");
506 }
507 
508 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
509     UNUSED(channel);
510     UNUSED(size);
511     uint16_t local_cid;
512     uint8_t  status = 0xFF;
513     bd_addr_t adress;
514 
515     if (packet_type != HCI_EVENT_PACKET) return;
516     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
517     switch (packet[2]){
518         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
519             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
520             if (avrcp_cid != 0 && avrcp_cid != local_cid) {
521                 printf("AVRCP demo: Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_cid, local_cid);
522                 return;
523             }
524 
525             status = avrcp_subevent_connection_established_get_status(packet);
526             if (status != ERROR_CODE_SUCCESS){
527                 printf("AVRCP demo: Connection failed: status 0x%02x\n", status);
528                 avrcp_cid = 0;
529                 return;
530             }
531 
532             avrcp_cid = local_cid;
533             avrcp_connected = 1;
534             avrcp_subevent_connection_established_get_bd_addr(packet, adress);
535             printf("AVRCP demo: Channel successfully opened: %s, avrcp_cid 0x%02x\n", bd_addr_to_str(adress), avrcp_cid);
536 
537             // automatically enable notifications
538             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
539             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
540             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
541             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
542             return;
543         }
544         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
545             printf("AVRCP demo: Channel released: avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
546             avrcp_cid = 0;
547             avrcp_connected = 0;
548             return;
549         default:
550             break;
551     }
552 
553     status = packet[5];
554     if (!avrcp_cid) return;
555 
556     // ignore INTERIM status
557     if (status == AVRCP_CTYPE_RESPONSE_INTERIM){
558         switch (packet[2]){
559             case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:{
560                 uint32_t playback_position_ms = avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet);
561                 if (playback_position_ms == AVRCP_NO_TRACK_SELECTED_PLAYBACK_POSITION_CHANGED){
562                     printf("notification, playback position changed, no track is selected\n");
563                 }
564                 break;
565             }
566             default:
567                 printf(" INTERIM response \n");
568                 break;
569         }
570         return;
571     }
572 
573     printf("AVRCP demo: command status: %s, ", avrcp_ctype2str(status));
574     switch (packet[2]){
575         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:
576             printf("notification, playback position changed, position %d ms\n", (unsigned int) avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet));
577             break;
578         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
579             printf("notification, playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
580             return;
581         case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
582             printf("notification, playing content changed\n");
583             return;
584         case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
585             printf("notification track changed\n");
586             return;
587         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
588             printf("notification absolute volume changed %d\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet));
589             return;
590         case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
591             printf("notification changed\n");
592             return;
593         case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{
594             uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
595             uint8_t repeat_mode  = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
596             printf("%s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
597             break;
598         }
599         case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO:
600             if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0){
601                 memcpy(value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet));
602                 printf("    Title: %s\n", value);
603             }
604             break;
605 
606         case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO:
607             if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0){
608                 memcpy(value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet));
609                 printf("    Artist: %s\n", value);
610             }
611             break;
612 
613         case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO:
614             if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0){
615                 memcpy(value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet));
616                 printf("    Album: %s\n", value);
617             }
618             break;
619 
620         case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO:
621             if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0){
622                 memcpy(value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet));
623                 printf("    Genre: %s\n", value);
624             }
625             break;
626 
627         case AVRCP_SUBEVENT_PLAY_STATUS:
628             printf("song length: %"PRIu32" ms, song position: %"PRIu32" ms, play status: %s\n",
629                 avrcp_subevent_play_status_get_song_length(packet),
630                 avrcp_subevent_play_status_get_song_position(packet),
631                 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
632             break;
633         case AVRCP_SUBEVENT_OPERATION_COMPLETE:
634             printf("operation done %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
635             break;
636         case AVRCP_SUBEVENT_OPERATION_START:
637             printf("operation start %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
638             break;
639         case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
640             // response to set shuffle and repeat mode
641             printf("\n");
642             break;
643         default:
644             printf("AVRCP demo: event is not parsed\n");
645             break;
646     }
647 }
648 
649 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
650     UNUSED(channel);
651     UNUSED(size);
652     if (packet_type != HCI_EVENT_PACKET) return;
653     if (hci_event_packet_get_type(packet) == HCI_EVENT_PIN_CODE_REQUEST) {
654         bd_addr_t address;
655         printf("Pin code request - using '0000'\n");
656         hci_event_pin_code_request_get_bd_addr(packet, address);
657         gap_pin_code_response(address, "0000");
658     }
659 }
660 
661 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
662     UNUSED(channel);
663     UNUSED(size);
664     uint16_t cid;
665     bd_addr_t address;
666     uint8_t status;
667 
668     if (packet_type != HCI_EVENT_PACKET) return;
669     if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return;
670 
671     switch (packet[2]){
672         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
673             printf("A2DP Sink demo: received non SBC codec. not implemented.\n");
674             break;
675         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
676             printf("A2DP Sink demo: received SBC codec configuration.\n");
677             sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
678             sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
679             sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
680             sbc_configuration.channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
681             sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
682             sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
683             sbc_configuration.allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
684             sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
685             sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
686             sbc_configuration.frames_per_buffer = sbc_configuration.subbands * sbc_configuration.block_length;
687             dump_sbc_configuration(sbc_configuration);
688 
689             if (sbc_configuration.reconfigure){
690                 media_processing_close();
691             }
692             // prepare media processing
693             media_processing_init(sbc_configuration);
694             break;
695         }
696         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
697             a2dp_subevent_stream_established_get_bd_addr(packet, address);
698             status = a2dp_subevent_stream_established_get_status(packet);
699             cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
700             printf("A2DP_SUBEVENT_STREAM_ESTABLISHED %d, %d \n", cid, a2dp_cid);
701             if (!a2dp_cid){
702                 // incoming connection
703                 a2dp_cid = cid;
704             } else if (cid != a2dp_cid) {
705                 break;
706             }
707             if (status){
708                 a2dp_sink_connected = 0;
709                 printf("A2DP Sink demo: streaming connection failed, status 0x%02x\n", status);
710                 break;
711             }
712             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);
713 
714             memcpy(device_addr, address, 6);
715 
716             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
717             a2dp_sink_connected = 1;
718             break;
719 
720         case A2DP_SUBEVENT_STREAM_STARTED:
721             cid = a2dp_subevent_stream_started_get_a2dp_cid(packet);
722             if (cid != a2dp_cid) break;
723             local_seid = a2dp_subevent_stream_started_get_local_seid(packet);
724             printf("A2DP Sink demo: stream started, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
725             // started
726             media_processing_init(sbc_configuration);
727             break;
728 
729         case A2DP_SUBEVENT_STREAM_SUSPENDED:
730             cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet);
731             if (cid != a2dp_cid) break;
732             local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet);
733             printf("A2DP Sink demo: stream paused, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
734             media_processing_close();
735             break;
736 
737         case A2DP_SUBEVENT_STREAM_RELEASED:
738             local_seid = a2dp_subevent_stream_released_get_local_seid(packet);
739             printf("A2DP Sink demo: stream released, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
740             media_processing_close();
741             break;
742         case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
743             cid = a2dp_subevent_signaling_connection_released_get_a2dp_cid(packet);
744             a2dp_sink_connected = 0;
745             printf("A2DP Sink demo: signaling connection released\n");
746             media_processing_close();
747             break;
748         default:
749             printf("A2DP Sink demo: not parsed 0x%02x\n", packet[2]);
750             break;
751     }
752 }
753 
754 #ifdef HAVE_BTSTACK_STDIN
755 static void show_usage(void){
756     bd_addr_t      iut_address;
757     gap_local_bd_addr(iut_address);
758     printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address));
759     printf("b      - AVDTP Sink create  connection to addr %s\n", bd_addr_to_str(device_addr));
760     printf("B      - AVDTP Sink disconnect\n");
761     printf("c      - AVRCP create connection to addr %s\n", bd_addr_to_str(device_addr));
762     printf("C      - AVRCP disconnect\n");
763 
764     printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address));
765     printf("O - get play status\n");
766     printf("j - get now playing info\n");
767     printf("k - play\n");
768     printf("K - stop\n");
769     printf("L - pause\n");
770     printf("u - start fast forward\n");
771     printf("U - stop  fast forward\n");
772     printf("n - start rewind\n");
773     printf("N - stop rewind\n");
774     printf("i - forward\n");
775     printf("I - backward\n");
776     printf("t - volume up\n");
777     printf("T - volume down\n");
778     printf("p - absolute volume of 50 percent\n");
779     printf("M - mute\n");
780     printf("r - skip\n");
781     printf("q - query repeat and shuffle mode\n");
782     printf("v - repeat single track\n");
783     printf("x - repeat all tracks\n");
784     printf("X - disable repeat mode\n");
785     printf("z - shuffle all tracks\n");
786     printf("Z - disable shuffle mode\n");
787 
788     printf("a/A - register/deregister TRACK_CHANGED\n");
789     printf("d/D - register/deregister PLAYBACK_POS_CHANGED\n");
790 
791     printf("---\n");
792 }
793 #endif
794 
795 #ifdef HAVE_BTSTACK_STDIN
796 static void stdin_process(char cmd){
797     uint8_t status = ERROR_CODE_SUCCESS;
798     if (!avrcp_connected){
799         switch (cmd){
800             case 'b':
801             case 'c':
802                 break;
803             default:
804                 printf("Not connected. Please use 'c' to establish an AVRCP connection with device (addr %s).\n", bd_addr_to_str(device_addr));
805                 return;
806         }
807     }
808 
809     switch (cmd){
810         case 'b':
811             status = a2dp_sink_establish_stream(device_addr, local_seid, &a2dp_cid);
812             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);
813             break;
814         case 'B':
815             printf(" - AVDTP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
816             status = avdtp_sink_disconnect(a2dp_cid);
817             break;
818         case 'c':
819             printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr));
820             status = avrcp_controller_connect(device_addr, &avrcp_cid);
821             break;
822         case 'C':
823             printf(" - AVRCP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
824             status = avrcp_controller_disconnect(avrcp_cid);
825             break;
826 
827         case '\n':
828         case '\r':
829             break;
830         case 'O':
831             printf(" - get play status\n");
832             status = avrcp_controller_get_play_status(avrcp_cid);
833             break;
834         case 'j':
835             printf(" - get now playing info\n");
836             status = avrcp_controller_get_now_playing_info(avrcp_cid);
837             break;
838         case 'k':
839             printf(" - play\n");
840             status = avrcp_controller_play(avrcp_cid);
841             break;
842         case 'K':
843             printf(" - stop\n");
844             status = avrcp_controller_stop(avrcp_cid);
845             break;
846         case 'L':
847             printf(" - pause\n");
848             status = avrcp_controller_pause(avrcp_cid);
849             break;
850         case 'u':
851             printf(" - start fast forward\n");
852             status = avrcp_controller_press_and_hold_fast_forward(avrcp_cid);
853             break;
854         case 'U':
855             printf(" - stop fast forward\n");
856             status = avrcp_controller_release_press_and_hold_cmd(avrcp_cid);
857             break;
858         case 'n':
859             printf(" - start rewind\n");
860             status = avrcp_controller_press_and_hold_rewind(avrcp_cid);
861             break;
862         case 'N':
863             printf(" - stop rewind\n");
864             status = avrcp_controller_release_press_and_hold_cmd(avrcp_cid);
865             break;
866         case 'i':
867             printf(" - forward\n");
868             status = avrcp_controller_forward(avrcp_cid);
869             break;
870         case 'I':
871             printf(" - backward\n");
872             status = avrcp_controller_backward(avrcp_cid);
873             break;
874         case 't':
875             printf(" - volume up\n");
876             status = avrcp_controller_volume_up(avrcp_cid);
877             break;
878         case 'T':
879             printf(" - volume down\n");
880             status = avrcp_controller_volume_down(avrcp_cid);
881             break;
882         case 'p':
883             printf(" - absolute volume of 50 percent\n");
884             status = avrcp_controller_set_absolute_volume(avrcp_cid, 50);
885             break;
886         case 'M':
887             printf(" - mute\n");
888             status = avrcp_controller_mute(avrcp_cid);
889             break;
890         case 'r':
891             printf(" - skip\n");
892             status = avrcp_controller_skip(avrcp_cid);
893             break;
894         case 'q':
895             printf(" - query repeat and shuffle mode\n");
896             status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_cid);
897             break;
898         case 'v':
899             printf(" - repeat single track\n");
900             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK);
901             break;
902         case 'x':
903             printf(" - repeat all tracks\n");
904             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS);
905             break;
906         case 'X':
907             printf(" - disable repeat mode\n");
908             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_OFF);
909             break;
910         case 'z':
911             printf(" - shuffle all tracks\n");
912             status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS);
913             break;
914         case 'Z':
915             printf(" - disable shuffle mode\n");
916             status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_OFF);
917             break;
918         case 'a':
919             printf("AVRCP: enable notification TRACK_CHANGED\n");
920             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
921             break;
922         case 'A':
923             printf("AVRCP: disable notification TRACK_CHANGED\n");
924             avrcp_controller_disable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
925             break;
926         case 'd':
927             printf("AVRCP: enable notification PLAYBACK_POS_CHANGED\n");
928             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
929             break;
930         case 'D':
931             printf("AVRCP: disable notification PLAYBACK_POS_CHANGED\n");
932             avrcp_controller_disable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
933             break;
934 
935         default:
936             show_usage();
937             return;
938     }
939     if (status != ERROR_CODE_SUCCESS){
940         printf("Could not perform command, status 0x%2x\n", status);
941     }
942 }
943 #endif
944 
945 int btstack_main(int argc, const char * argv[]);
946 int btstack_main(int argc, const char * argv[]){
947     UNUSED(argc);
948     (void)argv;
949 
950     a2dp_and_avrcp_setup();
951 
952 #ifdef HAVE_BTSTACK_STDIN
953     // parse human readable Bluetooth address
954     sscanf_bd_addr(device_addr_string, device_addr);
955     btstack_stdin_setup(stdin_process);
956 #endif
957 
958     // turn on!
959     printf("Starting BTstack ...\n");
960     hci_power_control(HCI_POWER_ON);
961     return 0;
962 }
963