1 /* 2 * Copyright (C) 2023 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 BLUEKITCHEN 24 * GMBH 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): A2DP Sink - Receive Audio Stream and Control 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. If HAVE_BTSTACK_STDIN is set, press SPACE on 52 * the console to show the available AVDTP and AVRCP commands. 53 * 54 * @text To test with a remote device, e.g. a mobile phone, 55 * pair from the remote device with the demo, then start playing music on the remote device. 56 * Alternatively, set the device_addr_string to the Bluetooth address of your 57 * remote device in the code, and call connect from the UI. 58 * 59 * @text For more info on BTstack audio, see our blog post 60 * [A2DP Sink and Source on STM32 F4 Discovery Board](http://bluekitchen-gmbh.com/a2dp-sink-and-source-on-stm32-f4-discovery-board/). 61 * 62 */ 63 // ***************************************************************************** 64 65 #include <inttypes.h> 66 #include <stdint.h> 67 #include <stdio.h> 68 #include <string.h> 69 70 #include "btstack.h" 71 #include "btstack_resample.h" 72 73 //#define AVRCP_BROWSING_ENABLED 74 75 #ifdef HAVE_BTSTACK_STDIN 76 #include "btstack_stdin.h" 77 #endif 78 79 #ifdef HAVE_BTSTACK_AUDIO_EFFECTIVE_SAMPLERATE 80 #include "btstack_sample_rate_compensation.h" 81 #endif 82 83 #include "btstack_ring_buffer.h" 84 85 #ifdef HAVE_POSIX_FILE_IO 86 #include "wav_util.h" 87 #define STORE_TO_WAV_FILE 88 #endif 89 90 #define NUM_CHANNELS 2 91 #define BYTES_PER_FRAME (2*NUM_CHANNELS) 92 #define MAX_SBC_FRAME_SIZE 120 93 94 #ifdef HAVE_BTSTACK_STDIN 95 static const char * device_addr_string = "00:1B:DC:08:E2:72"; // pts v5.0 96 static bd_addr_t device_addr; 97 #endif 98 99 #ifdef HAVE_BTSTACK_AUDIO_EFFECTIVE_SAMPLERATE 100 static btstack_sample_rate_compensation_t sample_rate_compensation; 101 #endif 102 103 static btstack_packet_callback_registration_t hci_event_callback_registration; 104 105 static uint8_t sdp_avdtp_sink_service_buffer[150]; 106 static uint8_t sdp_avrcp_target_service_buffer[150]; 107 static uint8_t sdp_avrcp_controller_service_buffer[200]; 108 static uint8_t device_id_sdp_service_buffer[100]; 109 110 // we support all configurations with bitpool 2-53 111 static uint8_t media_sbc_codec_capabilities[] = { 112 0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO, 113 0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS, 114 2, 53 115 }; 116 117 // WAV File 118 #ifdef STORE_TO_WAV_FILE 119 static uint32_t audio_frame_count = 0; 120 static char * wav_filename = "a2dp_sink_demo.wav"; 121 #endif 122 123 // SBC Decoder for WAV file or live playback 124 static btstack_sbc_decoder_state_t state; 125 static btstack_sbc_mode_t mode = SBC_MODE_STANDARD; 126 127 // ring buffer for SBC Frames 128 // below 30: add samples, 30-40: fine, above 40: drop samples 129 #define OPTIMAL_FRAMES_MIN 60 130 #define OPTIMAL_FRAMES_MAX 80 131 #define ADDITIONAL_FRAMES 30 132 static uint8_t sbc_frame_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE]; 133 static btstack_ring_buffer_t sbc_frame_ring_buffer; 134 static unsigned int sbc_frame_size; 135 136 // overflow buffer for not fully used sbc frames, with additional frames for resampling 137 static uint8_t decoded_audio_storage[(128+16) * BYTES_PER_FRAME]; 138 static btstack_ring_buffer_t decoded_audio_ring_buffer; 139 140 static int media_initialized = 0; 141 static int audio_stream_started; 142 #ifdef HAVE_BTSTACK_AUDIO_EFFECTIVE_SAMPLERATE 143 static int l2cap_stream_started; 144 #endif 145 static btstack_resample_t resample_instance; 146 147 // temp storage of lower-layer request for audio samples 148 static int16_t * request_buffer; 149 static int request_frames; 150 151 // sink state 152 static int volume_percentage = 0; 153 static avrcp_battery_status_t battery_status = AVRCP_BATTERY_STATUS_WARNING; 154 155 #ifdef ENABLE_AVRCP_COVER_ART 156 static char a2dp_sink_demo_image_handle[8]; 157 static avrcp_cover_art_client_t a2dp_sink_demo_cover_art_client; 158 static bool a2dp_sink_demo_cover_art_client_connected; 159 static uint16_t a2dp_sink_demo_cover_art_cid; 160 static uint8_t a2dp_sink_demo_ertm_buffer[2000]; 161 static l2cap_ertm_config_t a2dp_sink_demo_ertm_config = { 162 1, // ertm mandatory 163 2, // max transmit, some tests require > 1 164 2000, 165 12000, 166 512, // l2cap ertm mtu 167 2, 168 2, 169 1, // 16-bit FCS 170 }; 171 static bool a2dp_sink_cover_art_download_active; 172 static uint32_t a2dp_sink_cover_art_file_size; 173 #ifdef HAVE_POSIX_FILE_IO 174 static const char * a2dp_sink_demo_thumbnail_path = "cover.jpg"; 175 static FILE * a2dp_sink_cover_art_file; 176 #endif 177 #endif 178 179 typedef struct { 180 uint8_t reconfigure; 181 uint8_t num_channels; 182 uint16_t sampling_frequency; 183 uint8_t block_length; 184 uint8_t subbands; 185 uint8_t min_bitpool_value; 186 uint8_t max_bitpool_value; 187 btstack_sbc_channel_mode_t channel_mode; 188 btstack_sbc_allocation_method_t allocation_method; 189 } media_codec_configuration_sbc_t; 190 191 typedef enum { 192 STREAM_STATE_CLOSED, 193 STREAM_STATE_OPEN, 194 STREAM_STATE_PLAYING, 195 STREAM_STATE_PAUSED, 196 } stream_state_t; 197 198 typedef struct { 199 uint8_t a2dp_local_seid; 200 uint8_t media_sbc_codec_configuration[4]; 201 } a2dp_sink_demo_stream_endpoint_t; 202 static a2dp_sink_demo_stream_endpoint_t a2dp_sink_demo_stream_endpoint; 203 204 typedef struct { 205 bd_addr_t addr; 206 uint16_t a2dp_cid; 207 uint8_t a2dp_local_seid; 208 stream_state_t stream_state; 209 media_codec_configuration_sbc_t sbc_configuration; 210 } a2dp_sink_demo_a2dp_connection_t; 211 static a2dp_sink_demo_a2dp_connection_t a2dp_sink_demo_a2dp_connection; 212 213 typedef struct { 214 bd_addr_t addr; 215 uint16_t avrcp_cid; 216 bool playing; 217 uint16_t notifications_supported_by_target; 218 } a2dp_sink_demo_avrcp_connection_t; 219 static a2dp_sink_demo_avrcp_connection_t a2dp_sink_demo_avrcp_connection; 220 221 /* @section Main Application Setup 222 * 223 * @text The Listing MainConfiguration shows how to set up AD2P Sink and AVRCP services. 224 * Besides calling init() method for each service, you'll also need to register several packet handlers: 225 * - hci_packet_handler - handles legacy pairing, here by using fixed '0000' pin code. 226 * - 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). 227 * - handle_l2cap_media_data_packet - used to receive streaming data. If STORE_TO_WAV_FILE directive (check btstack_config.h) is 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. 228 * - avrcp_packet_handler - receives AVRCP connect/disconnect event. 229 * - avrcp_controller_packet_handler - receives answers for sent AVRCP commands. 230 * - avrcp_target_packet_handler - receives AVRCP commands, and registered notifications. 231 * - stdin_process - used to trigger AVRCP commands to the A2DP Source device, such are get now playing info, start, stop, volume control. Requires HAVE_BTSTACK_STDIN. 232 * 233 * @text To announce A2DP Sink and AVRCP services, you need to create corresponding 234 * SDP records and register them with the SDP service. 235 * 236 * @text Note, currently only the SBC codec is supported. 237 * If you want to store the audio data in a file, you'll need to define STORE_TO_WAV_FILE. 238 * If STORE_TO_WAV_FILE directive is defined, the SBC decoder needs to get initialized when a2dp_sink_packet_handler receives event A2DP_SUBEVENT_STREAM_STARTED. 239 * The initialization of the SBC decoder requires a callback that handles PCM data: 240 * - handle_pcm_data - handles PCM audio frames. Here, they are stored in a wav file if STORE_TO_WAV_FILE is defined, and/or played using the audio library. 241 */ 242 243 /* LISTING_START(MainConfiguration): Setup Audio Sink and AVRCP services */ 244 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 245 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t event_size); 246 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size); 247 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 248 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 249 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 250 #ifdef HAVE_BTSTACK_STDIN 251 static void stdin_process(char cmd); 252 #endif 253 254 static int setup_demo(void){ 255 256 // init protocols 257 l2cap_init(); 258 sdp_init(); 259 #ifdef ENABLE_BLE 260 // Initialize LE Security Manager. Needed for cross-transport key derivation 261 sm_init(); 262 #endif 263 #ifdef ENABLE_AVRCP_COVER_ART 264 goep_client_init(); 265 avrcp_cover_art_client_init(); 266 #endif 267 268 // Init profiles 269 a2dp_sink_init(); 270 avrcp_init(); 271 avrcp_controller_init(); 272 avrcp_target_init(); 273 274 275 // Configure A2DP Sink 276 a2dp_sink_register_packet_handler(&a2dp_sink_packet_handler); 277 a2dp_sink_register_media_handler(&handle_l2cap_media_data_packet); 278 a2dp_sink_demo_stream_endpoint_t * stream_endpoint = &a2dp_sink_demo_stream_endpoint; 279 avdtp_stream_endpoint_t * local_stream_endpoint = a2dp_sink_create_stream_endpoint(AVDTP_AUDIO, 280 AVDTP_CODEC_SBC, media_sbc_codec_capabilities, sizeof(media_sbc_codec_capabilities), 281 stream_endpoint->media_sbc_codec_configuration, sizeof(stream_endpoint->media_sbc_codec_configuration)); 282 btstack_assert(local_stream_endpoint != NULL); 283 // - Store stream enpoint's SEP ID, as it is used by A2DP API to identify the stream endpoint 284 stream_endpoint->a2dp_local_seid = avdtp_local_seid(local_stream_endpoint); 285 286 287 // Configure AVRCP Controller + Target 288 avrcp_register_packet_handler(&avrcp_packet_handler); 289 avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler); 290 avrcp_target_register_packet_handler(&avrcp_target_packet_handler); 291 292 293 // Configure SDP 294 295 // - Create and register A2DP Sink service record 296 memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer)); 297 a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, sdp_create_service_record_handle(), 298 AVDTP_SINK_FEATURE_MASK_HEADPHONE, NULL, NULL); 299 sdp_register_service(sdp_avdtp_sink_service_buffer); 300 301 // - Create AVRCP Controller service record and register it with SDP. We send Category 1 commands to the media player, e.g. play/pause 302 memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer)); 303 uint16_t controller_supported_features = 1 << AVRCP_CONTROLLER_SUPPORTED_FEATURE_CATEGORY_PLAYER_OR_RECORDER; 304 #ifdef AVRCP_BROWSING_ENABLED 305 controller_supported_features |= 1 << AVRCP_CONTROLLER_SUPPORTED_FEATURE_BROWSING; 306 #endif 307 #ifdef ENABLE_AVRCP_COVER_ART 308 controller_supported_features |= 1 << AVRCP_CONTROLLER_SUPPORTED_FEATURE_COVER_ART_GET_LINKED_THUMBNAIL; 309 #endif 310 avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, sdp_create_service_record_handle(), 311 controller_supported_features, NULL, NULL); 312 sdp_register_service(sdp_avrcp_controller_service_buffer); 313 314 // - Create and register A2DP Sink service record 315 // - We receive Category 2 commands from the media player, e.g. volume up/down 316 memset(sdp_avrcp_target_service_buffer, 0, sizeof(sdp_avrcp_target_service_buffer)); 317 uint16_t target_supported_features = 1 << AVRCP_TARGET_SUPPORTED_FEATURE_CATEGORY_MONITOR_OR_AMPLIFIER; 318 avrcp_target_create_sdp_record(sdp_avrcp_target_service_buffer, 319 sdp_create_service_record_handle(), target_supported_features, NULL, NULL); 320 sdp_register_service(sdp_avrcp_target_service_buffer); 321 322 // - Create and register Device ID (PnP) service record 323 memset(device_id_sdp_service_buffer, 0, sizeof(device_id_sdp_service_buffer)); 324 device_id_create_sdp_record(device_id_sdp_service_buffer, 325 sdp_create_service_record_handle(), DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1); 326 sdp_register_service(device_id_sdp_service_buffer); 327 328 329 // Configure GAP - discovery / connection 330 331 // - Set local name with a template Bluetooth address, that will be automatically 332 // replaced with an actual address once it is available, i.e. when BTstack boots 333 // up and starts talking to a Bluetooth module. 334 gap_set_local_name("A2DP Sink Demo 00:00:00:00:00:00"); 335 336 // - Allow to show up in Bluetooth inquiry 337 gap_discoverable_control(1); 338 339 // - Set Class of Device - Service Class: Audio, Major Device Class: Audio, Minor: Loudspeaker 340 gap_set_class_of_device(0x200414); 341 342 // - Allow for role switch in general and sniff mode 343 gap_set_default_link_policy_settings( LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE ); 344 345 // - Allow for role switch on outgoing connections 346 // - This allows A2DP Source, e.g. smartphone, to become master when we re-connect to it. 347 gap_set_allow_role_switch(true); 348 349 350 // Register for HCI events 351 hci_event_callback_registration.callback = &hci_packet_handler; 352 hci_add_event_handler(&hci_event_callback_registration); 353 354 // Inform about audio playback / test options 355 #ifdef HAVE_POSIX_FILE_IO 356 if (!btstack_audio_sink_get_instance()){ 357 printf("No audio playback.\n"); 358 } else { 359 printf("Audio playback supported.\n"); 360 } 361 #ifdef STORE_TO_WAV_FILE 362 printf("Audio will be stored to \'%s\' file.\n", wav_filename); 363 #endif 364 #endif 365 return 0; 366 } 367 /* LISTING_END */ 368 369 370 static void playback_handler(int16_t * buffer, uint16_t num_audio_frames){ 371 372 #ifdef STORE_TO_WAV_FILE 373 int wav_samples = num_audio_frames * NUM_CHANNELS; 374 int16_t * wav_buffer = buffer; 375 #endif 376 377 // called from lower-layer but guaranteed to be on main thread 378 if (sbc_frame_size == 0){ 379 memset(buffer, 0, num_audio_frames * BYTES_PER_FRAME); 380 return; 381 } 382 383 // first fill from resampled audio 384 uint32_t bytes_read; 385 btstack_ring_buffer_read(&decoded_audio_ring_buffer, (uint8_t *) buffer, num_audio_frames * BYTES_PER_FRAME, &bytes_read); 386 buffer += bytes_read / NUM_CHANNELS; 387 num_audio_frames -= bytes_read / BYTES_PER_FRAME; 388 389 // then start decoding sbc frames using request_* globals 390 request_buffer = buffer; 391 request_frames = num_audio_frames; 392 while (request_frames && btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) >= sbc_frame_size){ 393 // decode frame 394 uint8_t sbc_frame[MAX_SBC_FRAME_SIZE]; 395 btstack_ring_buffer_read(&sbc_frame_ring_buffer, sbc_frame, sbc_frame_size, &bytes_read); 396 btstack_sbc_decoder_process_data(&state, 0, sbc_frame, sbc_frame_size); 397 } 398 399 #ifdef STORE_TO_WAV_FILE 400 audio_frame_count += num_audio_frames; 401 wav_writer_write_int16(wav_samples, wav_buffer); 402 #endif 403 } 404 405 static void handle_pcm_data(int16_t * data, int num_audio_frames, int num_channels, int sample_rate, void * context){ 406 UNUSED(sample_rate); 407 UNUSED(context); 408 UNUSED(num_channels); // must be stereo == 2 409 410 const btstack_audio_sink_t * audio_sink = btstack_audio_sink_get_instance(); 411 if (!audio_sink){ 412 #ifdef STORE_TO_WAV_FILE 413 audio_frame_count += num_audio_frames; 414 wav_writer_write_int16(num_audio_frames * NUM_CHANNELS, data); 415 #endif 416 return; 417 } 418 419 // resample into request buffer - add some additional space for resampling 420 int16_t output_buffer[(128+16) * NUM_CHANNELS]; // 16 * 8 * 2 421 uint32_t resampled_frames = btstack_resample_block(&resample_instance, data, num_audio_frames, output_buffer); 422 423 // store data in btstack_audio buffer first 424 int frames_to_copy = btstack_min(resampled_frames, request_frames); 425 memcpy(request_buffer, output_buffer, frames_to_copy * BYTES_PER_FRAME); 426 request_frames -= frames_to_copy; 427 request_buffer += frames_to_copy * NUM_CHANNELS; 428 429 // and rest in ring buffer 430 int frames_to_store = resampled_frames - frames_to_copy; 431 if (frames_to_store){ 432 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); 433 if (status){ 434 printf("Error storing samples in PCM ring buffer!!!\n"); 435 } 436 } 437 } 438 439 static int media_processing_init(media_codec_configuration_sbc_t * configuration){ 440 if (media_initialized) return 0; 441 btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL); 442 443 #ifdef STORE_TO_WAV_FILE 444 wav_writer_open(wav_filename, configuration->num_channels, configuration->sampling_frequency); 445 #endif 446 447 btstack_ring_buffer_init(&sbc_frame_ring_buffer, sbc_frame_storage, sizeof(sbc_frame_storage)); 448 btstack_ring_buffer_init(&decoded_audio_ring_buffer, decoded_audio_storage, sizeof(decoded_audio_storage)); 449 btstack_resample_init(&resample_instance, configuration->num_channels); 450 451 // setup audio playback 452 const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance(); 453 if (audio){ 454 audio->init(NUM_CHANNELS, configuration->sampling_frequency, &playback_handler); 455 } 456 457 audio_stream_started = 0; 458 media_initialized = 1; 459 return 0; 460 } 461 462 static void media_processing_start(void){ 463 if (!media_initialized) return; 464 465 #ifdef HAVE_BTSTACK_AUDIO_EFFECTIVE_SAMPLERATE 466 btstack_sample_rate_compensation_reset( &sample_rate_compensation, btstack_run_loop_get_time_ms() ); 467 #endif 468 // setup audio playback 469 const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance(); 470 if (audio){ 471 audio->start_stream(); 472 } 473 audio_stream_started = 1; 474 } 475 476 static void media_processing_pause(void){ 477 if (!media_initialized) return; 478 479 // stop audio playback 480 audio_stream_started = 0; 481 #ifdef HAVE_BTSTACK_AUDIO_EFFECTIVE_SAMPLERATE 482 l2cap_stream_started = 0; 483 #endif 484 485 const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance(); 486 if (audio){ 487 audio->stop_stream(); 488 } 489 // discard pending data 490 btstack_ring_buffer_reset(&decoded_audio_ring_buffer); 491 btstack_ring_buffer_reset(&sbc_frame_ring_buffer); 492 } 493 494 static void media_processing_close(void){ 495 if (!media_initialized) return; 496 497 media_initialized = 0; 498 audio_stream_started = 0; 499 sbc_frame_size = 0; 500 #ifdef HAVE_BTSTACK_AUDIO_EFFECTIVE_SAMPLERATE 501 l2cap_stream_started = 0; 502 #endif 503 504 #ifdef STORE_TO_WAV_FILE 505 wav_writer_close(); 506 uint32_t total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr; 507 508 printf("WAV Writer: Decoding done. Processed %u SBC frames:\n - %d good\n - %d bad\n", total_frames_nr, state.good_frames_nr, total_frames_nr - state.good_frames_nr); 509 printf("WAV Writer: Wrote %u audio frames to wav file: %s\n", audio_frame_count, wav_filename); 510 #endif 511 512 // stop audio playback 513 const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance(); 514 if (audio){ 515 printf("close stream\n"); 516 audio->close(); 517 } 518 } 519 520 /* @section Handle Media Data Packet 521 * 522 * @text Here the audio data, are received through the handle_l2cap_media_data_packet callback. 523 * Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet. 524 * 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). 525 * If the audio stream wasn't started already and there are enough SBC frames in the ring buffer, start playback. 526 */ 527 528 static int read_media_data_header(uint8_t * packet, int size, int * offset, avdtp_media_packet_header_t * media_header); 529 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header); 530 531 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size){ 532 UNUSED(seid); 533 int pos = 0; 534 535 avdtp_media_packet_header_t media_header; 536 if (!read_media_data_header(packet, size, &pos, &media_header)) return; 537 538 avdtp_sbc_codec_header_t sbc_header; 539 if (!read_sbc_header(packet, size, &pos, &sbc_header)) return; 540 541 int packet_length = size-pos; 542 uint8_t *packet_begin = packet+pos; 543 544 const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance(); 545 // process data right away if there's no audio implementation active, e.g. on posix systems to store as .wav 546 if (!audio){ 547 btstack_sbc_decoder_process_data(&state, 0, packet_begin, packet_length); 548 return; 549 } 550 551 552 // store sbc frame size for buffer management 553 sbc_frame_size = packet_length / sbc_header.num_frames; 554 int status = btstack_ring_buffer_write(&sbc_frame_ring_buffer, packet_begin, packet_length); 555 if (status != ERROR_CODE_SUCCESS){ 556 printf("Error storing samples in SBC ring buffer!!!\n"); 557 } 558 559 // decide on audio sync drift based on number of sbc frames in queue 560 int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) / sbc_frame_size; 561 #ifdef HAVE_BTSTACK_AUDIO_EFFECTIVE_SAMPLERATE 562 if( !l2cap_stream_started && audio_stream_started ) { 563 l2cap_stream_started = 1; 564 btstack_sample_rate_compensation_init( &sample_rate_compensation, btstack_run_loop_get_time_ms(), a2dp_sink_demo_a2dp_connection.sbc_configuration.sampling_frequency, FLOAT_TO_Q15(1.f) ); 565 } 566 // update sample rate compensation 567 if( audio_stream_started && (audio != NULL)) { 568 uint32_t resampling_factor = btstack_sample_rate_compensation_update( &sample_rate_compensation, btstack_run_loop_get_time_ms(), sbc_header.num_frames*128, audio->get_samplerate() ); 569 btstack_resample_set_factor(&resample_instance, resampling_factor); 570 // printf("sbc buffer level : %"PRIu32"\n", btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer)); 571 } 572 #else 573 uint32_t resampling_factor; 574 575 // nominal factor (fixed-point 2^16) and compensation offset 576 uint32_t nominal_factor = 0x10000; 577 uint32_t compensation = 0x00100; 578 579 if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){ 580 resampling_factor = nominal_factor - compensation; // stretch samples 581 } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){ 582 resampling_factor = nominal_factor; // nothing to do 583 } else { 584 resampling_factor = nominal_factor + compensation; // compress samples 585 } 586 587 btstack_resample_set_factor(&resample_instance, resampling_factor); 588 #endif 589 // start stream if enough frames buffered 590 if (!audio_stream_started && sbc_frames_in_buffer >= OPTIMAL_FRAMES_MIN){ 591 media_processing_start(); 592 } 593 } 594 595 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header){ 596 int sbc_header_len = 12; // without crc 597 int pos = *offset; 598 599 if (size - pos < sbc_header_len){ 600 printf("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size-pos); 601 return 0; 602 } 603 604 sbc_header->fragmentation = get_bit16(packet[pos], 7); 605 sbc_header->starting_packet = get_bit16(packet[pos], 6); 606 sbc_header->last_packet = get_bit16(packet[pos], 5); 607 sbc_header->num_frames = packet[pos] & 0x0f; 608 pos++; 609 *offset = pos; 610 return 1; 611 } 612 613 static int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header){ 614 int media_header_len = 12; // without crc 615 int pos = *offset; 616 617 if (size - pos < media_header_len){ 618 printf("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size-pos); 619 return 0; 620 } 621 622 media_header->version = packet[pos] & 0x03; 623 media_header->padding = get_bit16(packet[pos],2); 624 media_header->extension = get_bit16(packet[pos],3); 625 media_header->csrc_count = (packet[pos] >> 4) & 0x0F; 626 pos++; 627 628 media_header->marker = get_bit16(packet[pos],0); 629 media_header->payload_type = (packet[pos] >> 1) & 0x7F; 630 pos++; 631 632 media_header->sequence_number = big_endian_read_16(packet, pos); 633 pos+=2; 634 635 media_header->timestamp = big_endian_read_32(packet, pos); 636 pos+=4; 637 638 media_header->synchronization_source = big_endian_read_32(packet, pos); 639 pos+=4; 640 *offset = pos; 641 return 1; 642 } 643 644 static void dump_sbc_configuration(media_codec_configuration_sbc_t * configuration){ 645 printf(" - num_channels: %d\n", configuration->num_channels); 646 printf(" - sampling_frequency: %d\n", configuration->sampling_frequency); 647 printf(" - channel_mode: %d\n", configuration->channel_mode); 648 printf(" - block_length: %d\n", configuration->block_length); 649 printf(" - subbands: %d\n", configuration->subbands); 650 printf(" - allocation_method: %d\n", configuration->allocation_method); 651 printf(" - bitpool_value [%d, %d] \n", configuration->min_bitpool_value, configuration->max_bitpool_value); 652 printf("\n"); 653 } 654 655 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 656 UNUSED(channel); 657 UNUSED(size); 658 if (packet_type != HCI_EVENT_PACKET) return; 659 if (hci_event_packet_get_type(packet) == HCI_EVENT_PIN_CODE_REQUEST) { 660 bd_addr_t address; 661 printf("Pin code request - using '0000'\n"); 662 hci_event_pin_code_request_get_bd_addr(packet, address); 663 gap_pin_code_response(address, "0000"); 664 } 665 } 666 667 #ifdef ENABLE_AVRCP_COVER_ART 668 static void a2dp_sink_demo_cover_art_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) { 669 UNUSED(channel); 670 UNUSED(size); 671 uint8_t status; 672 uint16_t cid; 673 switch (packet_type){ 674 case BIP_DATA_PACKET: 675 if (a2dp_sink_cover_art_download_active){ 676 a2dp_sink_cover_art_file_size += size; 677 #ifdef HAVE_POSIX_FILE_IO 678 fwrite(packet, 1, size, a2dp_sink_cover_art_file); 679 #else 680 printf("Cover art : TODO - store %u bytes image data\n", size); 681 #endif 682 } else { 683 uint16_t i; 684 for (i=0;i<size;i++){ 685 putchar(packet[i]); 686 } 687 printf("\n"); 688 } 689 break; 690 case HCI_EVENT_PACKET: 691 switch (hci_event_packet_get_type(packet)){ 692 case HCI_EVENT_AVRCP_META: 693 switch (hci_event_avrcp_meta_get_subevent_code(packet)){ 694 case AVRCP_SUBEVENT_COVER_ART_CONNECTION_ESTABLISHED: 695 status = avrcp_subevent_cover_art_connection_established_get_status(packet); 696 cid = avrcp_subevent_cover_art_connection_established_get_cover_art_cid(packet); 697 if (status == ERROR_CODE_SUCCESS){ 698 printf("Cover Art : connection established, cover art cid 0x%02x\n", cid); 699 a2dp_sink_demo_cover_art_client_connected = true; 700 } else { 701 printf("Cover Art : connection failed, status 0x%02x\n", status); 702 a2dp_sink_demo_cover_art_cid = 0; 703 } 704 break; 705 case AVRCP_SUBEVENT_COVER_ART_OPERATION_COMPLETE: 706 if (a2dp_sink_cover_art_download_active){ 707 a2dp_sink_cover_art_download_active = false; 708 #ifdef HAVE_POSIX_FILE_IO 709 printf("Cover Art : download of '%s complete, size %u bytes'\n", 710 a2dp_sink_demo_thumbnail_path, a2dp_sink_cover_art_file_size); 711 fclose(a2dp_sink_cover_art_file); 712 a2dp_sink_cover_art_file = NULL; 713 #else 714 printf("Cover Art: download completed\n"); 715 #endif 716 } 717 break; 718 case AVRCP_SUBEVENT_COVER_ART_CONNECTION_RELEASED: 719 a2dp_sink_demo_cover_art_client_connected = false; 720 a2dp_sink_demo_cover_art_cid = 0; 721 printf("Cover Art : connection released 0x%02x\n", 722 avrcp_subevent_cover_art_connection_released_get_cover_art_cid(packet)); 723 break; 724 default: 725 break; 726 } 727 break; 728 default: 729 break; 730 } 731 break; 732 default: 733 break; 734 } 735 } 736 737 static uint8_t a2dp_sink_demo_cover_art_connect(void) { 738 uint8_t status; 739 status = avrcp_cover_art_client_connect(&a2dp_sink_demo_cover_art_client, a2dp_sink_demo_cover_art_packet_handler, 740 device_addr, a2dp_sink_demo_ertm_buffer, 741 sizeof(a2dp_sink_demo_ertm_buffer), &a2dp_sink_demo_ertm_config, 742 &a2dp_sink_demo_cover_art_cid); 743 return status; 744 } 745 #endif 746 747 static void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 748 UNUSED(channel); 749 UNUSED(size); 750 uint16_t local_cid; 751 uint8_t status; 752 bd_addr_t address; 753 754 a2dp_sink_demo_avrcp_connection_t * connection = &a2dp_sink_demo_avrcp_connection; 755 756 if (packet_type != HCI_EVENT_PACKET) return; 757 if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return; 758 switch (packet[2]){ 759 case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: { 760 local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet); 761 status = avrcp_subevent_connection_established_get_status(packet); 762 if (status != ERROR_CODE_SUCCESS){ 763 printf("AVRCP: Connection failed, status 0x%02x\n", status); 764 connection->avrcp_cid = 0; 765 return; 766 } 767 768 connection->avrcp_cid = local_cid; 769 avrcp_subevent_connection_established_get_bd_addr(packet, address); 770 printf("AVRCP: Connected to %s, cid 0x%02x\n", bd_addr_to_str(address), connection->avrcp_cid); 771 772 #ifdef HAVE_BTSTACK_STDIN 773 // use address for outgoing connections 774 avrcp_subevent_connection_established_get_bd_addr(packet, device_addr); 775 #endif 776 777 avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED); 778 avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_BATT_STATUS_CHANGED); 779 avrcp_target_battery_status_changed(connection->avrcp_cid, battery_status); 780 781 // query supported events: 782 avrcp_controller_get_supported_events(connection->avrcp_cid); 783 return; 784 } 785 786 case AVRCP_SUBEVENT_CONNECTION_RELEASED: 787 printf("AVRCP: Channel released: cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet)); 788 connection->avrcp_cid = 0; 789 connection->notifications_supported_by_target = 0; 790 return; 791 default: 792 break; 793 } 794 } 795 796 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 797 UNUSED(channel); 798 UNUSED(size); 799 800 // helper to print c strings 801 uint8_t avrcp_subevent_value[256]; 802 uint8_t play_status; 803 uint8_t event_id; 804 805 a2dp_sink_demo_avrcp_connection_t * avrcp_connection = &a2dp_sink_demo_avrcp_connection; 806 807 if (packet_type != HCI_EVENT_PACKET) return; 808 if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return; 809 if (avrcp_connection->avrcp_cid == 0) return; 810 811 memset(avrcp_subevent_value, 0, sizeof(avrcp_subevent_value)); 812 switch (packet[2]){ 813 case AVRCP_SUBEVENT_GET_CAPABILITY_EVENT_ID: 814 avrcp_connection->notifications_supported_by_target |= (1 << avrcp_subevent_get_capability_event_id_get_event_id(packet)); 815 break; 816 case AVRCP_SUBEVENT_GET_CAPABILITY_EVENT_ID_DONE: 817 818 printf("AVRCP Controller: supported notifications by target:\n"); 819 for (event_id = (uint8_t) AVRCP_NOTIFICATION_EVENT_FIRST_INDEX; event_id < (uint8_t) AVRCP_NOTIFICATION_EVENT_LAST_INDEX; event_id++){ 820 printf(" - [%s] %s\n", 821 (avrcp_connection->notifications_supported_by_target & (1 << event_id)) != 0 ? "X" : " ", 822 avrcp_notification2str((avrcp_notification_event_id_t)event_id)); 823 } 824 printf("\n\n"); 825 826 // automatically enable notifications 827 avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED); 828 avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED); 829 avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED); 830 831 #ifdef ENABLE_AVRCP_COVER_ART 832 // image handles become invalid on player change, registe for notifications 833 avrcp_controller_enable_notification(a2dp_sink_demo_avrcp_connection.avrcp_cid, AVRCP_NOTIFICATION_EVENT_UIDS_CHANGED); 834 // trigger cover art client connection 835 a2dp_sink_demo_cover_art_connect(); 836 #endif 837 break; 838 839 case AVRCP_SUBEVENT_NOTIFICATION_STATE: 840 event_id = (avrcp_notification_event_id_t)avrcp_subevent_notification_state_get_event_id(packet); 841 printf("AVRCP Controller: %s notification registered\n", avrcp_notification2str(event_id)); 842 break; 843 844 case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED: 845 printf("AVRCP Controller: Playback position changed, position %d ms\n", (unsigned int) avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet)); 846 break; 847 case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED: 848 printf("AVRCP Controller: Playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet))); 849 play_status = avrcp_subevent_notification_playback_status_changed_get_play_status(packet); 850 switch (play_status){ 851 case AVRCP_PLAYBACK_STATUS_PLAYING: 852 avrcp_connection->playing = true; 853 break; 854 default: 855 avrcp_connection->playing = false; 856 break; 857 } 858 break; 859 860 case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED: 861 printf("AVRCP Controller: Playing content changed\n"); 862 break; 863 864 case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED: 865 printf("AVRCP Controller: Track changed\n"); 866 break; 867 868 case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED: 869 printf("AVRCP Controller: Available Players Changed\n"); 870 break; 871 872 case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{ 873 uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet); 874 uint8_t repeat_mode = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet); 875 printf("AVRCP Controller: %s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode)); 876 break; 877 } 878 case AVRCP_SUBEVENT_NOW_PLAYING_TRACK_INFO: 879 printf("AVRCP Controller: Track %d\n", avrcp_subevent_now_playing_track_info_get_track(packet)); 880 break; 881 882 case AVRCP_SUBEVENT_NOW_PLAYING_TOTAL_TRACKS_INFO: 883 printf("AVRCP Controller: Total Tracks %d\n", avrcp_subevent_now_playing_total_tracks_info_get_total_tracks(packet)); 884 break; 885 886 case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO: 887 if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0){ 888 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet)); 889 printf("AVRCP Controller: Title %s\n", avrcp_subevent_value); 890 } 891 break; 892 893 case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO: 894 if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0){ 895 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet)); 896 printf("AVRCP Controller: Artist %s\n", avrcp_subevent_value); 897 } 898 break; 899 900 case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO: 901 if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0){ 902 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet)); 903 printf("AVRCP Controller: Album %s\n", avrcp_subevent_value); 904 } 905 break; 906 907 case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO: 908 if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0){ 909 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet)); 910 printf("AVRCP Controller: Genre %s\n", avrcp_subevent_value); 911 } 912 break; 913 914 case AVRCP_SUBEVENT_PLAY_STATUS: 915 printf("AVRCP Controller: Song length %"PRIu32" ms, Song position %"PRIu32" ms, Play status %s\n", 916 avrcp_subevent_play_status_get_song_length(packet), 917 avrcp_subevent_play_status_get_song_position(packet), 918 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet))); 919 break; 920 921 case AVRCP_SUBEVENT_OPERATION_COMPLETE: 922 printf("AVRCP Controller: %s complete\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet))); 923 break; 924 925 case AVRCP_SUBEVENT_OPERATION_START: 926 printf("AVRCP Controller: %s start\n", avrcp_operation2str(avrcp_subevent_operation_start_get_operation_id(packet))); 927 break; 928 929 case AVRCP_SUBEVENT_NOTIFICATION_EVENT_TRACK_REACHED_END: 930 printf("AVRCP Controller: Track reached end\n"); 931 break; 932 933 case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE: 934 printf("AVRCP Controller: Set Player App Value %s\n", avrcp_ctype2str(avrcp_subevent_player_application_value_response_get_command_type(packet))); 935 break; 936 937 #ifdef ENABLE_AVRCP_COVER_ART 938 case AVRCP_SUBEVENT_NOTIFICATION_EVENT_UIDS_CHANGED: 939 if (a2dp_sink_demo_cover_art_client_connected){ 940 printf("AVRCP Controller: UIDs changed -> disconnect cover art client\n"); 941 avrcp_cover_art_client_disconnect(a2dp_sink_demo_cover_art_cid); 942 } 943 break; 944 945 case AVRCP_SUBEVENT_NOW_PLAYING_COVER_ART_INFO: 946 if (avrcp_subevent_now_playing_cover_art_info_get_value_len(packet) == 7){ 947 memcpy(a2dp_sink_demo_image_handle, avrcp_subevent_now_playing_cover_art_info_get_value(packet), 7); 948 printf("AVRCP Controller: Cover Art %s\n", a2dp_sink_demo_image_handle); 949 } 950 break; 951 #endif 952 953 default: 954 break; 955 } 956 } 957 958 static void avrcp_volume_changed(uint8_t volume){ 959 const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance(); 960 if (audio){ 961 audio->set_volume(volume); 962 } 963 } 964 965 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 966 UNUSED(channel); 967 UNUSED(size); 968 969 if (packet_type != HCI_EVENT_PACKET) return; 970 if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return; 971 972 uint8_t volume; 973 char const * button_state; 974 avrcp_operation_id_t operation_id; 975 976 switch (packet[2]){ 977 case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED: 978 volume = avrcp_subevent_notification_volume_changed_get_absolute_volume(packet); 979 volume_percentage = volume * 100 / 127; 980 printf("AVRCP Target : Volume set to %d%% (%d)\n", volume_percentage, volume); 981 avrcp_volume_changed(volume); 982 break; 983 984 case AVRCP_SUBEVENT_OPERATION: 985 operation_id = avrcp_subevent_operation_get_operation_id(packet); 986 button_state = avrcp_subevent_operation_get_button_pressed(packet) > 0 ? "PRESS" : "RELEASE"; 987 switch (operation_id){ 988 case AVRCP_OPERATION_ID_VOLUME_UP: 989 printf("AVRCP Target : VOLUME UP (%s)\n", button_state); 990 break; 991 case AVRCP_OPERATION_ID_VOLUME_DOWN: 992 printf("AVRCP Target : VOLUME DOWN (%s)\n", button_state); 993 break; 994 default: 995 return; 996 } 997 break; 998 default: 999 printf("AVRCP Target : Event 0x%02x is not parsed\n", packet[2]); 1000 break; 1001 } 1002 } 1003 1004 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1005 UNUSED(channel); 1006 UNUSED(size); 1007 uint8_t status; 1008 1009 uint8_t allocation_method; 1010 1011 if (packet_type != HCI_EVENT_PACKET) return; 1012 if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return; 1013 1014 a2dp_sink_demo_a2dp_connection_t * a2dp_conn = &a2dp_sink_demo_a2dp_connection; 1015 1016 switch (packet[2]){ 1017 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION: 1018 printf("A2DP Sink : Received non SBC codec - not implemented\n"); 1019 break; 1020 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{ 1021 printf("A2DP Sink : Received SBC codec configuration\n"); 1022 a2dp_conn->sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet); 1023 a2dp_conn->sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet); 1024 a2dp_conn->sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet); 1025 a2dp_conn->sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet); 1026 a2dp_conn->sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet); 1027 a2dp_conn->sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet); 1028 a2dp_conn->sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet); 1029 1030 allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet); 1031 1032 // Adapt Bluetooth spec definition to SBC Encoder expected input 1033 a2dp_conn->sbc_configuration.allocation_method = (btstack_sbc_allocation_method_t)(allocation_method - 1); 1034 1035 switch (a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet)){ 1036 case AVDTP_CHANNEL_MODE_JOINT_STEREO: 1037 a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO; 1038 break; 1039 case AVDTP_CHANNEL_MODE_STEREO: 1040 a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_STEREO; 1041 break; 1042 case AVDTP_CHANNEL_MODE_DUAL_CHANNEL: 1043 a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL; 1044 break; 1045 case AVDTP_CHANNEL_MODE_MONO: 1046 a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_MONO; 1047 break; 1048 default: 1049 btstack_assert(false); 1050 break; 1051 } 1052 dump_sbc_configuration(&a2dp_conn->sbc_configuration); 1053 break; 1054 } 1055 1056 case A2DP_SUBEVENT_STREAM_ESTABLISHED: 1057 status = a2dp_subevent_stream_established_get_status(packet); 1058 if (status != ERROR_CODE_SUCCESS){ 1059 printf("A2DP Sink : Streaming connection failed, status 0x%02x\n", status); 1060 break; 1061 } 1062 1063 a2dp_subevent_stream_established_get_bd_addr(packet, a2dp_conn->addr); 1064 a2dp_conn->a2dp_cid = a2dp_subevent_stream_established_get_a2dp_cid(packet); 1065 a2dp_conn->stream_state = STREAM_STATE_OPEN; 1066 1067 printf("A2DP Sink : Streaming connection is established, address %s, cid 0x%02x, local seid %d\n", 1068 bd_addr_to_str(a2dp_conn->addr), a2dp_conn->a2dp_cid, a2dp_conn->a2dp_local_seid); 1069 #ifdef HAVE_BTSTACK_STDIN 1070 // use address for outgoing connections 1071 memcpy(device_addr, a2dp_conn->addr, 6); 1072 #endif 1073 break; 1074 1075 #ifdef ENABLE_AVDTP_ACCEPTOR_EXPLICIT_START_STREAM_CONFIRMATION 1076 case A2DP_SUBEVENT_START_STREAM_REQUESTED: 1077 printf("A2DP Sink : Explicit Accept to start stream, local_seid %d\n", a2dp_subevent_start_stream_requested_get_local_seid(packet)); 1078 a2dp_sink_start_stream_accept(a2dp_cid, a2dp_local_seid); 1079 break; 1080 #endif 1081 case A2DP_SUBEVENT_STREAM_STARTED: 1082 printf("A2DP Sink : Stream started\n"); 1083 a2dp_conn->stream_state = STREAM_STATE_PLAYING; 1084 if (a2dp_conn->sbc_configuration.reconfigure){ 1085 media_processing_close(); 1086 } 1087 // prepare media processing 1088 media_processing_init(&a2dp_conn->sbc_configuration); 1089 // audio stream is started when buffer reaches minimal level 1090 break; 1091 1092 case A2DP_SUBEVENT_STREAM_SUSPENDED: 1093 printf("A2DP Sink : Stream paused\n"); 1094 a2dp_conn->stream_state = STREAM_STATE_PAUSED; 1095 media_processing_pause(); 1096 break; 1097 1098 case A2DP_SUBEVENT_STREAM_RELEASED: 1099 printf("A2DP Sink : Stream released\n"); 1100 a2dp_conn->stream_state = STREAM_STATE_CLOSED; 1101 media_processing_close(); 1102 break; 1103 1104 case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED: 1105 printf("A2DP Sink : Signaling connection released\n"); 1106 a2dp_conn->a2dp_cid = 0; 1107 media_processing_close(); 1108 break; 1109 1110 default: 1111 break; 1112 } 1113 } 1114 1115 #ifdef HAVE_BTSTACK_STDIN 1116 static void show_usage(void){ 1117 bd_addr_t iut_address; 1118 gap_local_bd_addr(iut_address); 1119 printf("\n--- A2DP Sink Demo Console %s ---\n", bd_addr_to_str(iut_address)); 1120 printf("b - A2DP Sink create connection to addr %s\n", bd_addr_to_str(device_addr)); 1121 printf("B - A2DP Sink disconnect\n"); 1122 1123 printf("\n--- AVRCP Controller ---\n"); 1124 printf("c - AVRCP create connection to addr %s\n", bd_addr_to_str(device_addr)); 1125 printf("C - AVRCP disconnect\n"); 1126 printf("O - get play status\n"); 1127 printf("j - get now playing info\n"); 1128 printf("k - play\n"); 1129 printf("K - stop\n"); 1130 printf("L - pause\n"); 1131 printf("u - start fast forward\n"); 1132 printf("U - stop fast forward\n"); 1133 printf("n - start rewind\n"); 1134 printf("N - stop rewind\n"); 1135 printf("i - forward\n"); 1136 printf("I - backward\n"); 1137 printf("M - mute\n"); 1138 printf("r - skip\n"); 1139 printf("q - query repeat and shuffle mode\n"); 1140 printf("v - repeat single track\n"); 1141 printf("w - delay report\n"); 1142 printf("x - repeat all tracks\n"); 1143 printf("X - disable repeat mode\n"); 1144 printf("z - shuffle all tracks\n"); 1145 printf("Z - disable shuffle mode\n"); 1146 1147 printf("a/A - register/deregister TRACK_CHANGED\n"); 1148 printf("R/P - register/deregister PLAYBACK_POS_CHANGED\n"); 1149 1150 printf("s/S - send/release long button press REWIND\n"); 1151 1152 printf("\n--- Volume and Battery Control ---\n"); 1153 printf("t - volume up for 10 percent\n"); 1154 printf("T - volume down for 10 percent\n"); 1155 printf("V - toggle Battery status from AVRCP_BATTERY_STATUS_NORMAL to AVRCP_BATTERY_STATUS_FULL_CHARGE\n"); 1156 1157 #ifdef ENABLE_AVRCP_COVER_ART 1158 printf("\n--- Cover Art Client ---\n"); 1159 printf("d - connect to addr %s\n", bd_addr_to_str(device_addr)); 1160 printf("D - disconnect\n"); 1161 if (a2dp_sink_demo_cover_art_client_connected == false){ 1162 if (a2dp_sink_demo_avrcp_connection.avrcp_cid == 0){ 1163 printf("Not connected, press 'b' or 'c' to first connect AVRCP, then press 'd' to connect cover art client\n"); 1164 } else { 1165 printf("Not connected, press 'd' to connect cover art client\n"); 1166 } 1167 } else if (a2dp_sink_demo_image_handle[0] == 0){ 1168 printf("No image handle, use 'j' to get current track info\n"); 1169 } 1170 printf("---\n"); 1171 #endif 1172 1173 } 1174 #endif 1175 1176 #ifdef HAVE_BTSTACK_STDIN 1177 1178 static void stdin_process(char cmd){ 1179 uint8_t status = ERROR_CODE_SUCCESS; 1180 uint8_t volume; 1181 avrcp_battery_status_t old_battery_status; 1182 1183 a2dp_sink_demo_stream_endpoint_t * stream_endpoint = &a2dp_sink_demo_stream_endpoint; 1184 a2dp_sink_demo_a2dp_connection_t * a2dp_connection = &a2dp_sink_demo_a2dp_connection; 1185 a2dp_sink_demo_avrcp_connection_t * avrcp_connection = &a2dp_sink_demo_avrcp_connection; 1186 1187 switch (cmd){ 1188 case 'b': 1189 status = a2dp_sink_establish_stream(device_addr, stream_endpoint->a2dp_local_seid, &a2dp_connection->a2dp_cid); 1190 printf(" - Create AVDTP connection to addr %s, and local seid %d, cid 0x%02x.\n", 1191 bd_addr_to_str(device_addr), a2dp_connection->a2dp_local_seid, a2dp_connection->a2dp_cid); 1192 break; 1193 case 'B': 1194 printf(" - AVDTP disconnect from addr %s.\n", bd_addr_to_str(device_addr)); 1195 a2dp_sink_disconnect(a2dp_connection->a2dp_cid); 1196 break; 1197 case 'c': 1198 printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr)); 1199 status = avrcp_connect(device_addr, &avrcp_connection->avrcp_cid); 1200 break; 1201 case 'C': 1202 printf(" - AVRCP disconnect from addr %s.\n", bd_addr_to_str(device_addr)); 1203 status = avrcp_disconnect(avrcp_connection->avrcp_cid); 1204 break; 1205 1206 case '\n': 1207 case '\r': 1208 break; 1209 case 'w': 1210 printf("Send delay report\n"); 1211 avdtp_sink_delay_report(a2dp_connection->a2dp_cid, a2dp_connection->a2dp_local_seid, 100); 1212 break; 1213 // Volume Control 1214 case 't': 1215 volume_percentage = volume_percentage <= 90 ? volume_percentage + 10 : 100; 1216 volume = volume_percentage * 127 / 100; 1217 printf(" - volume up for 10 percent, %d%% (%d) \n", volume_percentage, volume); 1218 status = avrcp_target_volume_changed(avrcp_connection->avrcp_cid, volume); 1219 avrcp_volume_changed(volume); 1220 break; 1221 case 'T': 1222 volume_percentage = volume_percentage >= 10 ? volume_percentage - 10 : 0; 1223 volume = volume_percentage * 127 / 100; 1224 printf(" - volume down for 10 percent, %d%% (%d) \n", volume_percentage, volume); 1225 status = avrcp_target_volume_changed(avrcp_connection->avrcp_cid, volume); 1226 avrcp_volume_changed(volume); 1227 break; 1228 case 'V': 1229 old_battery_status = battery_status; 1230 1231 if (battery_status < AVRCP_BATTERY_STATUS_FULL_CHARGE){ 1232 battery_status = (avrcp_battery_status_t)((uint8_t) battery_status + 1); 1233 } else { 1234 battery_status = AVRCP_BATTERY_STATUS_NORMAL; 1235 } 1236 printf(" - toggle battery value, old %d, new %d\n", old_battery_status, battery_status); 1237 status = avrcp_target_battery_status_changed(avrcp_connection->avrcp_cid, battery_status); 1238 break; 1239 case 'O': 1240 printf(" - get play status\n"); 1241 status = avrcp_controller_get_play_status(avrcp_connection->avrcp_cid); 1242 break; 1243 case 'j': 1244 printf(" - get now playing info\n"); 1245 status = avrcp_controller_get_now_playing_info(avrcp_connection->avrcp_cid); 1246 break; 1247 case 'k': 1248 printf(" - play\n"); 1249 status = avrcp_controller_play(avrcp_connection->avrcp_cid); 1250 break; 1251 case 'K': 1252 printf(" - stop\n"); 1253 status = avrcp_controller_stop(avrcp_connection->avrcp_cid); 1254 break; 1255 case 'L': 1256 printf(" - pause\n"); 1257 status = avrcp_controller_pause(avrcp_connection->avrcp_cid); 1258 break; 1259 case 'u': 1260 printf(" - start fast forward\n"); 1261 status = avrcp_controller_press_and_hold_fast_forward(avrcp_connection->avrcp_cid); 1262 break; 1263 case 'U': 1264 printf(" - stop fast forward\n"); 1265 status = avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid); 1266 break; 1267 case 'n': 1268 printf(" - start rewind\n"); 1269 status = avrcp_controller_press_and_hold_rewind(avrcp_connection->avrcp_cid); 1270 break; 1271 case 'N': 1272 printf(" - stop rewind\n"); 1273 status = avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid); 1274 break; 1275 case 'i': 1276 printf(" - forward\n"); 1277 status = avrcp_controller_forward(avrcp_connection->avrcp_cid); 1278 break; 1279 case 'I': 1280 printf(" - backward\n"); 1281 status = avrcp_controller_backward(avrcp_connection->avrcp_cid); 1282 break; 1283 case 'M': 1284 printf(" - mute\n"); 1285 status = avrcp_controller_mute(avrcp_connection->avrcp_cid); 1286 break; 1287 case 'r': 1288 printf(" - skip\n"); 1289 status = avrcp_controller_skip(avrcp_connection->avrcp_cid); 1290 break; 1291 case 'q': 1292 printf(" - query repeat and shuffle mode\n"); 1293 status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_connection->avrcp_cid); 1294 break; 1295 case 'v': 1296 printf(" - repeat single track\n"); 1297 status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK); 1298 break; 1299 case 'x': 1300 printf(" - repeat all tracks\n"); 1301 status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS); 1302 break; 1303 case 'X': 1304 printf(" - disable repeat mode\n"); 1305 status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_OFF); 1306 break; 1307 case 'z': 1308 printf(" - shuffle all tracks\n"); 1309 status = avrcp_controller_set_shuffle_mode(avrcp_connection->avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS); 1310 break; 1311 case 'Z': 1312 printf(" - disable shuffle mode\n"); 1313 status = avrcp_controller_set_shuffle_mode(avrcp_connection->avrcp_cid, AVRCP_SHUFFLE_MODE_OFF); 1314 break; 1315 case 'a': 1316 printf("AVRCP: enable notification TRACK_CHANGED\n"); 1317 status = avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED); 1318 break; 1319 case 'A': 1320 printf("AVRCP: disable notification TRACK_CHANGED\n"); 1321 status = avrcp_controller_disable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED); 1322 break; 1323 case 'R': 1324 printf("AVRCP: enable notification PLAYBACK_POS_CHANGED\n"); 1325 status = avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED); 1326 break; 1327 case 'P': 1328 printf("AVRCP: disable notification PLAYBACK_POS_CHANGED\n"); 1329 status = avrcp_controller_disable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED); 1330 break; 1331 case 's': 1332 printf("AVRCP: send long button press REWIND\n"); 1333 status = avrcp_controller_start_press_and_hold_cmd(avrcp_connection->avrcp_cid, AVRCP_OPERATION_ID_REWIND); 1334 break; 1335 case 'S': 1336 printf("AVRCP: release long button press REWIND\n"); 1337 status = avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid); 1338 break; 1339 #ifdef ENABLE_AVRCP_COVER_ART 1340 case 'd': 1341 printf(" - Create AVRCP Cover Art connection to addr %s.\n", bd_addr_to_str(device_addr)); 1342 status = a2dp_sink_demo_cover_art_connect(); 1343 break; 1344 case 'D': 1345 printf(" - AVRCP Cover Art disconnect from addr %s.\n", bd_addr_to_str(device_addr)); 1346 status = avrcp_cover_art_client_disconnect(a2dp_sink_demo_cover_art_cid); 1347 break; 1348 case '@': 1349 printf("Get linked thumbnail for '%s'\n", a2dp_sink_demo_image_handle); 1350 #ifdef HAVE_POSIX_FILE_IO 1351 a2dp_sink_cover_art_file = fopen(a2dp_sink_demo_thumbnail_path, "w"); 1352 #endif 1353 a2dp_sink_cover_art_download_active = true; 1354 a2dp_sink_cover_art_file_size = 0; 1355 status = avrcp_cover_art_client_get_linked_thumbnail(a2dp_sink_demo_cover_art_cid, a2dp_sink_demo_image_handle); 1356 break; 1357 #endif 1358 default: 1359 show_usage(); 1360 return; 1361 } 1362 if (status != ERROR_CODE_SUCCESS){ 1363 printf("Could not perform command, status 0x%02x\n", status); 1364 } 1365 } 1366 #endif 1367 1368 int btstack_main(int argc, const char * argv[]); 1369 int btstack_main(int argc, const char * argv[]){ 1370 UNUSED(argc); 1371 (void)argv; 1372 1373 setup_demo(); 1374 1375 #ifdef HAVE_BTSTACK_STDIN 1376 // parse human-readable Bluetooth address 1377 sscanf_bd_addr(device_addr_string, device_addr); 1378 btstack_stdin_setup(stdin_process); 1379 #endif 1380 1381 // turn on! 1382 printf("Starting BTstack ...\n"); 1383 hci_power_control(HCI_POWER_ON); 1384 return 0; 1385 } 1386 /* EXAMPLE_END */ 1387