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