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