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 39 #include <stdint.h> 40 #include <stdio.h> 41 #include <stdlib.h> 42 #include <string.h> 43 44 #include "btstack.h" 45 46 #define AVRCP_BROWSING_ENABLED 0 47 48 #ifdef HAVE_BTSTACK_STDIN 49 #include "btstack_stdin.h" 50 #endif 51 52 #ifdef HAVE_AUDIO_DMA 53 #include "btstack_ring_buffer.h" 54 #include "hal_audio_dma.h" 55 #endif 56 57 #ifdef HAVE_PORTAUDIO 58 #include "btstack_ring_buffer.h" 59 #include <portaudio.h> 60 #endif 61 62 #ifdef HAVE_POSIX_FILE_IO 63 #include "wav_util.h" 64 #define STORE_SBC_TO_SBC_FILE 65 #define STORE_SBC_TO_WAV_FILE 66 #endif 67 68 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE) || defined(HAVE_AUDIO_DMA) 69 #define DECODE_SBC 70 #endif 71 72 #define NUM_CHANNELS 2 73 #define BYTES_PER_FRAME (2*NUM_CHANNELS) 74 #define MAX_SBC_FRAME_SIZE 120 75 76 // SBC Decoder for WAV file or PortAudio 77 #ifdef DECODE_SBC 78 static btstack_sbc_decoder_state_t state; 79 static btstack_sbc_mode_t mode = SBC_MODE_STANDARD; 80 #endif 81 82 #if defined(HAVE_PORTAUDIO) || defined (HAVE_AUDIO_DMA) 83 #define PREBUFFER_MS 200 84 static int audio_stream_started = 0; 85 static int audio_stream_paused = 0; 86 static btstack_ring_buffer_t ring_buffer; 87 #endif 88 89 #ifdef HAVE_AUDIO_DMA 90 // below 30: add samples, 30-40: fine, above 40: drop samples 91 #define OPTIMAL_FRAMES_MIN 30 92 #define OPTIMAL_FRAMES_MAX 40 93 #define ADDITIONAL_FRAMES 10 94 #define DMA_AUDIO_FRAMES 128 95 #define DMA_MAX_FILL_FRAMES 1 96 #define NUM_AUDIO_BUFFERS 2 97 98 static uint16_t audio_samples[(DMA_AUDIO_FRAMES + DMA_MAX_FILL_FRAMES)*2*NUM_AUDIO_BUFFERS]; 99 static uint16_t audio_samples_len[NUM_AUDIO_BUFFERS]; 100 static uint8_t ring_buffer_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE]; 101 static const uint16_t silent_buffer[DMA_AUDIO_FRAMES*2]; 102 static volatile int playback_buffer; 103 static int write_buffer; 104 static uint8_t sbc_frame_size; 105 static int sbc_samples_fix; 106 #endif 107 108 // PortAdudio - live playback 109 #ifdef HAVE_PORTAUDIO 110 #define PA_SAMPLE_TYPE paInt16 111 #define SAMPLE_RATE 48000 112 #define FRAMES_PER_BUFFER 128 113 #define PREBUFFER_BYTES (PREBUFFER_MS*SAMPLE_RATE/1000*BYTES_PER_FRAME) 114 static PaStream * stream; 115 static uint8_t ring_buffer_storage[2*PREBUFFER_BYTES]; 116 static int total_num_samples = 0; 117 #endif 118 119 // WAV File 120 #ifdef STORE_SBC_TO_WAV_FILE 121 static int frame_count = 0; 122 static char * wav_filename = "avdtp_sink.wav"; 123 #endif 124 125 #ifdef STORE_SBC_TO_SBC_FILE 126 static FILE * sbc_file; 127 static char * sbc_filename = "avdtp_sink.sbc"; 128 #endif 129 130 typedef struct { 131 // bitmaps 132 uint8_t sampling_frequency_bitmap; 133 uint8_t channel_mode_bitmap; 134 uint8_t block_length_bitmap; 135 uint8_t subbands_bitmap; 136 uint8_t allocation_method_bitmap; 137 uint8_t min_bitpool_value; 138 uint8_t max_bitpool_value; 139 } adtvp_media_codec_information_sbc_t; 140 141 typedef struct { 142 int reconfigure; 143 int num_channels; 144 int sampling_frequency; 145 int channel_mode; 146 int block_length; 147 int subbands; 148 int allocation_method; 149 int min_bitpool_value; 150 int max_bitpool_value; 151 int frames_per_buffer; 152 } avdtp_media_codec_configuration_sbc_t; 153 154 #ifdef HAVE_BTSTACK_STDIN 155 // mac 2011: static bd_addr_t remote = {0x04, 0x0C, 0xCE, 0xE4, 0x85, 0xD3}; 156 // pts: static bd_addr_t remote = {0x00, 0x1B, 0xDC, 0x08, 0x0A, 0xA5}; 157 // mac 2013: 158 // mac 2013: static const char * device_addr_string = "84:38:35:65:d1:15"; 159 // iPhone 5S: 160 static const char * device_addr_string = "54:E4:3A:26:A2:39"; 161 #endif 162 163 // bt dongle: -u 02-02 static bd_addr_t remote = {0x00, 0x02, 0x72, 0xDC, 0x31, 0xC1}; 164 165 static uint8_t sdp_avdtp_sink_service_buffer[150]; 166 static avdtp_media_codec_configuration_sbc_t sbc_configuration; 167 static uint16_t a2dp_cid = 0; 168 static uint8_t local_seid = 0; 169 170 typedef enum { 171 AVDTP_APPLICATION_IDLE, 172 AVDTP_APPLICATION_CONNECTED, 173 AVDTP_APPLICATION_STREAMING 174 } avdtp_application_state_t; 175 176 avdtp_application_state_t app_state = AVDTP_APPLICATION_IDLE; 177 178 static btstack_packet_callback_registration_t hci_event_callback_registration; 179 180 static int media_initialized = 0; 181 182 #ifdef HAVE_BTSTACK_STDIN 183 static bd_addr_t device_addr; 184 #endif 185 186 static uint16_t avrcp_cid = 0; 187 static uint8_t sdp_avrcp_controller_service_buffer[200]; 188 189 #ifdef HAVE_PORTAUDIO 190 static int patestCallback( const void *inputBuffer, void *outputBuffer, 191 unsigned long framesPerBuffer, 192 const PaStreamCallbackTimeInfo* timeInfo, 193 PaStreamCallbackFlags statusFlags, 194 void *userData ) { 195 196 /** patestCallback is called from different thread, don't use hci_dump / log_info here without additional checks */ 197 198 (void) timeInfo; /* Prevent unused variable warnings. */ 199 (void) statusFlags; 200 (void) inputBuffer; 201 (void) userData; 202 203 int bytes_to_copy = framesPerBuffer * BYTES_PER_FRAME; 204 205 // fill with silence while paused 206 if (audio_stream_paused){ 207 208 if (btstack_ring_buffer_bytes_available(&ring_buffer) < PREBUFFER_BYTES){ 209 // printf("PA: silence\n"); 210 memset(outputBuffer, 0, bytes_to_copy); 211 return 0; 212 } else { 213 // resume playback 214 audio_stream_paused = 0; 215 } 216 } 217 218 // get data from ringbuffer 219 uint32_t bytes_read = 0; 220 btstack_ring_buffer_read(&ring_buffer, outputBuffer, bytes_to_copy, &bytes_read); 221 bytes_to_copy -= bytes_read; 222 223 // fill with 0 if not enough 224 if (bytes_to_copy){ 225 memset(outputBuffer + bytes_read, 0, bytes_to_copy); 226 audio_stream_paused = 1; 227 } 228 return 0; 229 } 230 #endif 231 232 #ifdef HAVE_AUDIO_DMA 233 static int next_buffer(int current){ 234 if (current == NUM_AUDIO_BUFFERS-1) return 0; 235 return current + 1; 236 } 237 static uint8_t * start_of_buffer(int num){ 238 return (uint8_t *) &audio_samples[num * DMA_AUDIO_FRAMES * 2]; 239 } 240 void hal_audio_dma_done(void){ 241 if (audio_stream_paused){ 242 hal_audio_dma_play((const uint8_t *) silent_buffer, DMA_AUDIO_FRAMES*4); 243 return; 244 } 245 // next buffer 246 int next_playback_buffer = next_buffer(playback_buffer); 247 uint8_t * playback_data; 248 if (next_playback_buffer == write_buffer){ 249 250 // TODO: stop codec while playing silence when getting 'stream paused' 251 252 // start playing silence 253 audio_stream_paused = 1; 254 hal_audio_dma_play((const uint8_t *) silent_buffer, DMA_AUDIO_FRAMES*4); 255 printf("%6u - paused - bytes in buffer %u\n", (int) btstack_run_loop_get_time_ms(), btstack_ring_buffer_bytes_available(&ring_buffer)); 256 return; 257 } 258 playback_buffer = next_playback_buffer; 259 playback_data = start_of_buffer(playback_buffer); 260 hal_audio_dma_play(playback_data, audio_samples_len[playback_buffer]); 261 // btstack_run_loop_embedded_trigger(); 262 } 263 #endif 264 265 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE) 266 267 static void handle_pcm_data(int16_t * data, int num_samples, int num_channels, int sample_rate, void * context){ 268 UNUSED(sample_rate); 269 UNUSED(context); 270 271 #ifdef STORE_SBC_TO_WAV_FILE 272 wav_writer_write_int16(num_samples*num_channels, data); 273 frame_count++; 274 #endif 275 276 #ifdef HAVE_PORTAUDIO 277 total_num_samples+=num_samples*num_channels; 278 279 // store pcm samples in ringbuffer 280 btstack_ring_buffer_write(&ring_buffer, (uint8_t *)data, num_samples*num_channels*2); 281 282 if (!audio_stream_started){ 283 audio_stream_paused = 1; 284 /* -- start stream -- */ 285 PaError err = Pa_StartStream(stream); 286 if (err != paNoError){ 287 printf("Error starting the stream: \"%s\"\n", Pa_GetErrorText(err)); 288 return; 289 } 290 audio_stream_started = 1; 291 } 292 #endif 293 294 } 295 #endif 296 297 298 #ifdef HAVE_AUDIO_DMA 299 300 static void handle_pcm_data(int16_t * data, int num_samples, int num_channels, int sample_rate, void * context){ 301 UNUSED(sample_rate); 302 UNUSED(context); 303 total_num_samples+=num_samples*num_channels; 304 305 // store in ring buffer 306 uint8_t * write_data = start_of_buffer(write_buffer); 307 uint16_t len = num_samples*num_channels*2; 308 memcpy(write_data, data, len); 309 audio_samples_len[write_buffer] = len; 310 311 // add/drop audio frame to fix drift 312 if (sbc_samples_fix > 0){ 313 memcpy(write_data + len, write_data + len - 4, 4); 314 audio_samples_len[write_buffer] += 4; 315 } 316 if (sbc_samples_fix < 0){ 317 audio_samples_len[write_buffer] -= 4; 318 } 319 320 write_buffer = next_buffer(write_buffer); 321 } 322 323 static void hal_audio_dma_process(btstack_data_source_t * ds, btstack_data_source_callback_type_t callback_type){ 324 UNUSED(ds); 325 UNUSED(callback_type); 326 327 if (!media_initialized) return; 328 329 int trigger_resume = 0; 330 if (audio_stream_paused) { 331 if (sbc_frame_size && btstack_ring_buffer_bytes_available(&ring_buffer) >= OPTIMAL_FRAMES_MIN * sbc_frame_size){ 332 trigger_resume = 1; 333 // reset buffers 334 playback_buffer = NUM_AUDIO_BUFFERS - 1; 335 write_buffer = 0; 336 } else { 337 return; 338 } 339 } 340 341 while (playback_buffer != write_buffer && btstack_ring_buffer_bytes_available(&ring_buffer) >= sbc_frame_size ){ 342 uint8_t frame[MAX_SBC_FRAME_SIZE]; 343 uint32_t bytes_read = 0; 344 btstack_ring_buffer_read(&ring_buffer, frame, sbc_frame_size, &bytes_read); 345 btstack_sbc_decoder_process_data(&state, 0, frame, sbc_frame_size); 346 } 347 348 if (trigger_resume){ 349 printf("%6u - resume\n", (int) btstack_run_loop_get_time_ms()); 350 audio_stream_paused = 0; 351 } 352 } 353 354 #endif 355 356 static int media_processing_init(avdtp_media_codec_configuration_sbc_t configuration){ 357 if (media_initialized) return 0; 358 359 #ifdef DECODE_SBC 360 btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL); 361 #endif 362 363 #ifdef STORE_SBC_TO_WAV_FILE 364 wav_writer_open(wav_filename, configuration.num_channels, configuration.sampling_frequency); 365 #endif 366 367 #ifdef STORE_SBC_TO_SBC_FILE 368 sbc_file = fopen(sbc_filename, "wb"); 369 #endif 370 371 #ifdef HAVE_PORTAUDIO 372 // int frames_per_buffer = configuration.frames_per_buffer; 373 PaError err; 374 PaStreamParameters outputParameters; 375 const PaDeviceInfo *deviceInfo; 376 377 /* -- initialize PortAudio -- */ 378 err = Pa_Initialize(); 379 if (err != paNoError){ 380 printf("Error initializing portaudio: \"%s\"\n", Pa_GetErrorText(err)); 381 return err; 382 } 383 /* -- setup input and output -- */ 384 outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ 385 outputParameters.channelCount = configuration.num_channels; 386 outputParameters.sampleFormat = PA_SAMPLE_TYPE; 387 outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency; 388 outputParameters.hostApiSpecificStreamInfo = NULL; 389 deviceInfo = Pa_GetDeviceInfo( outputParameters.device ); 390 printf("PortAudio: Output device: %s\n", deviceInfo->name); 391 log_info("PortAudio: Output device: %s", deviceInfo->name); 392 /* -- setup stream -- */ 393 err = Pa_OpenStream( 394 &stream, 395 NULL, /* &inputParameters */ 396 &outputParameters, 397 configuration.sampling_frequency, 398 0, 399 paClipOff, /* we won't output out of range samples so don't bother clipping them */ 400 patestCallback, /* use callback */ 401 NULL ); 402 403 if (err != paNoError){ 404 printf("Error initializing portaudio: \"%s\"\n", Pa_GetErrorText(err)); 405 return err; 406 } 407 log_info("PortAudio: stream opened"); 408 printf("PortAudio: stream opened\n"); 409 #endif 410 #ifdef HAVE_AUDIO_DMA 411 audio_stream_paused = 1; 412 hal_audio_dma_init(configuration.sampling_frequency); 413 hal_audio_dma_set_audio_played(&hal_audio_dma_done); 414 // start playing silence 415 hal_audio_dma_done(); 416 #endif 417 418 #if defined(HAVE_PORTAUDIO) || defined (HAVE_AUDIO_DMA) 419 memset(ring_buffer_storage, 0, sizeof(ring_buffer_storage)); 420 btstack_ring_buffer_init(&ring_buffer, ring_buffer_storage, sizeof(ring_buffer_storage)); 421 audio_stream_started = 0; 422 #endif 423 media_initialized = 1; 424 return 0; 425 } 426 427 static void media_processing_close(void){ 428 if (!media_initialized) return; 429 media_initialized = 0; 430 431 #ifdef STORE_SBC_TO_WAV_FILE 432 printf("WAV Writer: close file.\n"); 433 wav_writer_close(); 434 int total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr; 435 436 printf("WAV Writer: Decoding done. Processed totaly %d frames:\n - %d good\n - %d bad\n - %d zero frames\n", total_frames_nr, state.good_frames_nr, state.bad_frames_nr, state.zero_frames_nr); 437 printf("WAV Writer: Written %d frames to wav file: %s\n", frame_count, wav_filename); 438 #endif 439 440 #ifdef STORE_SBC_TO_SBC_FILE 441 fclose(sbc_file); 442 #endif 443 444 #if defined(HAVE_PORTAUDIO) || defined (HAVE_AUDIO_DMA) 445 audio_stream_started = 0; 446 #endif 447 448 #ifdef HAVE_PORTAUDIO 449 printf("PortAudio: Steram closed\n"); 450 log_info("PortAudio: Stream closed"); 451 452 PaError err = Pa_StopStream(stream); 453 if (err != paNoError){ 454 printf("Error stopping the stream: \"%s\"\n", Pa_GetErrorText(err)); 455 log_error("Error stopping the stream: \"%s\"", Pa_GetErrorText(err)); 456 return; 457 } 458 err = Pa_CloseStream(stream); 459 if (err != paNoError){ 460 printf("Error closing the stream: \"%s\"\n", Pa_GetErrorText(err)); 461 log_error("Error closing the stream: \"%s\"", Pa_GetErrorText(err)); 462 return; 463 } 464 err = Pa_Terminate(); 465 if (err != paNoError){ 466 printf("Error terminating portaudio: \"%s\"\n", Pa_GetErrorText(err)); 467 log_error("Error terminating portaudio: \"%s\"", Pa_GetErrorText(err)); 468 return; 469 } 470 #endif 471 472 #ifdef HAVE_AUDIO_DMA 473 hal_audio_dma_close(); 474 #endif 475 } 476 477 static void handle_l2cap_media_data_packet(avdtp_stream_endpoint_t * stream_endpoint, uint8_t *packet, uint16_t size){ 478 UNUSED(stream_endpoint); 479 480 int pos = 0; 481 482 avdtp_media_packet_header_t media_header; 483 media_header.version = packet[pos] & 0x03; 484 media_header.padding = get_bit16(packet[pos],2); 485 media_header.extension = get_bit16(packet[pos],3); 486 media_header.csrc_count = (packet[pos] >> 4) & 0x0F; 487 488 pos++; 489 490 media_header.marker = get_bit16(packet[pos],0); 491 media_header.payload_type = (packet[pos] >> 1) & 0x7F; 492 pos++; 493 494 media_header.sequence_number = big_endian_read_16(packet, pos); 495 pos+=2; 496 497 media_header.timestamp = big_endian_read_32(packet, pos); 498 pos+=4; 499 500 media_header.synchronization_source = big_endian_read_32(packet, pos); 501 pos+=4; 502 503 UNUSED(media_header); 504 505 // TODO: read csrc list 506 507 // printf_hexdump( packet, pos ); 508 // printf("MEDIA HEADER: %u timestamp, version %u, padding %u, extension %u, csrc_count %u\n", 509 // media_header.timestamp, media_header.version, media_header.padding, media_header.extension, media_header.csrc_count); 510 // printf("MEDIA HEADER: marker %02x, payload_type %02x, sequence_number %u, synchronization_source %u\n", 511 // media_header.marker, media_header.payload_type, media_header.sequence_number, media_header.synchronization_source); 512 513 avdtp_sbc_codec_header_t sbc_header; 514 sbc_header.fragmentation = get_bit16(packet[pos], 7); 515 sbc_header.starting_packet = get_bit16(packet[pos], 6); 516 sbc_header.last_packet = get_bit16(packet[pos], 5); 517 sbc_header.num_frames = packet[pos] & 0x0f; 518 pos++; 519 520 #ifdef HAVE_AUDIO_DMA 521 // store sbc frame size for buffer management 522 sbc_frame_size = (size-pos)/ sbc_header.num_frames; 523 #endif 524 525 UNUSED(sbc_header); 526 // 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); 527 // printf_hexdump( packet+pos, size-pos ); 528 529 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE) 530 btstack_sbc_decoder_process_data(&state, 0, packet+pos, size-pos); 531 #endif 532 533 #ifdef HAVE_AUDIO_DMA 534 btstack_ring_buffer_write(&ring_buffer, packet+pos, size-pos); 535 536 // decide on audio sync drift based on number of sbc frames in queue 537 int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&ring_buffer) / sbc_frame_size; 538 if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){ 539 sbc_samples_fix = 1; // duplicate last sample 540 } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){ 541 sbc_samples_fix = 0; // nothing to do 542 } else { 543 sbc_samples_fix = -1; // drop last sample 544 } 545 546 // dump 547 printf("%6u %03u %d\n", (int) btstack_run_loop_get_time_ms(), sbc_frames_in_buffer, sbc_samples_fix); 548 549 #endif 550 551 #ifdef STORE_SBC_TO_SBC_FILE 552 fwrite(packet+pos, size-pos, 1, sbc_file); 553 #endif 554 } 555 556 static void dump_sbc_configuration(avdtp_media_codec_configuration_sbc_t configuration){ 557 printf(" -- a2dp sink demo: Received media codec configuration:\n"); 558 printf(" - num_channels: %d\n", configuration.num_channels); 559 printf(" - sampling_frequency: %d\n", configuration.sampling_frequency); 560 printf(" - channel_mode: %d\n", configuration.channel_mode); 561 printf(" - block_length: %d\n", configuration.block_length); 562 printf(" - subbands: %d\n", configuration.subbands); 563 printf(" - allocation_method: %d\n", configuration.allocation_method); 564 printf(" - bitpool_value [%d, %d] \n", configuration.min_bitpool_value, configuration.max_bitpool_value); 565 printf("\n"); 566 } 567 568 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 569 UNUSED(channel); 570 UNUSED(size); 571 uint16_t local_cid; 572 uint8_t status = 0xFF; 573 bd_addr_t adress; 574 575 if (packet_type != HCI_EVENT_PACKET) return; 576 if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return; 577 switch (packet[2]){ 578 case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: { 579 local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet); 580 if (avrcp_cid != 0 && avrcp_cid != local_cid) { 581 printf("AVRCP Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_cid, local_cid); 582 return; 583 } 584 585 status = avrcp_subevent_connection_established_get_status(packet); 586 if (status != ERROR_CODE_SUCCESS){ 587 printf("AVRCP Connection failed: status 0x%02x\n", status); 588 avrcp_cid = 0; 589 return; 590 } 591 592 avrcp_cid = local_cid; 593 avrcp_subevent_connection_established_get_bd_addr(packet, adress); 594 printf("Channel successfully opened: %s, avrcp_cid 0x%02x\n", bd_addr_to_str(adress), avrcp_cid); 595 596 // automatically enable notifications 597 avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED); 598 avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED); 599 return; 600 } 601 case AVRCP_SUBEVENT_CONNECTION_RELEASED: 602 printf("Channel released: avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet)); 603 avrcp_cid = 0; 604 return; 605 default: 606 break; 607 } 608 609 status = packet[5]; 610 if (!avrcp_cid) return; 611 612 // avoid printing INTERIM status 613 if (status == AVRCP_CTYPE_RESPONSE_INTERIM) return; 614 615 printf("AVRCP: command status: %s, ", avrcp_ctype2str(status)); 616 switch (packet[2]){ 617 case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED: 618 printf("notification, playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet))); 619 return; 620 case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED: 621 printf("notification, playing content changed\n"); 622 return; 623 case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED: 624 printf("notification track changed\n"); 625 return; 626 case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED: 627 printf("notification absolute volume changed %d\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet)); 628 return; 629 case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED: 630 printf("notification changed\n"); 631 return; 632 case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{ 633 uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet); 634 uint8_t repeat_mode = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet); 635 printf("%s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode)); 636 break; 637 } 638 case AVRCP_SUBEVENT_NOW_PLAYING_INFO:{ 639 uint8_t value[100]; 640 printf("now playing: \n"); 641 if (avrcp_subevent_now_playing_info_get_title_len(packet) > 0){ 642 memcpy(value, avrcp_subevent_now_playing_info_get_title(packet), avrcp_subevent_now_playing_info_get_title_len(packet)); 643 printf(" Title: %s\n", value); 644 } 645 if (avrcp_subevent_now_playing_info_get_album_len(packet) > 0){ 646 memcpy(value, avrcp_subevent_now_playing_info_get_album(packet), avrcp_subevent_now_playing_info_get_album_len(packet)); 647 printf(" Album: %s\n", value); 648 } 649 if (avrcp_subevent_now_playing_info_get_artist_len(packet) > 0){ 650 memcpy(value, avrcp_subevent_now_playing_info_get_artist(packet), avrcp_subevent_now_playing_info_get_artist_len(packet)); 651 printf(" Artist: %s\n", value); 652 } 653 if (avrcp_subevent_now_playing_info_get_genre_len(packet) > 0){ 654 memcpy(value, avrcp_subevent_now_playing_info_get_genre(packet), avrcp_subevent_now_playing_info_get_genre_len(packet)); 655 printf(" Genre: %s\n", value); 656 } 657 printf(" Track: %d\n", avrcp_subevent_now_playing_info_get_track(packet)); 658 printf(" Total nr. tracks: %d\n", avrcp_subevent_now_playing_info_get_total_tracks(packet)); 659 printf(" Song length: %d ms\n", avrcp_subevent_now_playing_info_get_song_length(packet)); 660 break; 661 } 662 case AVRCP_SUBEVENT_PLAY_STATUS: 663 printf("song length: %d ms, song position: %d ms, play status: %s\n", 664 avrcp_subevent_play_status_get_song_length(packet), 665 avrcp_subevent_play_status_get_song_position(packet), 666 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet))); 667 break; 668 case AVRCP_SUBEVENT_OPERATION_COMPLETE: 669 printf("operation done %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet))); 670 break; 671 case AVRCP_SUBEVENT_OPERATION_START: 672 printf("operation start %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet))); 673 break; 674 case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE: 675 // response to set shuffle and repeat mode 676 printf("\n"); 677 break; 678 default: 679 printf("Not implemented\n"); 680 break; 681 } 682 } 683 684 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 685 UNUSED(channel); 686 UNUSED(size); 687 uint16_t cid; 688 bd_addr_t address; 689 690 if (packet_type != HCI_EVENT_PACKET) return; 691 if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return; 692 693 switch (packet[2]){ 694 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION: 695 printf(" -- a2dp sink demo: received non SBC codec. not implemented.\n"); 696 break; 697 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{ 698 printf(" -- a2dp sink demo: received SBC codec configuration.\n"); 699 sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet); 700 sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet); 701 sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet); 702 sbc_configuration.channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet); 703 sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet); 704 sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet); 705 sbc_configuration.allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet); 706 sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet); 707 sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet); 708 sbc_configuration.frames_per_buffer = sbc_configuration.subbands * sbc_configuration.block_length; 709 dump_sbc_configuration(sbc_configuration); 710 711 if (sbc_configuration.reconfigure){ 712 media_processing_close(); 713 } 714 // prepare media processing 715 media_processing_init(sbc_configuration); 716 break; 717 } 718 case A2DP_SUBEVENT_STREAM_ESTABLISHED: 719 a2dp_subevent_stream_established_get_bd_addr(packet, address); 720 cid = a2dp_subevent_stream_established_get_a2dp_cid(packet); 721 if (cid != a2dp_cid) break; 722 local_seid = a2dp_subevent_stream_established_get_local_seid(packet); 723 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); 724 app_state = AVDTP_APPLICATION_STREAMING; 725 break; 726 727 case A2DP_SUBEVENT_STREAM_STARTED: 728 cid = a2dp_subevent_stream_started_get_a2dp_cid(packet); 729 if (cid != a2dp_cid) break; 730 local_seid = a2dp_subevent_stream_started_get_local_seid(packet); 731 printf(" -- a2dp sink demo: stream started, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid); 732 // started 733 media_processing_init(sbc_configuration); 734 break; 735 736 case A2DP_SUBEVENT_STREAM_SUSPENDED: 737 cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet); 738 if (cid != a2dp_cid) break; 739 local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet); 740 printf(" -- a2dp sink demo: stream paused, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid); 741 // paused/stopped 742 media_processing_close(); 743 break; 744 745 case A2DP_SUBEVENT_STREAM_RELEASED: 746 cid = a2dp_subevent_stream_released_get_a2dp_cid(packet); 747 if (cid != a2dp_cid) break; 748 local_seid = a2dp_subevent_stream_released_get_local_seid(packet); 749 app_state = AVDTP_APPLICATION_IDLE; 750 printf(" -- a2dp sink demo: stream released, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid); 751 752 // paused/stopped 753 media_processing_close(); 754 break; 755 756 default: 757 printf(" not implemented\n"); 758 break; 759 } 760 } 761 762 #ifdef HAVE_BTSTACK_STDIN 763 static void show_usage(void){ 764 bd_addr_t iut_address; 765 gap_local_bd_addr(iut_address); 766 printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address)); 767 printf("b - AVDTP Sink create connection to addr %s\n", device_addr_string); 768 printf("B - AVDTP Sink disconnect\n"); 769 printf("c - AVRCP create connection to addr %s\n", device_addr_string); 770 printf("C - AVRCP disconnect\n"); 771 772 printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address)); 773 printf("O - get play status\n"); 774 printf("j - get now playing info\n"); 775 printf("k - play\n"); 776 printf("K - stop\n"); 777 printf("L - pause\n"); 778 printf("u - start fast forward\n"); 779 printf("U - stop fast forward\n"); 780 printf("n - start rewind\n"); 781 printf("N - stop rewind\n"); 782 printf("i - forward\n"); 783 printf("I - backward\n"); 784 printf("t - volume up\n"); 785 printf("T - volume down\n"); 786 printf("p - absolute volume of 50 percent\n"); 787 printf("M - mute\n"); 788 printf("r - skip\n"); 789 printf("q - query repeat and shuffle mode\n"); 790 printf("v - repeat single track\n"); 791 printf("x - repeat all tracks\n"); 792 printf("X - disable repeat mode\n"); 793 printf("z - shuffle all tracks\n"); 794 printf("Z - disable shuffle mode\n"); 795 printf("---\n"); 796 } 797 #endif 798 799 static uint8_t media_sbc_codec_capabilities[] = { 800 0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO, 801 0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS, 802 2, 53 803 }; 804 805 static uint8_t media_sbc_codec_configuration[] = { 806 (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO, 807 (AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS, 808 2, 53 809 }; 810 811 #ifdef HAVE_BTSTACK_STDIN 812 static void stdin_process(char cmd){ 813 uint8_t status = ERROR_CODE_SUCCESS; 814 switch (cmd){ 815 case 'b': 816 printf(" - Create AVDTP connection to addr %s.\n", bd_addr_to_str(device_addr)); 817 status = a2dp_sink_establish_stream(device_addr, local_seid, &a2dp_cid); 818 break; 819 case 'B': 820 printf(" - Disconnect\n"); 821 status = avdtp_sink_disconnect(a2dp_cid); 822 break; 823 case 'c': 824 printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr)); 825 status = avrcp_controller_connect(device_addr, &avrcp_cid); 826 break; 827 case 'C': 828 printf(" - Disconnect\n"); 829 status = avrcp_controller_disconnect(avrcp_cid); 830 break; 831 832 case '\n': 833 case '\r': 834 break; 835 case 'O': 836 printf(" - get play status\n"); 837 status = avrcp_controller_get_play_status(avrcp_cid); 838 break; 839 case 'j': 840 printf(" - get now playing info\n"); 841 status = avrcp_controller_get_now_playing_info(avrcp_cid); 842 break; 843 case 'k': 844 printf(" - play\n"); 845 status = avrcp_controller_play(avrcp_cid); 846 break; 847 case 'K': 848 printf(" - stop\n"); 849 status = avrcp_controller_stop(avrcp_cid); 850 break; 851 case 'L': 852 printf(" - pause\n"); 853 status = avrcp_controller_pause(avrcp_cid); 854 break; 855 case 'u': 856 printf(" - start fast forward\n"); 857 status = avrcp_controller_start_fast_forward(avrcp_cid); 858 break; 859 case 'U': 860 printf(" - stop fast forward\n"); 861 status = avrcp_controller_stop_fast_forward(avrcp_cid); 862 break; 863 case 'n': 864 printf(" - start rewind\n"); 865 status = avrcp_controller_start_rewind(avrcp_cid); 866 break; 867 case 'N': 868 printf(" - stop rewind\n"); 869 status = avrcp_controller_stop_rewind(avrcp_cid); 870 break; 871 case 'i': 872 printf(" - forward\n"); 873 status = avrcp_controller_forward(avrcp_cid); 874 break; 875 case 'I': 876 printf(" - backward\n"); 877 status = avrcp_controller_backward(avrcp_cid); 878 break; 879 case 't': 880 printf(" - volume up\n"); 881 status = avrcp_controller_volume_up(avrcp_cid); 882 break; 883 case 'T': 884 printf(" - volume down\n"); 885 status = avrcp_controller_volume_down(avrcp_cid); 886 break; 887 case 'p': 888 printf(" - absolute volume of 50 percent\n"); 889 status = avrcp_controller_set_absolute_volume(avrcp_cid, 50); 890 break; 891 case 'M': 892 printf(" - mute\n"); 893 status = avrcp_controller_mute(avrcp_cid); 894 break; 895 case 'r': 896 printf(" - skip\n"); 897 status = avrcp_controller_skip(avrcp_cid); 898 break; 899 case 'q': 900 printf(" - query repeat and shuffle mode\n"); 901 status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_cid); 902 break; 903 case 'v': 904 printf(" - repeat single track\n"); 905 status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK); 906 break; 907 case 'x': 908 printf(" - repeat all tracks\n"); 909 status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS); 910 break; 911 case 'X': 912 printf(" - disable repeat mode\n"); 913 status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_OFF); 914 break; 915 case 'z': 916 printf(" - shuffle all tracks\n"); 917 status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS); 918 break; 919 case 'Z': 920 printf(" - disable shuffle mode\n"); 921 status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_OFF); 922 break; 923 default: 924 show_usage(); 925 return; 926 } 927 if (status != ERROR_CODE_SUCCESS){ 928 printf("Could not perform command, status 0x%2x\n", status); 929 } 930 } 931 #endif 932 933 934 int btstack_main(int argc, const char * argv[]); 935 int btstack_main(int argc, const char * argv[]){ 936 937 UNUSED(argc); 938 (void)argv; 939 940 /* Register for HCI events */ 941 hci_event_callback_registration.callback = &packet_handler; 942 hci_add_event_handler(&hci_event_callback_registration); 943 944 l2cap_init(); 945 // Initialize AVDTP Sink 946 a2dp_sink_init(); 947 a2dp_sink_register_packet_handler(&packet_handler); 948 a2dp_sink_register_media_handler(&handle_l2cap_media_data_packet); 949 950 avdtp_stream_endpoint_t * local_stream_endpoint = 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)); 951 if (!local_stream_endpoint){ 952 printf("A2DP Sink: not enough memory to create local stream endpoint\n"); 953 return 1; 954 } 955 local_seid = avdtp_local_seid(local_stream_endpoint); 956 // Initialize AVRCP COntroller 957 avrcp_controller_init(); 958 avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler); 959 960 // Initialize SDP 961 sdp_init(); 962 // setup AVDTP sink 963 memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer)); 964 a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, 0x10001, 1, NULL, NULL); 965 sdp_register_service(sdp_avdtp_sink_service_buffer); 966 967 // setup AVRCP 968 memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer)); 969 avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10001, AVRCP_BROWSING_ENABLED, 1, NULL, NULL); 970 sdp_register_service(sdp_avrcp_controller_service_buffer); 971 972 gap_set_local_name("A2DP Sink Demo 00:00:00:00:00:00"); 973 gap_discoverable_control(1); 974 gap_set_class_of_device(0x200408); 975 printf("sdp, gap done\n"); 976 977 // turn on! 978 hci_power_control(HCI_POWER_ON); 979 980 #ifdef HAVE_AUDIO_DMA 981 static btstack_data_source_t hal_audio_dma_data_source; 982 // set up polling data_source 983 btstack_run_loop_set_data_source_handler(&hal_audio_dma_data_source, &hal_audio_dma_process); 984 btstack_run_loop_enable_data_source_callbacks(&hal_audio_dma_data_source, DATA_SOURCE_CALLBACK_POLL); 985 btstack_run_loop_add_data_source(&hal_audio_dma_data_source); 986 #endif 987 988 #ifdef HAVE_BTSTACK_STDIN 989 // parse human readable Bluetooth address 990 sscanf_bd_addr(device_addr_string, device_addr); 991 btstack_stdin_setup(stdin_process); 992 #endif 993 994 return 0; 995 } 996