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