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 printf("AVRCP Controller: Playback status changed %s\n", avrcp_play_status2str(play_status)); return; 675 case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED: 676 printf("AVRCP Controller: Playing content changed\n"); 677 return; 678 case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED: 679 printf("AVRCP Controller: Track changed\n"); 680 return; 681 case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED: 682 printf("AVRCP Controller: Changed\n"); 683 return; 684 case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{ 685 uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet); 686 uint8_t repeat_mode = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet); 687 printf("AVRCP Controller: %s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode)); 688 break; 689 } 690 case AVRCP_SUBEVENT_NOW_PLAYING_TRACK_INFO: 691 printf("AVRCP Controller: Track: %d\n", avrcp_subevent_now_playing_track_info_get_track(packet)); 692 break; 693 694 case AVRCP_SUBEVENT_NOW_PLAYING_TOTAL_TRACKS_INFO: 695 printf("AVRCP Controller: Total Tracks: %d\n", avrcp_subevent_now_playing_total_tracks_info_get_total_tracks(packet)); 696 break; 697 698 case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO: 699 if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0){ 700 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet)); 701 printf("AVRCP Controller: Title: %s\n", avrcp_subevent_value); 702 } 703 break; 704 705 case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO: 706 if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0){ 707 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet)); 708 printf("AVRCP Controller: Artist: %s\n", avrcp_subevent_value); 709 } 710 break; 711 712 case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO: 713 if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0){ 714 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet)); 715 printf("AVRCP Controller: Album: %s\n", avrcp_subevent_value); 716 } 717 break; 718 719 case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO: 720 if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0){ 721 memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet)); 722 printf("AVRCP Controller: Genre: %s\n", avrcp_subevent_value); 723 } 724 break; 725 726 case AVRCP_SUBEVENT_PLAY_STATUS: 727 printf("AVRCP Controller: Song length %"PRIu32" ms, Song position %"PRIu32" ms, Play status %s\n", 728 avrcp_subevent_play_status_get_song_length(packet), 729 avrcp_subevent_play_status_get_song_position(packet), 730 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet))); 731 break; 732 733 case AVRCP_SUBEVENT_OPERATION_COMPLETE: 734 printf("AVRCP Controller: %s complete\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet))); 735 break; 736 737 case AVRCP_SUBEVENT_OPERATION_START: 738 printf("AVRCP Controller: %s start\n", avrcp_operation2str(avrcp_subevent_operation_start_get_operation_id(packet))); 739 break; 740 741 case AVRCP_SUBEVENT_NOTIFICATION_EVENT_TRACK_REACHED_END: 742 printf("AVRCP Controller: Track reached end\n"); 743 break; 744 745 case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE: 746 printf("AVRCP Controller: Set Player App Value %s\n", avrcp_ctype2str(avrcp_subevent_player_application_value_response_get_command_type(packet))); 747 break; 748 749 default: 750 break; 751 } 752 } 753 754 static void avrcp_volume_changed(uint8_t volume){ 755 const btstack_audio_sink_t * audio = btstack_audio_sink_get_instance(); 756 if (audio){ 757 audio->set_volume(volume); 758 } 759 } 760 761 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 762 UNUSED(channel); 763 UNUSED(size); 764 765 if (packet_type != HCI_EVENT_PACKET) return; 766 if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return; 767 768 uint8_t volume; 769 char const * button_state; 770 avrcp_operation_id_t operation_id; 771 772 switch (packet[2]){ 773 case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED: 774 volume = avrcp_subevent_notification_volume_changed_get_absolute_volume(packet); 775 volume_percentage = volume * 100 / 127; 776 printf("AVRCP Target : Volume set to %d%% (%d)\n", volume_percentage, volume); 777 avrcp_volume_changed(volume); 778 break; 779 780 case AVRCP_SUBEVENT_OPERATION: 781 operation_id = avrcp_subevent_operation_get_operation_id(packet); 782 button_state = avrcp_subevent_operation_get_button_pressed(packet) > 0 ? "PRESS" : "RELEASE"; 783 switch (operation_id){ 784 case AVRCP_OPERATION_ID_VOLUME_UP: 785 printf("AVRCP Target : VOLUME UP (%s)\n", button_state); 786 break; 787 case AVRCP_OPERATION_ID_VOLUME_DOWN: 788 printf("AVRCP Target : VOLUME DOWN (%s)\n", button_state); 789 break; 790 default: 791 return; 792 } 793 break; 794 default: 795 printf("AVRCP Target : Event 0x%02x is not parsed\n", packet[2]); 796 break; 797 } 798 } 799 800 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 801 UNUSED(channel); 802 UNUSED(size); 803 if (packet_type != HCI_EVENT_PACKET) return; 804 if (hci_event_packet_get_type(packet) == HCI_EVENT_PIN_CODE_REQUEST) { 805 bd_addr_t address; 806 printf("Pin code request - using '0000'\n"); 807 hci_event_pin_code_request_get_bd_addr(packet, address); 808 gap_pin_code_response(address, "0000"); 809 } 810 } 811 812 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 813 UNUSED(channel); 814 UNUSED(size); 815 bd_addr_t address; 816 uint8_t status; 817 818 uint8_t allocation_method; 819 820 if (packet_type != HCI_EVENT_PACKET) return; 821 if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return; 822 823 a2dp_sink_demo_a2dp_connection_t * a2dp_conn = &a2dp_sink_demo_a2dp_connection; 824 825 switch (packet[2]){ 826 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION: 827 printf("A2DP Sink : Received non SBC codec - not implemented\n"); 828 break; 829 case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{ 830 printf("A2DP Sink : Received SBC codec configuration\n"); 831 a2dp_conn->sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet); 832 a2dp_conn->sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet); 833 a2dp_conn->sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet); 834 a2dp_conn->sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet); 835 a2dp_conn->sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet); 836 a2dp_conn->sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet); 837 a2dp_conn->sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet); 838 839 allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet); 840 841 // Adapt Bluetooth spec definition to SBC Encoder expected input 842 a2dp_conn->sbc_configuration.allocation_method = (btstack_sbc_allocation_method_t)(allocation_method - 1); 843 844 switch (a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet)){ 845 case AVDTP_CHANNEL_MODE_JOINT_STEREO: 846 a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO; 847 break; 848 case AVDTP_CHANNEL_MODE_STEREO: 849 a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_STEREO; 850 break; 851 case AVDTP_CHANNEL_MODE_DUAL_CHANNEL: 852 a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL; 853 break; 854 case AVDTP_CHANNEL_MODE_MONO: 855 a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_MONO; 856 break; 857 default: 858 btstack_assert(false); 859 break; 860 } 861 dump_sbc_configuration(&a2dp_conn->sbc_configuration); 862 break; 863 } 864 865 case A2DP_SUBEVENT_STREAM_ESTABLISHED: 866 a2dp_subevent_stream_established_get_bd_addr(packet, a2dp_conn->addr); 867 868 status = a2dp_subevent_stream_established_get_status(packet); 869 if (status != ERROR_CODE_SUCCESS){ 870 printf("A2DP Sink : Streaming connection failed, status 0x%02x\n", status); 871 break; 872 } 873 874 a2dp_conn->a2dp_cid = a2dp_subevent_stream_established_get_a2dp_cid(packet); 875 a2dp_conn->stream_state = STREAM_STATE_OPEN; 876 877 printf("A2DP Sink : Streaming connection is established, address %s, cid 0x%02x, local seid %d\n", 878 bd_addr_to_str(address), a2dp_conn->a2dp_cid, a2dp_conn->a2dp_local_seid); 879 #ifdef HAVE_BTSTACK_STDIN 880 // use address for outgoing connections 881 memcpy(device_addr, address, 6); 882 #endif 883 break; 884 885 #ifdef ENABLE_AVDTP_ACCEPTOR_EXPLICIT_START_STREAM_CONFIRMATION 886 case A2DP_SUBEVENT_START_STREAM_REQUESTED: 887 printf("A2DP Sink : Explicit Accept to start stream, local_seid %d\n", a2dp_subevent_start_stream_requested_get_local_seid(packet)); 888 a2dp_sink_start_stream_accept(a2dp_cid, a2dp_local_seid); 889 break; 890 #endif 891 case A2DP_SUBEVENT_STREAM_STARTED: 892 printf("A2DP Sink : Stream started\n"); 893 a2dp_conn->stream_state = STREAM_STATE_PLAYING; 894 if (a2dp_conn->sbc_configuration.reconfigure){ 895 media_processing_close(); 896 } 897 // prepare media processing 898 media_processing_init(&a2dp_conn->sbc_configuration); 899 // audio stream is started when buffer reaches minimal level 900 break; 901 902 case A2DP_SUBEVENT_STREAM_SUSPENDED: 903 printf("A2DP Sink : Stream paused\n"); 904 a2dp_conn->stream_state = STREAM_STATE_PAUSED; 905 media_processing_pause(); 906 break; 907 908 case A2DP_SUBEVENT_STREAM_RELEASED: 909 printf("A2DP Sink : Stream released\n"); 910 a2dp_conn->stream_state = STREAM_STATE_CLOSED; 911 media_processing_close(); 912 break; 913 914 case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED: 915 printf("A2DP Sink : Signaling connection released\n"); 916 a2dp_conn->a2dp_cid = 0; 917 media_processing_close(); 918 break; 919 920 default: 921 break; 922 } 923 } 924 925 #ifdef HAVE_BTSTACK_STDIN 926 static void show_usage(void){ 927 bd_addr_t iut_address; 928 gap_local_bd_addr(iut_address); 929 printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address)); 930 printf("b - AVDTP Sink create connection to addr %s\n", bd_addr_to_str(device_addr)); 931 printf("B - AVDTP Sink disconnect\n"); 932 printf("c - AVRCP create connection to addr %s\n", bd_addr_to_str(device_addr)); 933 printf("C - AVRCP disconnect\n"); 934 935 printf("w - delay report\n"); 936 937 printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address)); 938 printf("O - get play status\n"); 939 printf("j - get now playing info\n"); 940 printf("k - play\n"); 941 printf("K - stop\n"); 942 printf("L - pause\n"); 943 printf("u - start fast forward\n"); 944 printf("U - stop fast forward\n"); 945 printf("n - start rewind\n"); 946 printf("N - stop rewind\n"); 947 printf("i - forward\n"); 948 printf("I - backward\n"); 949 printf("M - mute\n"); 950 printf("r - skip\n"); 951 printf("q - query repeat and shuffle mode\n"); 952 printf("v - repeat single track\n"); 953 printf("x - repeat all tracks\n"); 954 printf("X - disable repeat mode\n"); 955 printf("z - shuffle all tracks\n"); 956 printf("Z - disable shuffle mode\n"); 957 958 printf("a/A - register/deregister TRACK_CHANGED\n"); 959 printf("R/P - register/deregister PLAYBACK_POS_CHANGED\n"); 960 961 printf("s/S - send/release long button press REWIND\n"); 962 963 printf("\n--- Volume and Battery Control ---\n"); 964 printf("t - volume up for 10 percent\n"); 965 printf("T - volume down for 10 percent\n"); 966 printf("V - toggle Battery status from AVRCP_BATTERY_STATUS_NORMAL to AVRCP_BATTERY_STATUS_FULL_CHARGE\n"); 967 printf("---\n"); 968 } 969 #endif 970 971 #ifdef HAVE_BTSTACK_STDIN 972 static void stdin_process(char cmd){ 973 uint8_t status = ERROR_CODE_SUCCESS; 974 uint8_t volume; 975 avrcp_battery_status_t old_battery_status; 976 977 a2dp_sink_demo_stream_endpoint_t * stream_endpoint = &a2dp_sink_demo_stream_endpoint; 978 a2dp_sink_demo_a2dp_connection_t * a2dp_connection = &a2dp_sink_demo_a2dp_connection; 979 a2dp_sink_demo_avrcp_connection_t * avrcp_connection = &a2dp_sink_demo_avrcp_connection; 980 981 switch (cmd){ 982 case 'b': 983 status = a2dp_sink_establish_stream(device_addr, stream_endpoint->a2dp_local_seid, &a2dp_connection->a2dp_cid); 984 printf(" - Create AVDTP connection to addr %s, and local seid %d, cid 0x%02x.\n", 985 bd_addr_to_str(device_addr), a2dp_connection->a2dp_local_seid, a2dp_connection->a2dp_cid); 986 break; 987 case 'B': 988 printf(" - AVDTP disconnect from addr %s.\n", bd_addr_to_str(device_addr)); 989 a2dp_sink_disconnect(a2dp_connection->a2dp_cid); 990 break; 991 case 'c': 992 printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr)); 993 status = avrcp_connect(device_addr, &avrcp_connection->avrcp_cid); 994 break; 995 case 'C': 996 printf(" - AVRCP disconnect from addr %s.\n", bd_addr_to_str(device_addr)); 997 status = avrcp_disconnect(avrcp_connection->avrcp_cid); 998 break; 999 1000 case '\n': 1001 case '\r': 1002 break; 1003 case 'w': 1004 printf("Send delay report\n"); 1005 avdtp_sink_delay_report(a2dp_connection->a2dp_cid, a2dp_connection->a2dp_local_seid, 100); 1006 break; 1007 // Volume Control 1008 case 't': 1009 volume_percentage = volume_percentage <= 90 ? volume_percentage + 10 : 100; 1010 volume = volume_percentage * 127 / 100; 1011 printf(" - volume up for 10 percent, %d%% (%d) \n", volume_percentage, volume); 1012 status = avrcp_target_volume_changed(avrcp_connection->avrcp_cid, volume); 1013 avrcp_volume_changed(volume); 1014 break; 1015 case 'T': 1016 volume_percentage = volume_percentage >= 10 ? volume_percentage - 10 : 0; 1017 volume = volume_percentage * 127 / 100; 1018 printf(" - volume down for 10 percent, %d%% (%d) \n", volume_percentage, volume); 1019 status = avrcp_target_volume_changed(avrcp_connection->avrcp_cid, volume); 1020 avrcp_volume_changed(volume); 1021 break; 1022 case 'V': 1023 old_battery_status = battery_status; 1024 1025 if (battery_status < AVRCP_BATTERY_STATUS_FULL_CHARGE){ 1026 battery_status = (avrcp_battery_status_t)((uint8_t) battery_status + 1); 1027 } else { 1028 battery_status = AVRCP_BATTERY_STATUS_NORMAL; 1029 } 1030 printf(" - toggle battery value, old %d, new %d\n", old_battery_status, battery_status); 1031 status = avrcp_target_battery_status_changed(avrcp_connection->avrcp_cid, battery_status); 1032 break; 1033 case 'O': 1034 printf(" - get play status\n"); 1035 status = avrcp_controller_get_play_status(avrcp_connection->avrcp_cid); 1036 break; 1037 case 'j': 1038 printf(" - get now playing info\n"); 1039 status = avrcp_controller_get_now_playing_info(avrcp_connection->avrcp_cid); 1040 break; 1041 case 'k': 1042 printf(" - play\n"); 1043 status = avrcp_controller_play(avrcp_connection->avrcp_cid); 1044 break; 1045 case 'K': 1046 printf(" - stop\n"); 1047 status = avrcp_controller_stop(avrcp_connection->avrcp_cid); 1048 break; 1049 case 'L': 1050 printf(" - pause\n"); 1051 status = avrcp_controller_pause(avrcp_connection->avrcp_cid); 1052 break; 1053 case 'u': 1054 printf(" - start fast forward\n"); 1055 status = avrcp_controller_press_and_hold_fast_forward(avrcp_connection->avrcp_cid); 1056 break; 1057 case 'U': 1058 printf(" - stop fast forward\n"); 1059 status = avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid); 1060 break; 1061 case 'n': 1062 printf(" - start rewind\n"); 1063 status = avrcp_controller_press_and_hold_rewind(avrcp_connection->avrcp_cid); 1064 break; 1065 case 'N': 1066 printf(" - stop rewind\n"); 1067 status = avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid); 1068 break; 1069 case 'i': 1070 printf(" - forward\n"); 1071 status = avrcp_controller_forward(avrcp_connection->avrcp_cid); 1072 break; 1073 case 'I': 1074 printf(" - backward\n"); 1075 status = avrcp_controller_backward(avrcp_connection->avrcp_cid); 1076 break; 1077 case 'M': 1078 printf(" - mute\n"); 1079 status = avrcp_controller_mute(avrcp_connection->avrcp_cid); 1080 break; 1081 case 'r': 1082 printf(" - skip\n"); 1083 status = avrcp_controller_skip(avrcp_connection->avrcp_cid); 1084 break; 1085 case 'q': 1086 printf(" - query repeat and shuffle mode\n"); 1087 status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_connection->avrcp_cid); 1088 break; 1089 case 'v': 1090 printf(" - repeat single track\n"); 1091 status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK); 1092 break; 1093 case 'x': 1094 printf(" - repeat all tracks\n"); 1095 status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS); 1096 break; 1097 case 'X': 1098 printf(" - disable repeat mode\n"); 1099 status = avrcp_controller_set_repeat_mode(avrcp_connection->avrcp_cid, AVRCP_REPEAT_MODE_OFF); 1100 break; 1101 case 'z': 1102 printf(" - shuffle all tracks\n"); 1103 status = avrcp_controller_set_shuffle_mode(avrcp_connection->avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS); 1104 break; 1105 case 'Z': 1106 printf(" - disable shuffle mode\n"); 1107 status = avrcp_controller_set_shuffle_mode(avrcp_connection->avrcp_cid, AVRCP_SHUFFLE_MODE_OFF); 1108 break; 1109 case 'a': 1110 printf("AVRCP: enable notification TRACK_CHANGED\n"); 1111 avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED); 1112 break; 1113 case 'A': 1114 printf("AVRCP: disable notification TRACK_CHANGED\n"); 1115 avrcp_controller_disable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED); 1116 break; 1117 case 'R': 1118 printf("AVRCP: enable notification PLAYBACK_POS_CHANGED\n"); 1119 avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED); 1120 break; 1121 case 'P': 1122 printf("AVRCP: disable notification PLAYBACK_POS_CHANGED\n"); 1123 avrcp_controller_disable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED); 1124 break; 1125 case 's': 1126 printf("AVRCP: send long button press REWIND\n"); 1127 avrcp_controller_start_press_and_hold_cmd(avrcp_connection->avrcp_cid, AVRCP_OPERATION_ID_REWIND); 1128 break; 1129 case 'S': 1130 printf("AVRCP: release long button press REWIND\n"); 1131 avrcp_controller_release_press_and_hold_cmd(avrcp_connection->avrcp_cid); 1132 break; 1133 default: 1134 show_usage(); 1135 return; 1136 } 1137 if (status != ERROR_CODE_SUCCESS){ 1138 printf("Could not perform command, status 0x%02x\n", status); 1139 } 1140 } 1141 #endif 1142 1143 int btstack_main(int argc, const char * argv[]); 1144 int btstack_main(int argc, const char * argv[]){ 1145 UNUSED(argc); 1146 (void)argv; 1147 1148 a2dp_and_avrcp_setup(); 1149 1150 #ifdef HAVE_BTSTACK_STDIN 1151 // parse human-readable Bluetooth address 1152 sscanf_bd_addr(device_addr_string, device_addr); 1153 btstack_stdin_setup(stdin_process); 1154 #endif 1155 1156 // turn on! 1157 printf("Starting BTstack ...\n"); 1158 hci_power_control(HCI_POWER_ON); 1159 return 0; 1160 } 1161 /* EXAMPLE_END */ 1162