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 if (!media_initialized) return; 354 media_initialized = 0; 355 audio_stream_started = 0; 356 357 #ifdef STORE_SBC_TO_WAV_FILE 358 wav_writer_close(); 359 int total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr; 360 361 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); 362 printf("WAV Writer: Written %d frames to wav file: %s\n", frame_count, wav_filename); 363 #endif 364 365 #ifdef STORE_SBC_TO_SBC_FILE 366 fclose(sbc_file); 367 #endif 368 369 // stop audio playback 370 const btstack_audio_t * audio = btstack_audio_get_instance(); 371 if (audio){ 372 audio->close(); 373 } 374 } 375 376 /* @section Handle Media Data Packet 377 * 378 * @text Media data packets, in this case the audio data, are received through the handle_l2cap_media_data_packet callback. 379 * Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet. 380 * 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) 381 * If the audio stream wasn't started already and there are enough SBC frames in the ring buffer, start playback. 382 */ 383 384 static int read_media_data_header(uint8_t * packet, int size, int * offset, avdtp_media_packet_header_t * media_header); 385 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header); 386 387 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size){ 388 UNUSED(seid); 389 int pos = 0; 390 391 avdtp_media_packet_header_t media_header; 392 if (!read_media_data_header(packet, size, &pos, &media_header)) return; 393 394 avdtp_sbc_codec_header_t sbc_header; 395 if (!read_sbc_header(packet, size, &pos, &sbc_header)) return; 396 397 // store sbc frame size for buffer management 398 sbc_frame_size = (size-pos)/ sbc_header.num_frames; 399 400 btstack_ring_buffer_write(&sbc_frame_ring_buffer, packet+pos, size-pos); 401 402 // decide on audio sync drift based on number of sbc frames in queue 403 int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) / sbc_frame_size; 404 if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){ 405 sbc_samples_fix = 1; // duplicate last sample 406 } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){ 407 sbc_samples_fix = 0; // nothing to do 408 } else { 409 sbc_samples_fix = -1; // drop last sample 410 } 411 412 // dump 413 // printf("%6u %03u %d\n", (int) btstack_run_loop_get_time_ms(), sbc_frames_in_buffer, sbc_samples_fix); 414 // log_info("%03u %d", sbc_frames_in_buffer, sbc_samples_fix); 415 416 #ifdef STORE_SBC_TO_SBC_FILE 417 fwrite(packet+pos, size-pos, 1, sbc_file); 418 #endif 419 420 // start stream if enough frames buffered 421 if (!audio_stream_started && sbc_frames_in_buffer >= (OPTIMAL_FRAMES_MAX+OPTIMAL_FRAMES_MIN)/2){ 422 audio_stream_started = 1; 423 // setup audio playback 424 const btstack_audio_t * audio = btstack_audio_get_instance(); 425 if (audio){ 426 audio->start_stream(); 427 } 428 } 429 } 430 431 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header){ 432 int sbc_header_len = 12; // without crc 433 int pos = *offset; 434 435 if (size - pos < sbc_header_len){ 436 printf("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size-pos); 437 return 0; 438 } 439 440 sbc_header->fragmentation = get_bit16(packet[pos], 7); 441 sbc_header->starting_packet = get_bit16(packet[pos], 6); 442 sbc_header->last_packet = get_bit16(packet[pos], 5); 443 sbc_header->num_frames = packet[pos] & 0x0f; 444 pos++; 445 // 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); 446 *offset = pos; 447 return 1; 448 } 449 450 static int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header){ 451 int media_header_len = 12; // without crc 452 int pos = *offset; 453 454 if (size - pos < media_header_len){ 455 printf("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size-pos); 456 return 0; 457 } 458 459 media_header->version = packet[pos] & 0x03; 460 media_header->padding = get_bit16(packet[pos],2); 461 media_header->extension = get_bit16(packet[pos],3); 462 media_header->csrc_count = (packet[pos] >> 4) & 0x0F; 463 pos++; 464 465 media_header->marker = get_bit16(packet[pos],0); 466 media_header->payload_type = (packet[pos] >> 1) & 0x7F; 467 pos++; 468 469 media_header->sequence_number = big_endian_read_16(packet, pos); 470 pos+=2; 471 472 media_header->timestamp = big_endian_read_32(packet, pos); 473 pos+=4; 474 475 media_header->synchronization_source = big_endian_read_32(packet, pos); 476 pos+=4; 477 *offset = pos; 478 // TODO: read csrc list 479 480 // printf_hexdump( packet, pos ); 481 // printf("MEDIA HEADER: %u timestamp, version %u, padding %u, extension %u, csrc_count %u\n", 482 // media_header->timestamp, media_header->version, media_header->padding, media_header->extension, media_header->csrc_count); 483 // printf("MEDIA HEADER: marker %02x, payload_type %02x, sequence_number %u, synchronization_source %u\n", 484 // media_header->marker, media_header->payload_type, media_header->sequence_number, media_header->synchronization_source); 485 return 1; 486 } 487 488 static void dump_sbc_configuration(avdtp_media_codec_configuration_sbc_t configuration){ 489 printf("Received SBC configuration:\n"); 490 printf(" - num_channels: %d\n", configuration.num_channels); 491 printf(" - sampling_frequency: %d\n", configuration.sampling_frequency); 492 printf(" - channel_mode: %d\n", configuration.channel_mode); 493 printf(" - block_length: %d\n", configuration.block_length); 494 printf(" - subbands: %d\n", configuration.subbands); 495 printf(" - allocation_method: %d\n", configuration.allocation_method); 496 printf(" - bitpool_value [%d, %d] \n", configuration.min_bitpool_value, configuration.max_bitpool_value); 497 printf("\n"); 498 } 499 500 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 501 UNUSED(channel); 502 UNUSED(size); 503 uint16_t local_cid; 504 uint8_t status = 0xFF; 505 bd_addr_t adress; 506 507 if (packet_type != HCI_EVENT_PACKET) return; 508 if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return; 509 switch (packet[2]){ 510 case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: { 511 local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet); 512 if (avrcp_cid != 0 && avrcp_cid != local_cid) { 513 printf("AVRCP demo: Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_cid, local_cid); 514 return; 515 } 516 517 status = avrcp_subevent_connection_established_get_status(packet); 518 if (status != ERROR_CODE_SUCCESS){ 519 printf("AVRCP demo: Connection failed: status 0x%02x\n", status); 520 avrcp_cid = 0; 521 return; 522 } 523 524 avrcp_cid = local_cid; 525 avrcp_connected = 1; 526 avrcp_subevent_connection_established_get_bd_addr(packet, adress); 527 printf("AVRCP demo: Channel successfully opened: %s, avrcp_cid 0x%02x\n", bd_addr_to_str(adress), avrcp_cid); 528 529 // automatically enable notifications 530 avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED); 531 avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED); 532 avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED); 533 avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED); 534 return; 535 } 536 case AVRCP_SUBEVENT_CONNECTION_RELEASED: 537 printf("AVRCP demo: Channel released: avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet)); 538 avrcp_cid = 0; 539 avrcp_connected = 0; 540 return; 541 default: 542 break; 543 } 544 545 status = packet[5]; 546 if (!avrcp_cid) return; 547 548 // ignore INTERIM status 549 if (status == AVRCP_CTYPE_RESPONSE_INTERIM){ 550 switch (packet[2]){ 551 case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:{ 552 uint32_t playback_position_ms = avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet); 553 if (playback_position_ms == AVRCP_NO_TRACK_SELECTED_PLAYBACK_POSITION_CHANGED){ 554 printf("notification, playback position changed, no track is selected\n"); 555 } 556 break; 557 } 558 default: 559 printf(" INTERIM response \n"); 560 break; 561 } 562 return; 563 } 564 565 printf("AVRCP demo: command status: %s, ", avrcp_ctype2str(status)); 566 switch (packet[2]){ 567 case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED: 568 printf("notification, playback position changed, position %d ms\n", (unsigned int) avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet)); 569 break; 570 case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED: 571 printf("notification, playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet))); 572 return; 573 case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED: 574 printf("notification, playing content changed\n"); 575 return; 576 case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED: 577 printf("notification track changed\n"); 578 return; 579 case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED: 580 printf("notification absolute volume changed %d\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet)); 581 return; 582 case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED: 583 printf("notification changed\n"); 584 return; 585 case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{ 586 uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet); 587 uint8_t repeat_mode = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet); 588 printf("%s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode)); 589 break; 590 } 591 case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO: 592 if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0){ 593 memcpy(value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet)); 594 printf(" Title: %s\n", value); 595 } 596 break; 597 598 case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO: 599 if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0){ 600 memcpy(value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet)); 601 printf(" Artist: %s\n", value); 602 } 603 break; 604 605 case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO: 606 if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0){ 607 memcpy(value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet)); 608 printf(" Album: %s\n", value); 609 } 610 break; 611 612 case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO: 613 if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0){ 614 memcpy(value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet)); 615 printf(" Genre: %s\n", value); 616 } 617 break; 618 619 case AVRCP_SUBEVENT_PLAY_STATUS: 620 printf("song length: %"PRIu32" ms, song position: %"PRIu32" ms, play status: %s\n", 621 avrcp_subevent_play_status_get_song_length(packet), 622 avrcp_subevent_play_status_get_song_position(packet), 623 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet))); 624 break; 625 case AVRCP_SUBEVENT_OPERATION_COMPLETE: 626 printf("operation done %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet))); 627 break; 628 case AVRCP_SUBEVENT_OPERATION_START: 629 printf("operation start %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet))); 630 break; 631 case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE: 632 // response to set shuffle and repeat mode 633 printf("\n"); 634 break; 635 default: 636 printf("AVRCP demo: event is not parsed\n"); 637 break; 638 } 639 } 640 641 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 642 UNUSED(channel); 643 UNUSED(size); 644 if (packet_type != HCI_EVENT_PACKET) return; 645 if (hci_event_packet_get_type(packet) == HCI_EVENT_PIN_CODE_REQUEST) { 646 bd_addr_t address; 647 printf("Pin code request - using '0000'\n"); 648 hci_event_pin_code_request_get_bd_addr(packet, address); 649 gap_pin_code_response(address, "0000"); 650 } 651 } 652 653 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 654 UNUSED(channel); 655 UNUSED(size); 656 uint16_t cid; 657 bd_addr_t address; 658 uint8_t status; 659 660 if (packet_type != HCI_EVENT_PACKET) return; 661 if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return; 662 663 switch (packet[2]){ 664 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION: 665 printf("A2DP Sink demo: received non SBC codec. not implemented.\n"); 666 break; 667 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{ 668 printf("A2DP Sink demo: received SBC codec configuration.\n"); 669 sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet); 670 sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet); 671 sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet); 672 sbc_configuration.channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet); 673 sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet); 674 sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet); 675 sbc_configuration.allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet); 676 sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet); 677 sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet); 678 sbc_configuration.frames_per_buffer = sbc_configuration.subbands * sbc_configuration.block_length; 679 dump_sbc_configuration(sbc_configuration); 680 681 if (sbc_configuration.reconfigure){ 682 media_processing_close(); 683 } 684 // prepare media processing 685 media_processing_init(sbc_configuration); 686 break; 687 } 688 case A2DP_SUBEVENT_STREAM_ESTABLISHED: 689 a2dp_subevent_stream_established_get_bd_addr(packet, address); 690 status = a2dp_subevent_stream_established_get_status(packet); 691 cid = a2dp_subevent_stream_established_get_a2dp_cid(packet); 692 printf("A2DP_SUBEVENT_STREAM_ESTABLISHED %d, %d \n", cid, a2dp_cid); 693 if (!a2dp_cid){ 694 // incoming connection 695 a2dp_cid = cid; 696 } else if (cid != a2dp_cid) { 697 break; 698 } 699 if (status){ 700 a2dp_sink_connected = 0; 701 printf("A2DP Sink demo: streaming connection failed, status 0x%02x\n", status); 702 break; 703 } 704 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); 705 706 memcpy(device_addr, address, 6); 707 708 local_seid = a2dp_subevent_stream_established_get_local_seid(packet); 709 a2dp_sink_connected = 1; 710 break; 711 712 case A2DP_SUBEVENT_STREAM_STARTED: 713 cid = a2dp_subevent_stream_started_get_a2dp_cid(packet); 714 if (cid != a2dp_cid) break; 715 local_seid = a2dp_subevent_stream_started_get_local_seid(packet); 716 printf("A2DP Sink demo: stream started, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid); 717 // started 718 media_processing_init(sbc_configuration); 719 break; 720 721 case A2DP_SUBEVENT_STREAM_SUSPENDED: 722 cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet); 723 if (cid != a2dp_cid) break; 724 local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet); 725 printf("A2DP Sink demo: stream paused, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid); 726 media_processing_close(); 727 break; 728 729 case A2DP_SUBEVENT_STREAM_RELEASED: 730 cid = a2dp_subevent_stream_released_get_a2dp_cid(packet); 731 if (cid != a2dp_cid) { 732 printf("A2DP Sink demo: unexpected cid 0x%02x instead of 0x%02x\n", cid, a2dp_cid); 733 break; 734 } 735 local_seid = a2dp_subevent_stream_released_get_local_seid(packet); 736 printf("A2DP Sink demo: stream released, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid); 737 media_processing_close(); 738 break; 739 case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED: 740 cid = a2dp_subevent_signaling_connection_released_get_a2dp_cid(packet); 741 if (cid != a2dp_cid) { 742 printf("A2DP Sink demo: unexpected cid 0x%02x instead of 0x%02x\n", cid, a2dp_cid); 743 break; 744 } 745 a2dp_sink_connected = 0; 746 printf("A2DP Sink demo: signaling connection released\n"); 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