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