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 uint8_t status; 690 691 if (packet_type != HCI_EVENT_PACKET) return; 692 if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return; 693 694 switch (packet[2]){ 695 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION: 696 printf(" -- a2dp sink demo: received non SBC codec. not implemented.\n"); 697 break; 698 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{ 699 printf(" -- a2dp sink demo: received SBC codec configuration.\n"); 700 sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet); 701 sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet); 702 sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet); 703 sbc_configuration.channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet); 704 sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet); 705 sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet); 706 sbc_configuration.allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet); 707 sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet); 708 sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet); 709 sbc_configuration.frames_per_buffer = sbc_configuration.subbands * sbc_configuration.block_length; 710 dump_sbc_configuration(sbc_configuration); 711 712 if (sbc_configuration.reconfigure){ 713 media_processing_close(); 714 } 715 // prepare media processing 716 media_processing_init(sbc_configuration); 717 break; 718 } 719 case A2DP_SUBEVENT_STREAM_ESTABLISHED: 720 a2dp_subevent_stream_established_get_bd_addr(packet, address); 721 status = a2dp_subevent_stream_established_get_status(packet); 722 cid = a2dp_subevent_stream_established_get_a2dp_cid(packet); 723 if (cid != a2dp_cid) break; 724 if (status){ 725 app_state = AVDTP_APPLICATION_IDLE; 726 printf(" -- a2dp sink demo: streaming connection failed, status 0x%02x\n", status); 727 break; 728 } 729 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); 730 local_seid = a2dp_subevent_stream_established_get_local_seid(packet); 731 app_state = AVDTP_APPLICATION_STREAMING; 732 break; 733 734 case A2DP_SUBEVENT_STREAM_STARTED: 735 cid = a2dp_subevent_stream_started_get_a2dp_cid(packet); 736 if (cid != a2dp_cid) break; 737 local_seid = a2dp_subevent_stream_started_get_local_seid(packet); 738 printf(" -- a2dp sink demo: stream started, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid); 739 // started 740 media_processing_init(sbc_configuration); 741 break; 742 743 case A2DP_SUBEVENT_STREAM_SUSPENDED: 744 cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet); 745 if (cid != a2dp_cid) break; 746 local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet); 747 printf(" -- a2dp sink demo: stream paused, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid); 748 // paused/stopped 749 media_processing_close(); 750 break; 751 752 case A2DP_SUBEVENT_STREAM_RELEASED: 753 cid = a2dp_subevent_stream_released_get_a2dp_cid(packet); 754 if (cid != a2dp_cid) break; 755 local_seid = a2dp_subevent_stream_released_get_local_seid(packet); 756 app_state = AVDTP_APPLICATION_IDLE; 757 printf(" -- a2dp sink demo: stream released, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid); 758 759 // paused/stopped 760 media_processing_close(); 761 break; 762 763 default: 764 printf(" not implemented\n"); 765 break; 766 } 767 } 768 769 #ifdef HAVE_BTSTACK_STDIN 770 static void show_usage(void){ 771 bd_addr_t iut_address; 772 gap_local_bd_addr(iut_address); 773 printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address)); 774 printf("b - AVDTP Sink create connection to addr %s\n", device_addr_string); 775 printf("B - AVDTP Sink disconnect\n"); 776 printf("c - AVRCP create connection to addr %s\n", device_addr_string); 777 printf("C - AVRCP disconnect\n"); 778 779 printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address)); 780 printf("O - get play status\n"); 781 printf("j - get now playing info\n"); 782 printf("k - play\n"); 783 printf("K - stop\n"); 784 printf("L - pause\n"); 785 printf("u - start fast forward\n"); 786 printf("U - stop fast forward\n"); 787 printf("n - start rewind\n"); 788 printf("N - stop rewind\n"); 789 printf("i - forward\n"); 790 printf("I - backward\n"); 791 printf("t - volume up\n"); 792 printf("T - volume down\n"); 793 printf("p - absolute volume of 50 percent\n"); 794 printf("M - mute\n"); 795 printf("r - skip\n"); 796 printf("q - query repeat and shuffle mode\n"); 797 printf("v - repeat single track\n"); 798 printf("x - repeat all tracks\n"); 799 printf("X - disable repeat mode\n"); 800 printf("z - shuffle all tracks\n"); 801 printf("Z - disable shuffle mode\n"); 802 printf("---\n"); 803 } 804 #endif 805 806 static uint8_t media_sbc_codec_capabilities[] = { 807 0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO, 808 0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS, 809 2, 53 810 }; 811 812 static uint8_t media_sbc_codec_configuration[] = { 813 (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO, 814 (AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS, 815 2, 53 816 }; 817 818 #ifdef HAVE_BTSTACK_STDIN 819 static void stdin_process(char cmd){ 820 uint8_t status = ERROR_CODE_SUCCESS; 821 switch (cmd){ 822 case 'b': 823 printf(" - Create AVDTP connection to addr %s, and local seid %d.\n", bd_addr_to_str(device_addr), local_seid); 824 status = a2dp_sink_establish_stream(device_addr, local_seid, &a2dp_cid); 825 break; 826 case 'B': 827 printf(" - Disconnect\n"); 828 status = avdtp_sink_disconnect(a2dp_cid); 829 break; 830 case 'c': 831 printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr)); 832 status = avrcp_controller_connect(device_addr, &avrcp_cid); 833 break; 834 case 'C': 835 printf(" - Disconnect\n"); 836 status = avrcp_controller_disconnect(avrcp_cid); 837 break; 838 839 case '\n': 840 case '\r': 841 break; 842 case 'O': 843 printf(" - get play status\n"); 844 status = avrcp_controller_get_play_status(avrcp_cid); 845 break; 846 case 'j': 847 printf(" - get now playing info\n"); 848 status = avrcp_controller_get_now_playing_info(avrcp_cid); 849 break; 850 case 'k': 851 printf(" - play\n"); 852 status = avrcp_controller_play(avrcp_cid); 853 break; 854 case 'K': 855 printf(" - stop\n"); 856 status = avrcp_controller_stop(avrcp_cid); 857 break; 858 case 'L': 859 printf(" - pause\n"); 860 status = avrcp_controller_pause(avrcp_cid); 861 break; 862 case 'u': 863 printf(" - start fast forward\n"); 864 status = avrcp_controller_start_fast_forward(avrcp_cid); 865 break; 866 case 'U': 867 printf(" - stop fast forward\n"); 868 status = avrcp_controller_stop_fast_forward(avrcp_cid); 869 break; 870 case 'n': 871 printf(" - start rewind\n"); 872 status = avrcp_controller_start_rewind(avrcp_cid); 873 break; 874 case 'N': 875 printf(" - stop rewind\n"); 876 status = avrcp_controller_stop_rewind(avrcp_cid); 877 break; 878 case 'i': 879 printf(" - forward\n"); 880 status = avrcp_controller_forward(avrcp_cid); 881 break; 882 case 'I': 883 printf(" - backward\n"); 884 status = avrcp_controller_backward(avrcp_cid); 885 break; 886 case 't': 887 printf(" - volume up\n"); 888 status = avrcp_controller_volume_up(avrcp_cid); 889 break; 890 case 'T': 891 printf(" - volume down\n"); 892 status = avrcp_controller_volume_down(avrcp_cid); 893 break; 894 case 'p': 895 printf(" - absolute volume of 50 percent\n"); 896 status = avrcp_controller_set_absolute_volume(avrcp_cid, 50); 897 break; 898 case 'M': 899 printf(" - mute\n"); 900 status = avrcp_controller_mute(avrcp_cid); 901 break; 902 case 'r': 903 printf(" - skip\n"); 904 status = avrcp_controller_skip(avrcp_cid); 905 break; 906 case 'q': 907 printf(" - query repeat and shuffle mode\n"); 908 status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_cid); 909 break; 910 case 'v': 911 printf(" - repeat single track\n"); 912 status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK); 913 break; 914 case 'x': 915 printf(" - repeat all tracks\n"); 916 status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS); 917 break; 918 case 'X': 919 printf(" - disable repeat mode\n"); 920 status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_OFF); 921 break; 922 case 'z': 923 printf(" - shuffle all tracks\n"); 924 status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS); 925 break; 926 case 'Z': 927 printf(" - disable shuffle mode\n"); 928 status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_OFF); 929 break; 930 default: 931 show_usage(); 932 return; 933 } 934 if (status != ERROR_CODE_SUCCESS){ 935 printf("Could not perform command, status 0x%2x\n", status); 936 } 937 } 938 #endif 939 940 941 int btstack_main(int argc, const char * argv[]); 942 int btstack_main(int argc, const char * argv[]){ 943 944 UNUSED(argc); 945 (void)argv; 946 947 /* Register for HCI events */ 948 hci_event_callback_registration.callback = &packet_handler; 949 hci_add_event_handler(&hci_event_callback_registration); 950 951 l2cap_init(); 952 // Initialize AVDTP Sink 953 a2dp_sink_init(); 954 a2dp_sink_register_packet_handler(&packet_handler); 955 a2dp_sink_register_media_handler(&handle_l2cap_media_data_packet); 956 957 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)); 958 if (!local_stream_endpoint){ 959 printf("A2DP Sink: not enough memory to create local stream endpoint\n"); 960 return 1; 961 } 962 local_seid = avdtp_local_seid(local_stream_endpoint); 963 // Initialize AVRCP COntroller 964 avrcp_controller_init(); 965 avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler); 966 967 // Initialize SDP 968 sdp_init(); 969 // setup AVDTP sink 970 memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer)); 971 a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, 0x10001, 1, NULL, NULL); 972 sdp_register_service(sdp_avdtp_sink_service_buffer); 973 974 // setup AVRCP 975 memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer)); 976 avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10001, AVRCP_BROWSING_ENABLED, 1, NULL, NULL); 977 sdp_register_service(sdp_avrcp_controller_service_buffer); 978 979 gap_set_local_name("A2DP Sink Demo 00:00:00:00:00:00"); 980 gap_discoverable_control(1); 981 gap_set_class_of_device(0x200408); 982 printf("sdp, gap done\n"); 983 984 // turn on! 985 hci_power_control(HCI_POWER_ON); 986 987 #ifdef HAVE_AUDIO_DMA 988 static btstack_data_source_t hal_audio_dma_data_source; 989 // set up polling data_source 990 btstack_run_loop_set_data_source_handler(&hal_audio_dma_data_source, &hal_audio_dma_process); 991 btstack_run_loop_enable_data_source_callbacks(&hal_audio_dma_data_source, DATA_SOURCE_CALLBACK_POLL); 992 btstack_run_loop_add_data_source(&hal_audio_dma_data_source); 993 #endif 994 995 #ifdef HAVE_BTSTACK_STDIN 996 // parse human readable Bluetooth address 997 sscanf_bd_addr(device_addr_string, device_addr); 998 btstack_stdin_setup(stdin_process); 999 #endif 1000 1001 return 0; 1002 } 1003