test/le_audio: add le audio broadcast sink + source tests

This commit is contained in:
Matthias Ringwald 2022-02-01 15:28:23 +01:00
parent ace087123b
commit 10277393e9
5 changed files with 1967 additions and 0 deletions

View File

@ -0,0 +1,173 @@
cmake_minimum_required (VERSION 3.12)
project(BTstack-LE-Audio)
set (CMAKE_CXX_STANDARD 11)
# fink pkgconfig
find_package(PkgConfig REQUIRED)
# libusb
pkg_check_modules(LIBUSB REQUIRED libusb-1.0)
include_directories(${LIBUSB_INCLUDE_DIRS})
link_directories(${LIBUSB_LIBRARY_DIRS})
link_libraries(${LIBUSB_LIBRARIES})
# portaudio
pkg_check_modules(PORTAUDIO portaudio-2.0)
if(PORTAUDIO_FOUND)
include_directories(${PORTAUDIO_INCLUDE_DIRS})
link_directories(${PORTAUDIO_LIBRARY_DIRS})
link_libraries(${PORTAUDIO_LIBRARIES})
add_compile_definitions(HAVE_PORTAUDIO)
endif()
# fdk-aac
pkg_check_modules(FDK_AAC fdk-aac)
if(FDK_AAC_FOUND)
message("HAVE_AAC_FDK")
include_directories(${FDK_AAC_INCLUDE_DIRS})
link_directories(${FDK_AAC_LIBRARY_DIRS})
link_libraries(${FDK_AAC_LIBRARIES})
add_compile_definitions(HAVE_AAC_FDK)
endif()
# ldac encoder
pkg_check_modules(LDAC_ENCODER ldacBT-enc)
if (LDAC_ENCODER_FOUND)
message("HAVE_LDAC_ENCODER")
include_directories(${LDAC_ENCODER_INCLUDE_DIRS})
link_directories(${LDAC_ENCODER_LIBRARY_DIRS})
link_libraries(${LDAC_ENCODER_LIBRARIES})
add_compile_definitions(HAVE_LDAC_ENCODER)
endif()
# ldac decoder
pkg_check_modules(LDAC_DECODER libldacdec)
if (LDAC_DECODER_FOUND)
message("HAVE_LDAC_DECODER")
include_directories(${LDAC_DECODER_INCLUDE_DIRS})
link_directories(${LDAC_DECODER_LIBRARY_DIRS})
link_libraries(${LDAC_DECODER_LIBRARIES})
add_compile_definitions(HAVE_LDAC_DECODER)
endif()
# openaptx
pkg_check_modules(APTX libopenaptx)
if (APTX_FOUND)
message("HAVE_APTX")
include_directories(${APTX_INCLUDE_DIRS})
link_directories(${APTX_LIBRARY_DIRS})
link_libraries(${APTX_LIBRARIES})
add_compile_definitions(HAVE_APTX)
endif()
# enable optional features
add_compile_definitions(ENABLE_TESTING_SUPPORT)
# to find generated .h from .gatt files
include_directories(${CMAKE_CURRENT_BINARY_DIR})
# local dir for btstack_config.h after build dir to avoid using .h from Makefile
include_directories(.)
include_directories(../../3rd-party/micro-ecc)
include_directories(../../3rd-party/bluedroid/decoder/include)
include_directories(../../3rd-party/bluedroid/encoder/include)
include_directories(../../3rd-party/md5)
include_directories(../../3rd-party/hxcmod-player)
include_directories(../../3rd-party/hxcmod-player/mod)
include_directories(../../3rd-party/kissfft)
include_directories(../../3rd-party/liblc3codec/Api)
include_directories(../../3rd-party/liblc3codec/Common)
include_directories(../../3rd-party/liblc3codec/Common/KissFft)
include_directories(../../3rd-party/liblc3codec/Common/Tables)
include_directories(../../3rd-party/liblc3codec/TestSupport)
include_directories(../../3rd-party/lwip/core/src/include)
include_directories(../../3rd-party/lwip/dhcp-server)
include_directories(../../3rd-party/rijndael)
include_directories(../../3rd-party/yxml)
include_directories(../../3rd-party/tinydir)
include_directories(../../src)
include_directories(../../example)
include_directories(../../chipset/zephyr)
include_directories(../../platform/posix)
include_directories(../../platform/embedded)
include_directories(../../platform/lwip)
include_directories(../../platform/lwip/port)
file(GLOB SOURCES_SRC "../../src/*.c" "../../src/*.cpp" "../../example/sco_demo_util.c")
file(GLOB SOURCES_BLE "../../src/ble/*.c")
file(GLOB SOURCES_GATT "../../src/ble/gatt-service/*.c")
file(GLOB SOURCES_CLASSIC "../../src/classic/*.c")
file(GLOB SOURCES_MESH "../../src/mesh/*.c")
file(GLOB SOURCES_MD5 "../../3rd-party/md5/md5.c")
file(GLOB SOURCES_UECC "../../3rd-party/micro-ecc/uECC.c")
file(GLOB SOURCES_YXML "../../3rd-party/yxml/yxml.c")
file(GLOB SOURCES_HXCMOD "../../3rd-party/hxcmod-player/*.c" "../../3rd-party/hxcmod-player/mods/*.c")
file(GLOB SOURCES_RIJNDAEL "../../3rd-party/rijndael/rijndael.c")
file(GLOB SOURCES_POSIX "../../platform/posix/*.c")
file(GLOB SOURCES_MAIN "main.c")
file(GLOB SOURCES_ZEPHYR "../../chipset/zephyr/*.c")
file(GLOB LC3_COMMON "../../3rd-party/liblc3codec/Common/*.cpp")
file(GLOB LC3_TABLES "../../3rd-party/liblc3codec/Common/Tables/*.cpp")
file(GLOB LC3_DECODER "../../3rd-party/liblc3codec/Decoder/*.cpp")
file(GLOB LC3_ENCODER "../../3rd-party/liblc3codec/Encoder/*.cpp")
set (SOURCES_LC3 ${LC3_COMMON} ${LC3_TABLES} ${LC3_DECODER} ${LC3_ENCODER} ${LC3_TESTSUPPORT})
file(GLOB SOURCES_BLE_OFF "../../src/ble/le_device_db_memory.c")
list(REMOVE_ITEM SOURCES_BLE ${SOURCES_BLE_OFF})
file(GLOB SOURCES_POSIX_OFF "../../platform/posix/le_device_db_fs.c")
list(REMOVE_ITEM SOURCES_POSIX ${SOURCES_POSIX_OFF})
set(SOURCES
${SOURCES_MD5}
${SOURCES_YXML}
${SOURCES_LC3}
${SOURCES_POSIX}
${SOURCES_MAIN}
${SOURCES_RIJNDAEL}
${SOURCES_SRC}
${SOURCES_BLE}
${SOURCES_GATT}
${SOURCES_MESH}
${SOURCES_CLASSIC}
${SOURCES_UECC}
${SOURCES_HXCMOD}
${SOURCES_ZEPHYR}
)
list(SORT SOURCES)
# Enable ASAN
add_compile_options( -g -fsanitize=address)
add_link_options( -fsanitize=address)
# create static lib
add_library(btstack STATIC ${SOURCES})
# create targets for all examples
file(GLOB EXAMPLES_C "le_audio_*.c")
list(SORT EXAMPLES_C)
file(GLOB EXAMPLES_GATT "*.gatt")
# create targets
foreach(EXAMPLE_FILE ${EXAMPLES_C})
get_filename_component(EXAMPLE ${EXAMPLE_FILE} NAME_WE)
# add GATT DB creation
if ( "${EXAMPLES_GATT}" MATCHES ${EXAMPLE} )
message("LE Audio Tool: ${EXAMPLE} -- with GATT DB")
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${EXAMPLE}.h
DEPENDS ${CMAKE_SOURCE_DIR}/${EXAMPLE}.gatt
COMMAND ${CMAKE_SOURCE_DIR}/../../tool/compile_gatt.py
ARGS ${CMAKE_SOURCE_DIR}/${EXAMPLE}.gatt ${CMAKE_CURRENT_BINARY_DIR}/${EXAMPLE}.h
)
list(APPEND SOURCE_FILES ${CMAKE_CURRENT_BINARY_DIR}/${EXAMPLE}.h)
else()
message("LE Audio Tool: ${EXAMPLE}")
endif()
add_executable(${EXAMPLE} ${EXAMPLE_FILE} )
target_link_libraries(${EXAMPLE} btstack)
endforeach(EXAMPLE_FILE)

View File

@ -0,0 +1,67 @@
//
// btstack_config.h for libusb port
//
#ifndef BTSTACK_CONFIG_H
#define BTSTACK_CONFIG_H
// Port related features
#define HAVE_ASSERT
#define HAVE_BTSTACK_STDIN
#define HAVE_MALLOC
#define HAVE_POSIX_FILE_IO
#define HAVE_POSIX_TIME
#define HAVE_LC3_EHIMA
// BTstack features that can be enabled
#define ENABLE_ATT_DELAYED_RESPONSE
#define ENABLE_BLE
#define ENABLE_CLASSIC
#define ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
#define ENABLE_HFP_WIDE_BAND_SPEECH
#define ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
#define ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
#define ENABLE_GOEP_L2CAP
#define ENABLE_GATT_OVER_CLASSIC
#define ENABLE_LE_CENTRAL
#define ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
#define ENABLE_LE_DATA_LENGTH_EXTENSION
#define ENABLE_LE_PERIPHERAL
#define ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
#define ENABLE_LE_SECURE_CONNECTIONS
#define ENABLE_LOG_ERROR
#define ENABLE_LOG_INFO
#define ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS
#define ENABLE_PRINTF_HEXDUMP
#define ENABLE_SCO_OVER_HCI
#define ENABLE_SDP_DES_DUMP
#define ENABLE_SOFTWARE_AES128
#define ENABLE_AVCTP_FRAGMENTATION
#define ENABLE_LE_EXTENDED_ADVERTISING
#define ENABLE_LE_PERIODIC_ADVERTISING
// BTstack configuration. buffers, sizes, ...
#define HCI_ACL_PAYLOAD_SIZE (1691 + 4)
#define HCI_INCOMING_PRE_BUFFER_SIZE 14 // sizeof BNEP header, avoid memcpy
#define NVM_NUM_DEVICE_DB_ENTRIES 16
#define NVM_NUM_LINK_KEYS 16
// Mesh Configuration
#define ENABLE_MESH
#define ENABLE_MESH_ADV_BEARER
#define ENABLE_MESH_GATT_BEARER
#define ENABLE_MESH_PB_ADV
#define ENABLE_MESH_PB_GATT
#define ENABLE_MESH_PROVISIONER
#define ENABLE_MESH_PROXY_SERVER
#define MAX_NR_MESH_SUBNETS 2
#define MAX_NR_MESH_TRANSPORT_KEYS 16
#define MAX_NR_MESH_VIRTUAL_ADDRESSES 16
// allow for one NetKey update
#define MAX_NR_MESH_NETWORK_KEYS (MAX_NR_MESH_SUBNETS+1)
#endif

View File

@ -0,0 +1,689 @@
/*
* Copyright (C) 2022 BlueKitchen GmbH
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* 4. Any redistribution, use, or modification is done solely for
* personal benefit and not for any commercial purpose or for
* monetary gain.
*
* THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
* RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Please inquire about commercial licensing options at
* contact@bluekitchen-gmbh.com
*
*/
#define BTSTACK_FILE__ "le_audio_broadcast_sink.c"
/*
* LE Audio Broadcast Sink
*/
#include "btstack_config.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <inttypes.h>
#include <fcntl.h> // open
#include <errno.h>
#include "ad_parser.h"
#include "bluetooth_data_types.h"
#include "bluetooth_gatt.h"
#include "btstack_debug.h"
#include "btstack_audio.h"
#include "btstack_event.h"
#include "btstack_run_loop.h"
#include "btstack_ring_buffer.h"
#include "btstack_stdin.h"
#include "btstack_util.h"
#include "gap.h"
#include "hci.h"
#include "hci_cmd.h"
#include "lc3.h"
#include "lc3_ehima.h"
#include "wav_util.h"
// max config
#define MAX_NUM_BIS 2
#define MAX_SAMPLES_PER_FRAME 480
#define DUMP_LEN_LC3_FRAMES 1000
// playback
#define MAX_NUM_LC3_FRAMES 5
#define MAX_BYTES_PER_SAMPLE 4
#define PLAYBACK_BUFFER_SIZE (MAX_NUM_LC3_FRAMES * MAX_SAMPLES_PER_FRAME * MAX_BYTES_PER_SAMPLE)
// analysis
#define PACKET_PREFIX_LEN 10
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
static void show_usage(void);
static const char * filename_lc3 = "le_audio_broadcast_sink.lc3";
static const char * filename_wav = "le_audio_broadcast_sink.wav";
static enum {
APP_W4_WORKING,
APP_W4_BROADCAST_ADV,
APP_W4_PA_AND_BIG_INFO,
APP_CREATE_BIG_SYNC,
APP_W4_BIG_SYNC_ESTABLISHED,
APP_SET_ISO_PATHS,
APP_STREAMING,
APP_TERMINATE_BIG,
APP_IDLE
} app_state = APP_W4_WORKING;
//
static btstack_packet_callback_registration_t hci_event_callback_registration;
static bool have_base;
static bool have_big_info;
uint32_t last_samples_report_ms;
uint32_t samples_received;
uint32_t samples_dropped;
uint16_t frames_per_second[MAX_NUM_BIS];
// remote info
static char remote_name[20];
static bd_addr_t remote;
static bd_addr_type_t remote_type;
static uint8_t remote_sid;
static bool count_mode;
static bool pts_mode;
// broadcast info
static const uint8_t big_handle = 1;
static hci_con_handle_t sync_handle;
static hci_con_handle_t bis_con_handles[MAX_NUM_BIS];
static unsigned int next_bis_index;
// analysis
static uint16_t last_packet_sequence[MAX_NUM_BIS];
static uint32_t last_packet_time_ms[MAX_NUM_BIS];
static uint8_t last_packet_prefix[MAX_NUM_BIS * PACKET_PREFIX_LEN];
// lc3 writer
static int dump_file;
static uint32_t lc3_frames;
// lc3 codec config
static uint32_t sampling_frequency_hz;
static lc3_frame_duration_t frame_duration;
static uint16_t number_samples_per_frame;
static uint16_t octets_per_frame;
static uint8_t num_bis;
// lc3 decoder
static const lc3_decoder_t * lc3_decoder;
static lc3_decoder_ehima_t decoder_contexts[MAX_NUM_BIS];
static int16_t pcm[MAX_NUM_BIS * MAX_SAMPLES_PER_FRAME];
// playback
static uint8_t playback_buffer_storage[PLAYBACK_BUFFER_SIZE];
static btstack_ring_buffer_t playback_buffer;
static void le_audio_broadcast_sink_playback(int16_t * buffer, uint16_t num_samples){
// called from lower-layer but guaranteed to be on main thread
uint32_t bytes_needed = num_samples * num_bis * 2;
static bool underrun = true;
log_info("Playback: need %u, have %u", num_samples, btstack_ring_buffer_bytes_available(&playback_buffer) / ( num_bis * 2));
if (bytes_needed > btstack_ring_buffer_bytes_available(&playback_buffer)){
memset(buffer, 0, bytes_needed);
if (underrun == false){
log_info("Playback underrun");
underrun = true;
}
return;
}
if (underrun){
underrun = false;
log_info("Playback started");
}
uint32_t bytes_read;
btstack_ring_buffer_read(&playback_buffer, (uint8_t *) buffer, bytes_needed, &bytes_read);
btstack_assert(bytes_read == bytes_needed);
}
static void open_lc3_file(void) {
// open lc3 file
int oflags = O_WRONLY | O_CREAT | O_TRUNC;
dump_file = open(filename_lc3, oflags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dump_file < 0) {
printf("failed to open file %s, errno = %d\n", filename_lc3, errno);
return;
}
printf("LC3 binary file: %s\n", filename_lc3);
// calc bps
uint16_t frame_duration_100us = (frame_duration == LC3_FRAME_DURATION_7500US) ? 75 : 100;
uint32_t bits_per_second = (uint32_t) octets_per_frame * num_bis * 8 * 10000 / frame_duration_100us;
// write header for floating point implementation
uint8_t header[18];
little_endian_store_16(header, 0, 0xcc1c);
little_endian_store_16(header, 2, sizeof(header));
little_endian_store_16(header, 4, sampling_frequency_hz / 100);
little_endian_store_16(header, 6, bits_per_second / 100);
little_endian_store_16(header, 8, num_bis);
little_endian_store_16(header, 10, frame_duration_100us * 10);
little_endian_store_16(header, 12, 0);
little_endian_store_32(header, 14, DUMP_LEN_LC3_FRAMES * number_samples_per_frame);
write(dump_file, header, sizeof(header));
}
static void setup_lc3_decoder(void){
uint8_t channel;
for (channel = 0 ; channel < num_bis ; channel++){
lc3_decoder_ehima_t * decoder_context = &decoder_contexts[channel];
lc3_decoder = lc3_decoder_ehima_init_instance(decoder_context);
lc3_decoder->configure(decoder_context, sampling_frequency_hz, frame_duration);
}
number_samples_per_frame = lc3_decoder->get_number_samples_per_frame(&decoder_contexts[0]);
btstack_assert(number_samples_per_frame <= MAX_SAMPLES_PER_FRAME);
}
static void close_files(void){
printf("Close files\n");
close(dump_file);
wav_writer_close();
}
static void handle_periodic_advertisement(const uint8_t * packet, uint16_t size){
// periodic advertisement contains the BASE
// TODO: BASE might be split across multiple advertisements
const uint8_t * adv_data = hci_subevent_le_periodic_advertising_report_get_data(packet);
uint16_t adv_size = hci_subevent_le_periodic_advertising_report_get_data_length(packet);
ad_context_t context;
for (ad_iterator_init(&context, adv_size, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
uint8_t data_type = ad_iterator_get_data_type(&context);
uint8_t data_size = ad_iterator_get_data_len(&context);
const uint8_t * data = ad_iterator_get_data(&context);
uint16_t uuid;
switch (data_type){
case BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID:
uuid = little_endian_read_16(data, 0);
if (uuid == ORG_BLUETOOTH_SERVICE_BASIC_AUDIO_ANNOUNCEMENT_SERVICE){
have_base = true;
// Level 1: Group Level
const uint8_t * base_data = &data[2];
uint16_t base_len = data_size - 2;
printf("BASE:\n");
uint32_t presentation_delay = little_endian_read_24(base_data, 0);
printf("- presentation delay: %"PRIu32" us\n", presentation_delay);
uint8_t num_subgroups = base_data[3];
printf("- num subgroups: %u\n", num_subgroups);
uint8_t i;
uint16_t offset = 4;
for (i=0;i<num_subgroups;i++){
// Level 2: Subgroup Level
num_bis = base_data[offset++];
printf(" - num bis[%u]: %u\n", i, num_bis);
// codec_id: coding format = 0x06, vendor and coded id = 0
offset += 5;
uint8_t codec_specific_configuration_length = base_data[offset++];
const uint8_t * codec_specific_configuration = &base_data[offset];
printf(" - codec specific config[%u]: ", i);
printf_hexdump(codec_specific_configuration, codec_specific_configuration_length);
// parse config to get sampling frequency and frame duration
uint8_t codec_offset = 0;
while ((codec_offset + 1) < codec_specific_configuration_length){
uint8_t ltv_len = codec_specific_configuration[codec_offset++];
uint8_t ltv_type = codec_specific_configuration[codec_offset];
const uint32_t sampling_frequency_map[] = { 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 384000 };
uint8_t sampling_frequency_index;
uint8_t frame_duration_index;
switch (ltv_type){
case 0x01: // sampling frequency
sampling_frequency_index = codec_specific_configuration[codec_offset+1];
// TODO: check range
sampling_frequency_hz = sampling_frequency_map[sampling_frequency_index - 1];
printf(" - sampling frequency[%u]: %"PRIu32"\n", i, sampling_frequency_hz);
break;
case 0x02: // 0 = 7.5, 1 = 10 ms
frame_duration_index = codec_specific_configuration[codec_offset+1];
frame_duration = (frame_duration_index == 0) ? LC3_FRAME_DURATION_7500US : LC3_FRAME_DURATION_10000US;
printf(" - frame duration[%u]: %s ms\n", i, (frame_duration == LC3_FRAME_DURATION_7500US) ? "7.5" : "10");
break;
case 0x04: // octets per coding frame
octets_per_frame = little_endian_read_16(codec_specific_configuration, codec_offset+1);
printf(" - octets per codec frame[%u]: %u\n", i, octets_per_frame);
break;
default:
break;
}
codec_offset += ltv_len;
}
//
offset += codec_specific_configuration_length;
uint8_t metadata_length = base_data[offset++];
const uint8_t * meta_data = &base_data[offset];
offset += metadata_length;
printf(" - meta data[%u]: ", i);
printf_hexdump(meta_data, metadata_length);
uint8_t k;
for (k=0;k<num_bis;k++){
// Level 3: BIS Level
uint8_t bis_index = base_data[offset++];
printf(" - bis index[%u][%u]: %u\n", i, k, bis_index);
uint8_t codec_specific_configuration_length2 = base_data[offset++];
const uint8_t * codec_specific_configuration2 = &base_data[offset];
printf(" - codec specific config[%u][%u]: ", i, k);
printf_hexdump(codec_specific_configuration2, codec_specific_configuration_length2);
offset += codec_specific_configuration_length2;
}
}
}
break;
default:
break;
}
}
}
static void handle_big_info(const uint8_t * packet, uint16_t size){
printf("BIG Info advertising report\n");
sync_handle = hci_subevent_le_biginfo_advertising_report_get_sync_handle(packet);
have_big_info = true;
}
static void enter_create_big_sync(void){
// stop scanning
gap_stop_scan();
// init decoder
setup_lc3_decoder();
printf("Configure: %u channels, sampling rate %u, samples per frame %u\n", num_bis, sampling_frequency_hz, number_samples_per_frame);
// create lc3 file
open_lc3_file();
// create wav file
printf("WAV file: %s\n", filename_wav);
wav_writer_open(filename_wav, num_bis, sampling_frequency_hz);
// init playback buffer
btstack_ring_buffer_init(&playback_buffer, playback_buffer_storage, PLAYBACK_BUFFER_SIZE);
// start playback
// PTS 8.2 sends stereo at half speed for stereo, for now playback at half speed
const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
if (sink != NULL){
uint32_t playback_speed;
if ((num_bis > 1) && pts_mode){
playback_speed = sampling_frequency_hz / num_bis;
printf("PTS workaround: playback at %u hz\n", playback_speed);
} else {
playback_speed = sampling_frequency_hz;
};
sink->init(num_bis, sampling_frequency_hz, le_audio_broadcast_sink_playback);
sink->start_stream();
}
app_state = APP_CREATE_BIG_SYNC;
}
static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
UNUSED(channel);
if (packet_type != HCI_EVENT_PACKET) return;
unsigned int i;
switch (packet[0]) {
case BTSTACK_EVENT_STATE:
switch(btstack_event_state_get_state(packet)) {
case HCI_STATE_WORKING:
if (app_state != APP_W4_WORKING) break;
app_state = APP_W4_BROADCAST_ADV;
gap_set_scan_params(1, 0x30, 0x30, 0);
gap_start_scan();
printf("Start scan..\n");
break;
case HCI_STATE_OFF:
printf("Goodbye\n");
exit(0);
break;
default:
break;
}
break;
case GAP_EVENT_EXTENDED_ADVERTISING_REPORT:
{
if (app_state != APP_W4_BROADCAST_ADV) break;
gap_event_extended_advertising_report_get_address(packet, remote);
uint8_t adv_size = gap_event_extended_advertising_report_get_data_length(packet);
const uint8_t * adv_data = gap_event_extended_advertising_report_get_data(packet);
ad_context_t context;
bool found = false;
remote_name[0] = '\0';
uint16_t uuid;
for (ad_iterator_init(&context, adv_size, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
uint8_t data_type = ad_iterator_get_data_type(&context);
uint8_t size = ad_iterator_get_data_len(&context);
const uint8_t *data = ad_iterator_get_data(&context);
switch (data_type){
case BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID:
uuid = little_endian_read_16(data, 0);
if (uuid == ORG_BLUETOOTH_SERVICE_BROADCAST_AUDIO_ANNOUNCEMENT_SERVICE){
found = true;
}
break;
case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
size = btstack_min(sizeof(remote_name) - 1, size);
memcpy(remote_name, data, size);
remote_name[size] = 0;
break;
default:
break;
}
}
if (!found) break;
remote_type = gap_event_extended_advertising_report_get_address_type(packet);
remote_sid = gap_event_extended_advertising_report_get_advertising_sid(packet);
pts_mode = strncmp("PTS-", remote_name, 4) == 0;
count_mode = strncmp("COUNT", remote_name, 5) == 0;
printf("Remote Broadcast sink found, addr %s, name: '%s' (pts-mode: %u, count: %u)\n", bd_addr_to_str(remote), remote_name, pts_mode, count_mode);
// ignore other advertisements
gap_whitelist_add(remote_type, remote);
gap_set_scan_params(1, 0x30, 0x30, 1);
// sync to PA
gap_periodic_advertiser_list_clear();
gap_periodic_advertiser_list_add(remote_type, remote, remote_sid);
app_state = APP_W4_PA_AND_BIG_INFO;
printf("Start Periodic Advertising Sync\n");
gap_periodic_advertising_create_sync(0x01, remote_sid, remote_type, remote, 0, 1000, 0);
break;
}
case HCI_EVENT_LE_META:
switch(hci_event_le_meta_get_subevent_code(packet)) {
case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
printf("Periodic advertising sync established\n");
break;
case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_REPORT:
if (have_base) break;
handle_periodic_advertisement(packet, size);
if (have_big_info){
enter_create_big_sync();
}
break;
case HCI_SUBEVENT_LE_BIGINFO_ADVERTISING_REPORT:
if (have_big_info) break;
handle_big_info(packet, size);
if (have_base){
enter_create_big_sync();
}
break;
case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
printf("BIG Sync Established\n");
if (app_state == APP_W4_BIG_SYNC_ESTABLISHED){
gap_stop_scan();
gap_periodic_advertising_terminate_sync(sync_handle);
// update num_bis
num_bis = packet[16];
for (i=0;i<num_bis;i++){
bis_con_handles[i] = little_endian_read_16(packet, 17 + 2*i);
}
next_bis_index = 0;
app_state = APP_SET_ISO_PATHS;
}
break;
default:
break;
}
default:
break;
}
if (!hci_can_send_command_packet_now()) return;
const uint8_t broadcast_code[16] = { 0 };
uint8_t bis_array[MAX_NUM_BIS];
switch(app_state){
case APP_CREATE_BIG_SYNC:
app_state = APP_W4_BIG_SYNC_ESTABLISHED;
printf("BIG Create Sync for BIS: ");
for (i=0;i<num_bis;i++){
bis_array[i] = i + 1;
printf("%u ", bis_array[i]);
}
printf("\n");
hci_send_cmd(&hci_le_big_create_sync, big_handle, sync_handle, 0, broadcast_code, 0, 100, num_bis, bis_array);
break;
case APP_SET_ISO_PATHS:
hci_send_cmd(&hci_le_setup_iso_data_path, bis_con_handles[next_bis_index++], 1, 0, 0, 0, 0, 0, 0, NULL);
if (next_bis_index == num_bis){
app_state = APP_STREAMING;
last_samples_report_ms = btstack_run_loop_get_time_ms();
}
break;
case APP_TERMINATE_BIG:
hci_send_cmd(&hci_le_big_terminate_sync, big_handle);
app_state = APP_IDLE;
printf("Shutdown...\n");
hci_power_control(HCI_POWER_OFF);
break;
default:
break;
}
}
static void iso_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
uint16_t header = little_endian_read_16(packet, 0);
hci_con_handle_t con_handle = header & 0x0fff;
uint8_t pb_flag = (header >> 12) & 3;
uint8_t ts_flag = (header >> 14) & 1;
uint16_t iso_load_len = little_endian_read_16(packet, 2);
uint16_t offset = 4;
uint32_t time_stamp = 0;
if (ts_flag){
uint32_t time_stamp = little_endian_read_32(packet, offset);
offset += 4;
}
uint16_t packet_sequence_number = little_endian_read_16(packet, offset);
offset += 2;
uint16_t header_2 = little_endian_read_16(packet, offset);
uint16_t iso_sdu_length = header_2 & 0x3fff;
uint8_t packet_status_flag = (uint8_t) (header_2 >> 14);
offset += 2;
if (iso_sdu_length == 0) return;
// infer channel from con handle - only works for up to 2 channels
uint8_t bis_channel = (con_handle == bis_con_handles[0]) ? 0 : 1;
if (count_mode){
// check for missing packet
uint16_t last_seq_no = last_packet_sequence[bis_channel];
uint32_t now = btstack_run_loop_get_time_ms();
bool packet_missed = (last_seq_no != 0) && ((last_seq_no + 1) != packet_sequence_number);
if (packet_missed){
// print last packet
printf("\n");
printf("%04x %10u %u ", last_seq_no, last_packet_time_ms[bis_channel], bis_channel);
printf_hexdump(&last_packet_prefix[num_bis*PACKET_PREFIX_LEN], PACKET_PREFIX_LEN);
last_seq_no++;
printf(ANSI_COLOR_RED);
while (last_seq_no < packet_sequence_number){
printf("%04x %u MISSING\n", last_seq_no, bis_channel);
last_seq_no++;
}
printf(ANSI_COLOR_RESET);
// print current packet
printf("%04x %10u %u ", packet_sequence_number, now, bis_channel);
printf_hexdump(&packet[offset], PACKET_PREFIX_LEN);
}
// cache current packet
last_packet_time_ms[bis_channel] = now;
last_packet_sequence[bis_channel] = packet_sequence_number;
memcpy(&last_packet_prefix[num_bis*PACKET_PREFIX_LEN], &packet[offset], PACKET_PREFIX_LEN);
} else {
if ((packet_sequence_number & 0x7c) == 0) {
printf("%04x %10u %u ", packet_sequence_number, btstack_run_loop_get_time_ms(), bis_channel);
printf_hexdump(&packet[offset], iso_sdu_length);
}
if (lc3_frames < DUMP_LEN_LC3_FRAMES) {
// store len header only for first bis
if (bis_channel == 0) {
uint8_t len_header[2];
little_endian_store_16(len_header, 0, num_bis * iso_sdu_length);
write(dump_file, len_header, 2);
}
// store single channel codec frame
write(dump_file, &packet[offset], iso_sdu_length);
}
// decode codec frame
uint8_t tmp_BEC_detect;
uint8_t BFI = 0;
(void) lc3_decoder->decode(&decoder_contexts[bis_channel], &packet[offset], iso_sdu_length, BFI,
&pcm[bis_channel * MAX_SAMPLES_PER_FRAME], number_samples_per_frame,
&tmp_BEC_detect);
// interleave channel samples
if ((bis_channel + 1) == num_bis) {
uint16_t sample;
int16_t wav_frame[MAX_NUM_BIS];
uint8_t wav_channel;
for (sample = 0; sample < number_samples_per_frame; sample++) {
for (wav_channel = 0; wav_channel < num_bis; wav_channel++) {
wav_frame[wav_channel] = pcm[wav_channel * MAX_SAMPLES_PER_FRAME + sample];
}
// write wav sample
if (lc3_frames < DUMP_LEN_LC3_FRAMES) {
wav_writer_write_int16(num_bis, wav_frame);
}
// store sample in playback buffer
uint32_t bytes_to_store = num_bis * 2;
samples_received++;
if (btstack_ring_buffer_bytes_free(&playback_buffer) >= bytes_to_store) {
btstack_ring_buffer_write(&playback_buffer, (uint8_t *) wav_frame, bytes_to_store);
} else {
samples_dropped++;
}
}
}
log_info("Samples in playback buffer %5u", btstack_ring_buffer_bytes_available(&playback_buffer) / (num_bis * 2));
lc3_frames++;
frames_per_second[bis_channel]++;
uint32_t time_ms = btstack_run_loop_get_time_ms();
if (btstack_time_delta(time_ms, last_samples_report_ms) > 1000){
last_samples_report_ms = time_ms;
printf("LC3 Frames: %4u - ", lc3_frames / num_bis);
uint8_t i;
for (i=0;i<num_bis;i++){
printf("%u ", frames_per_second[i]);
frames_per_second[i] = 0;
}
printf(" frames per second, dropped %u of %u\n", samples_dropped, samples_received);
samples_received = 0;
samples_dropped = 0;
}
if (lc3_frames == DUMP_LEN_LC3_FRAMES){
close_files();
}
}
}
static void show_usage(void){
printf("\n--- LE Audio Broadcast Sink Test Console ---\n");
printf("x - close files and exit\n");
printf("---\n");
}
static void stdin_process(char c){
switch (c){
case 'x':
close_files();
printf("Shutdown...\n");
hci_power_control(HCI_POWER_OFF);
break;
case '\n':
case '\r':
break;
default:
show_usage();
break;
}
}
int btstack_main(int argc, const char * argv[]);
int btstack_main(int argc, const char * argv[]){
(void) argv;
(void) argc;
// register for HCI events
hci_event_callback_registration.callback = &packet_handler;
hci_add_event_handler(&hci_event_callback_registration);
// register for ISO Packet
hci_register_iso_packet_handler(&iso_packet_handler);
// turn on!
hci_power_control(HCI_POWER_ON);
btstack_stdin_setup(stdin_process);
return 0;
}

View File

@ -0,0 +1,803 @@
/*
* Copyright (C) 2022 BlueKitchen GmbH
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* 4. Any redistribution, use, or modification is done solely for
* personal benefit and not for any commercial purpose or for
* monetary gain.
*
* THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
* RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Please inquire about commercial licensing options at
* contact@bluekitchen-gmbh.com
*
*/
#define BTSTACK_FILE__ "le_audio_broadcast_source.c"
/*
* LE Audio Broadcast Source
*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <btstack_debug.h>
#include "bluetooth_data_types.h"
#include "btstack_stdin.h"
#include "btstack_event.h"
#include "btstack_run_loop.h"
#include "gap.h"
#include "hci.h"
#include "hci_cmd.h"
#include "hci_dump.h"
#include "lc3.h"
#include "lc3_ehima.h"
#include "hxcmod.h"
#include "mods/mod.h"
// PTS mode
// #define PTS_MODE
// Count mode - send packet count as test data for manual analysis
// #define COUNT_MODE
// create audio based on timer instead of num completed packets
// #define GENERATE_AUDIO_WITH_TIMER
// max config
#define MAX_NUM_BIS 2
#define MAX_SAMPLES_PER_FRAME 480
static const uint8_t adv_sid = 0;
static le_advertising_set_t le_advertising_set;
static const le_extended_advertising_parameters_t extended_params = {
.advertising_event_properties = 0,
.primary_advertising_interval_min = 0x4b0, // 750 ms
.primary_advertising_interval_max = 0x4b0, // 750 ms
.primary_advertising_channel_map = 7,
.own_address_type = 0,
.peer_address_type = 0,
.peer_address = 0,
.advertising_filter_policy = 0,
.advertising_tx_power = 10, // 10 dBm
.primary_advertising_phy = 1, // LE 1M PHY
.secondary_advertising_max_skip = 0,
.secondary_advertising_phy = 1, // LE 1M PHY
.advertising_sid = adv_sid,
.scan_request_notification_enable = 0,
};
static const uint8_t extended_adv_data[] = {
// 16 bit service data, ORG_BLUETOOTH_SERVICE_BASIC_AUDIO_ANNOUNCEMENT_SERVICE, Broadcast ID
6, BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID, 0x52, 0x18, 0x30, 0x5d, 0x9b,
// name
#ifdef PTS_MODE
7, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'P', 'T', 'S', '-', 'x', 'x'
#elif defined(COUNT_MODE)
6, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'C', 'O', 'U', 'N', 'T'
#else
7, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'S', 'o', 'u', 'r', 'c', 'e'
#endif
};
static const le_periodic_advertising_parameters_t periodic_params = {
.periodic_advertising_interval_min = 0x258, // 375 ms
.periodic_advertising_interval_max = 0x258, // 375 ms
.periodic_advertising_properties = 0
};
static uint8_t periodic_adv_data_1[] = {
// 16 bit service data
37, BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID,
// Level 1 - BIG Parameters (common to all BISes)
0x51, 0x18, // Basic Audio Announcement Service UUID
0x28, 0x00, 0x00, // Presentation Delay 3
0x01, // Num_Subgroups
// Level 2 - BIS Subgroup Parameters (common parameters for subgroups of BISes)
// offset 8
0x01, // The number of BISes in this subgroup
0x06, 0x00, 0x00, 0x00, 0x00, // 0x06 = LC3, vendor id + codec id = 0
10, // Codec_Specific_Configuration_Length[i]
// Codec_Specific_Configuration[i] = 8_2
// offset 15
0x02, 0x01, 0x01, // Sampling frequency 0x01 = 0x01 / 8 kHz
0x02, 0x02, 0x01, // Frame Duration 0x02 = 0x01 / 10 ms
0x03, 0x04, 0x1E, 0x00, // Octets per Frame 0x04 = 0x1e / 30
4, // Metadata_Length[i]
0x03, 0x02, 0x04, 0x00, // Metadata[i]
// Level 3 - Specific BIS Parameters (if required, for individual BISes)
0x01, // BIS_index[i[k]]
6, // Codec_Specific_Configuration_Length[i[k]]
0x05, 0x03, 0x01, 0x00, 0x00, 0x00 // Codec_Specific_Configuration[i[k]]
};
static uint8_t periodic_adv_data_2[] = {
// 16 bit service data
37+8, BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID,
// Level 1 - BIG Parameters (common to all BISes)
0x51, 0x18, // Basic Audio Announcement Service UUID
0x28, 0x00, 0x00, // Presentation Delay 3
0x01, // Num_Subgroups
// Level 2 - BIS Subgroup Parameters (common parameters for subgroups of BISes)
// offset 8
0x02, // The number of BISes in this subgroup
0x06, 0x00, 0x00, 0x00, 0x00, // 0x06 = LC3, vendor id + codec id = 0
10, // Codec_Specific_Configuration_Length[i]
// Codec_Specific_Configuration[0] = 8_2
// offset 15
0x02, 0x01, 0x01, // Sampling frequency 0x01 = 0x01 / 8 kHz
0x02, 0x02, 0x01, // Frame Duration 0x02 = 0x01 / 10 ms
0x03, 0x04, 0x1E, 0x00, // Octets per Frame 0x04 = 0x1e / 30
4, // Metadata_Length[i]
0x03, 0x02, 0x04, 0x00, // Metadata[0]
// Level 3 - Specific BIS Parameters (if required, for individual BISes)
0x01, // BIS_index[i[k]]
6, // Codec_Specific_Configuration_Length[i[k]]
0x05, 0x03, 0x01, 0x00, 0x00, 0x00, // Codec_Specific_Configuration[i[k]]
// Level 3 - Specific BIS Parameters (if required, for individual BISes)
0x02, // BIS_index[i[k]]
6, // Codec_Specific_Configuration_Length[i[k]]
0x05, 0x03, 0x02, 0x00, 0x00, 0x00 // Codec_Specific_Configuration[i[k]]
};
// input signal: pre-computed int16 sine wave, 96000 Hz at 300 Hz
static const int16_t sine_int16[] = {
0, 643, 1286, 1929, 2571, 3212, 3851, 4489, 5126, 5760,
6393, 7022, 7649, 8273, 8894, 9512, 10126, 10735, 11341, 11943,
12539, 13131, 13718, 14300, 14876, 15446, 16011, 16569, 17121, 17666,
18204, 18736, 19260, 19777, 20286, 20787, 21280, 21766, 22242, 22710,
23170, 23620, 24062, 24494, 24916, 25329, 25732, 26126, 26509, 26882,
27245, 27597, 27938, 28269, 28589, 28898, 29196, 29482, 29757, 30021,
30273, 30513, 30742, 30958, 31163, 31356, 31537, 31705, 31862, 32006,
32137, 32257, 32364, 32458, 32540, 32609, 32666, 32710, 32742, 32761,
32767, 32761, 32742, 32710, 32666, 32609, 32540, 32458, 32364, 32257,
32137, 32006, 31862, 31705, 31537, 31356, 31163, 30958, 30742, 30513,
30273, 30021, 29757, 29482, 29196, 28898, 28589, 28269, 27938, 27597,
27245, 26882, 26509, 26126, 25732, 25329, 24916, 24494, 24062, 23620,
23170, 22710, 22242, 21766, 21280, 20787, 20286, 19777, 19260, 18736,
18204, 17666, 17121, 16569, 16011, 15446, 14876, 14300, 13718, 13131,
12539, 11943, 11341, 10735, 10126, 9512, 8894, 8273, 7649, 7022,
6393, 5760, 5126, 4489, 3851, 3212, 2571, 1929, 1286, 643,
0, -643, -1286, -1929, -2571, -3212, -3851, -4489, -5126, -5760,
-6393, -7022, -7649, -8273, -8894, -9512, -10126, -10735, -11341, -11943,
-12539, -13131, -13718, -14300, -14876, -15446, -16011, -16569, -17121, -17666,
-18204, -18736, -19260, -19777, -20286, -20787, -21280, -21766, -22242, -22710,
-23170, -23620, -24062, -24494, -24916, -25329, -25732, -26126, -26509, -26882,
-27245, -27597, -27938, -28269, -28589, -28898, -29196, -29482, -29757, -30021,
-30273, -30513, -30742, -30958, -31163, -31356, -31537, -31705, -31862, -32006,
-32137, -32257, -32364, -32458, -32540, -32609, -32666, -32710, -32742, -32761,
-32767, -32761, -32742, -32710, -32666, -32609, -32540, -32458, -32364, -32257,
-32137, -32006, -31862, -31705, -31537, -31356, -31163, -30958, -30742, -30513,
-30273, -30021, -29757, -29482, -29196, -28898, -28589, -28269, -27938, -27597,
-27245, -26882, -26509, -26126, -25732, -25329, -24916, -24494, -24062, -23620,
-23170, -22710, -22242, -21766, -21280, -20787, -20286, -19777, -19260, -18736,
-18204, -17666, -17121, -16569, -16011, -15446, -14876, -14300, -13718, -13131,
-12539, -11943, -11341, -10735, -10126, -9512, -8894, -8273, -7649, -7022,
-6393, -5760, -5126, -4489, -3851, -3212, -2571, -1929, -1286, -643,
};
static bd_addr_t remote;
static const char * remote_addr_string = "00:1B:DC:08:E2:72";
static btstack_packet_callback_registration_t hci_event_callback_registration;
static uint8_t adv_handle = 0;
static unsigned int next_bis_index;
static hci_con_handle_t bis_con_handles[MAX_NUM_BIS];
static uint16_t packet_sequence_numbers[MAX_NUM_BIS];
static uint8_t framed_pdus;
static bool bis_can_send[MAX_NUM_BIS];
static bool bis_has_data[MAX_NUM_BIS];
static uint8_t iso_frame_counter;
static uint16_t frame_duration_us;
// time stamping
#ifdef COUNT_MODE
#define MAX_PACKET_INTERVAL_BINS_MS 50
static uint32_t send_time_bins[MAX_PACKET_INTERVAL_BINS_MS];
static uint32_t send_last_ms;
#endif
// time based sender
#ifdef GENERATE_AUDIO_WITH_TIMER
static uint32_t next_send_time_ms;
static uint32_t next_send_time_additional_us;
static btstack_timer_source_t send_timer;
#endif
// lc3 codec config
static uint32_t sampling_frequency_hz;
static lc3_frame_duration_t frame_duration;
static uint16_t number_samples_per_frame;
static uint16_t octets_per_frame;
static uint8_t num_bis = 1;
// lc3 encoder
static const lc3_encoder_t * lc3_encoder;
static lc3_encoder_ehima_t encoder_contexts[MAX_NUM_BIS];
static int16_t pcm[MAX_NUM_BIS * MAX_SAMPLES_PER_FRAME];
static uint32_t time_generation_ms;
// codec menu
static uint8_t menu_sampling_frequency;
static uint8_t menu_variant;
// mod player
static int hxcmod_initialized;
static modcontext mod_context;
static tracker_buffer_state trkbuf;
static int16_t mod_pcm[MAX_NUM_BIS * MAX_SAMPLES_PER_FRAME];
// sine generator
static uint8_t sine_step;
static uint16_t sine_phases[MAX_NUM_BIS];
// audio producer
static enum {
AUDIO_SOURCE_SINE,
AUDIO_SOURCE_MODPLAYER
} audio_source = AUDIO_SOURCE_MODPLAYER;
static enum {
APP_IDLE,
APP_W4_PERIODIC_ENABLED,
APP_CREATE_BIG,
APP_W4_CREATE_BIG_COMPLETE,
APP_SET_ISO_PATH,
APP_STREAMING
} app_state = APP_IDLE;
// enumerate default codec configs
static struct {
uint32_t samplingrate_hz;
uint8_t samplingrate_index;
uint8_t num_variants;
struct {
const char * name;
lc3_frame_duration_t frame_duration;
uint16_t octets_per_frame;
} variants[6];
} codec_configurations[] = {
{
8000, 0x01, 2,
{
{ "8_1", LC3_FRAME_DURATION_7500US, 26},
{ "8_2", LC3_FRAME_DURATION_10000US, 30}
}
},
{
16000, 0x03, 2,
{
{ "16_1", LC3_FRAME_DURATION_7500US, 30},
{ "16_2", LC3_FRAME_DURATION_10000US, 40}
}
},
{
24000, 0x05, 2,
{
{ "24_1", LC3_FRAME_DURATION_7500US, 45},
{ "24_2", LC3_FRAME_DURATION_10000US, 60}
}
},
{
32000, 0x06, 2,
{
{ "32_1", LC3_FRAME_DURATION_7500US, 60},
{ "32_2", LC3_FRAME_DURATION_10000US, 80}
}
},
{
44100, 0x07, 2,
{
{ "441_1", LC3_FRAME_DURATION_7500US, 97},
{ "441_2", LC3_FRAME_DURATION_10000US, 130}
}
},
{
48000, 0x08, 6,
{
{ "48_1", LC3_FRAME_DURATION_7500US, 75},
{ "48_2", LC3_FRAME_DURATION_10000US, 100},
{ "48_3", LC3_FRAME_DURATION_7500US, 90},
{ "48_4", LC3_FRAME_DURATION_10000US, 120},
{ "48_5", LC3_FRAME_DURATION_7500US, 117},
{ "48_6", LC3_FRAME_DURATION_10000US, 155}
}
},
};
static void show_usage(void);
static void print_config(void) {
printf("Config '%s_%u': %u, %s ms, %u octets - %s\n",
codec_configurations[menu_sampling_frequency].variants[menu_variant].name,
num_bis,
codec_configurations[menu_sampling_frequency].samplingrate_hz,
codec_configurations[menu_sampling_frequency].variants[menu_variant].frame_duration == LC3_FRAME_DURATION_7500US ? "7.5" : "10",
codec_configurations[menu_sampling_frequency].variants[menu_variant].octets_per_frame,
audio_source == AUDIO_SOURCE_SINE ? "Sine" : "Modplayer");
}
static void setup_lc3_encoder(void){
uint8_t channel;
for (channel = 0 ; channel < num_bis ; channel++){
lc3_encoder_ehima_t * context = &encoder_contexts[channel];
lc3_encoder = lc3_encoder_ehima_init_instance(context);
lc3_encoder->configure(context, sampling_frequency_hz, frame_duration);
}
number_samples_per_frame = lc3_encoder->get_number_samples_per_frame(&encoder_contexts[0]);
btstack_assert(number_samples_per_frame <= MAX_SAMPLES_PER_FRAME);
printf("LC3 Encoder config: %u hz, frame duration %s ms, num samples %u, num octets %u\n",
sampling_frequency_hz, frame_duration == LC3_FRAME_DURATION_7500US ? "7.5" : "10",
number_samples_per_frame, octets_per_frame);
}
static void setup_mod_player(void){
if (!hxcmod_initialized) {
hxcmod_initialized = hxcmod_init(&mod_context);
btstack_assert(hxcmod_initialized != 0);
}
hxcmod_unload(&mod_context);
hxcmod_setcfg(&mod_context, sampling_frequency_hz, 16, 1, 1, 1);
hxcmod_load(&mod_context, (void *) &mod_data, mod_len);
}
static void generate_audio(void){
uint32_t start_ms = btstack_run_loop_get_time_ms();
uint16_t sample;
switch (audio_source) {
case AUDIO_SOURCE_SINE:
// generate sine wave for all channels
for (sample = 0 ; sample < number_samples_per_frame ; sample++){
uint8_t channel;
for (channel = 0; channel < num_bis; channel++) {
int16_t value = sine_int16[sine_phases[channel]] / 4;
pcm[channel * MAX_SAMPLES_PER_FRAME + sample] = value;
sine_phases[channel] += sine_step * (1+channel); // second channel, double frequency
if (sine_phases[channel] >= (sizeof(sine_int16) / sizeof(int16_t))) {
sine_phases[channel] = 0;
}
}
}
break;
case AUDIO_SOURCE_MODPLAYER:
// mod player configured for stereo
hxcmod_fillbuffer(&mod_context, (unsigned short *) &mod_pcm[0], number_samples_per_frame, &trkbuf);
uint16_t i;
if (num_bis == 1){
// stereo -> mono
for (i=0;i<number_samples_per_frame;i++){
pcm[i] = (mod_pcm[2*i] / 2) + (mod_pcm[2*i+1] / 2);
}
} else {
// sort interleaved samples
for (i=0;i<number_samples_per_frame;i++){
pcm[i] = mod_pcm[2*i];
pcm[MAX_SAMPLES_PER_FRAME+i] = mod_pcm[2*i+1];
}
}
break;
default:
btstack_unreachable();
break;
}
time_generation_ms = btstack_run_loop_get_time_ms() - start_ms;
iso_frame_counter++;
}
static void encode_and_send(uint8_t bis_index){
#ifdef COUNT_MODE
if (bis_index == 0) {
uint32_t now = btstack_run_loop_get_time_ms();
if (send_last_ms != 0) {
uint16_t send_interval_ms = now - send_last_ms;
if (send_interval_ms >= MAX_PACKET_INTERVAL_BINS_MS) {
printf("ERROR: send interval %u\n", send_interval_ms);
} else {
send_time_bins[send_interval_ms]++;
}
}
send_last_ms = now;
}
#endif
bool ok = hci_reserve_packet_buffer();
btstack_assert(ok);
uint8_t * buffer = hci_get_outgoing_packet_buffer();
// complete SDU, no TimeStamp
little_endian_store_16(buffer, 0, bis_con_handles[bis_index] | (2 << 12));
// len
little_endian_store_16(buffer, 2, 0 + 4 + octets_per_frame);
// TimeStamp if TS flag is set
// packet seq nr
little_endian_store_16(buffer, 4, packet_sequence_numbers[bis_index]);
// iso sdu len
little_endian_store_16(buffer, 6, octets_per_frame);
#ifdef COUNT_MODE
// test data: bis_index, counter
buffer[8] = bis_index;
memset(&buffer[9], iso_frame_counter, octets_per_frame - 1);
#else
// encode as lc3
lc3_encoder->encode(&encoder_contexts[bis_index], &pcm[bis_index * MAX_SAMPLES_PER_FRAME], &buffer[8], octets_per_frame);
#endif
// send
hci_send_iso_packet_buffer(4 + 0 + 4 + octets_per_frame);
if (((packet_sequence_numbers[bis_index] & 0x7f) == 0) && (bis_index == 0)) {
printf("Encoding time: %u\n", time_generation_ms);
}
if ((packet_sequence_numbers[bis_index] & 0x7c) == 0){
printf("%04x %10u %u ", packet_sequence_numbers[bis_index], btstack_run_loop_get_time_ms(), bis_index);
printf_hexdump(&buffer[8], octets_per_frame);
}
packet_sequence_numbers[bis_index]++;
}
static void try_send(void){
bool all_can_send = true;
uint8_t i;
for (i=0; i<num_bis;i++) {
all_can_send &= bis_can_send[i];
}
#ifdef PTS_MODE
static uint8_t next_sender;
// PTS 8.2 sends a packet after the previous one was received -> it sends at half speed for stereo configuration
if (all_can_send) {
if (next_sender == 0) {
generate_audio();
}
bis_can_send[next_sender] = false;
encode_and_send(next_sender);
next_sender = (num_bis - 1) - next_sender;
}
#else
#ifdef GENERATE_AUDIO_WITH_TIMER
for (i=0;i<num_bis;i++){
if (hci_is_packet_buffer_reserved()) return;
if (bis_has_data[i]){
bis_can_send[i] = false;
bis_has_data[i] = false;
encode_and_send(i);
return;
}
}
#else
// check if next audio frame should be produced and send
if (all_can_send){
generate_audio();
for (i=0; i<num_bis;i++) {
bis_has_data[i] = true;
}
}
for (i=0;i<num_bis;i++){
if (hci_is_packet_buffer_reserved()) return;
if (bis_can_send[i] && bis_has_data[i]){
bis_can_send[i] = false;
bis_has_data[i] = false;
encode_and_send(i);
return;
}
}
#endif
#endif
}
#ifdef GENERATE_AUDIO_WITH_TIMER
static void generate_audio_timer_handler(btstack_timer_source_t *ts){
generate_audio();
uint8_t i;
for (i=0; i<num_bis;i++) {
bis_has_data[i] = true;
}
// next send time based on frame_duration_us
next_send_time_additional_us += frame_duration_us % 1000;
if (next_send_time_additional_us > 1000){
next_send_time_ms++;
next_send_time_additional_us -= 1000;
}
next_send_time_ms += frame_duration_us / 1000;
uint32_t now = btstack_run_loop_get_time_ms();
btstack_run_loop_set_timer(&send_timer, next_send_time_ms - now);
btstack_run_loop_add_timer(&send_timer);
try_send();
}
#endif
static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
UNUSED(channel);
if (packet_type != HCI_EVENT_PACKET) return;
switch (packet[0]) {
case BTSTACK_EVENT_STATE:
switch(btstack_event_state_get_state(packet)) {
case HCI_STATE_WORKING:
show_usage();
printf("Please select sample frequency and variation, then start broadcast\n");
break;
case HCI_STATE_OFF:
printf("Goodbye\n");
exit(0);
break;
default:
break;
}
break;
case HCI_EVENT_COMMAND_COMPLETE:
switch (hci_event_command_complete_get_command_opcode(packet)){
case HCI_OPCODE_HCI_LE_SET_PERIODIC_ADVERTISING_ENABLE:
if (app_state != APP_W4_PERIODIC_ENABLED) break;
app_state = APP_CREATE_BIG;
break;
case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH:
next_bis_index++;
if (next_bis_index == num_bis){
printf("%u ISO path(s) set up\n", num_bis);
// ready to send
uint8_t i;
for (i=0;i<num_bis;i++) {
bis_can_send[i] = true;
}
app_state = APP_STREAMING;
//
#ifdef GENERATE_AUDIO_WITH_TIMER
btstack_run_loop_set_timer_handler(&send_timer, &generate_audio_timer_handler);
uint32_t next_send_time_ms = btstack_run_loop_get_time_ms() + 10;
uint32_t now = btstack_run_loop_get_time_ms();
btstack_run_loop_set_timer(&send_timer, next_send_time_ms - now);
btstack_run_loop_add_timer(&send_timer);
#endif
}
break;
}
break;
case HCI_EVENT_LE_META:
switch(hci_event_le_meta_get_subevent_code(packet)){
case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
if (app_state == APP_W4_CREATE_BIG_COMPLETE){
uint8_t i;
printf("BIS Connection Handles: ");
for (i=0;i<num_bis;i++){
bis_con_handles[i] = little_endian_read_16(packet, 21 + 2*i);
printf("0x%04x ", bis_con_handles[i]);
}
printf("\n");
next_bis_index = 0;
app_state = APP_SET_ISO_PATH;
printf("Start streaming\n");
}
break;
default:
break;
}
break;
case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
if (size >= 3){
uint16_t num_handles = packet[2];
if (size != (3u + num_handles * 4u)) break;
uint16_t offset = 3;
uint16_t i;
for (i=0; i<num_handles;i++) {
hci_con_handle_t handle = little_endian_read_16(packet, offset) & 0x0fffu;
offset += 2u;
uint16_t num_packets = little_endian_read_16(packet, offset);
offset += 2u;
uint8_t j;
for (j=0 ; j<num_bis ; j++){
if (handle == bis_con_handles[j]){
// allow to send
bis_can_send[j] = true;
}
}
}
}
break;
default:
break;
}
const uint8_t broadcast_code[16] = { 0 };
switch(app_state){
case APP_CREATE_BIG:
if (hci_can_send_command_packet_now()) {
app_state = APP_W4_CREATE_BIG_COMPLETE;
if (sampling_frequency_hz == 44100){
framed_pdus = 1;
// same config as for 48k -> frame is longer by 48/44.1
frame_duration_us = frame_duration == LC3_FRAME_DURATION_7500US ? 8163 : 10884;
} else {
framed_pdus = 0;
frame_duration_us = frame_duration == LC3_FRAME_DURATION_7500US ? 7500 : 10000;
}
hci_send_cmd(&hci_le_create_big, 0, adv_handle, num_bis, frame_duration_us, octets_per_frame, 0x1F, 2, 2, 0, framed_pdus, 0, broadcast_code);
}
break;
case APP_SET_ISO_PATH:
if (!hci_can_send_command_packet_now()) break;
hci_send_cmd(&hci_le_setup_iso_data_path, bis_con_handles[next_bis_index], 0, 0, 0, 0, 0, 0, 0, NULL);
break;
default:
break;
}
try_send();
}
static void show_usage(void){
printf("\n--- LE Audio Broadcast Source Test Console ---\n");
print_config();
printf("---\n");
printf("c - toggle channels\n");
printf("f - next sampling frequency\n");
printf("v - next codec variant\n");
printf("t - toggle sine / modplayer\n");
printf("s - start broadcast\n");
printf("x - shutdown\n");
printf("---\n");
}
static void stdin_process(char c){
switch (c){
case 'c':
if (app_state != APP_IDLE){
printf("Codec configuration can only be changed in idle state\n");
break;
}
num_bis = 3 - num_bis;
print_config();
break;
case 'f':
if (app_state != APP_IDLE){
printf("Codec configuration can only be changed in idle state\n");
break;
}
menu_sampling_frequency++;
if (menu_sampling_frequency >= 6){
menu_sampling_frequency = 0;
}
if (menu_variant >= codec_configurations[menu_sampling_frequency].num_variants){
menu_variant = 0;
}
print_config();
break;
case 'v':
if (app_state != APP_IDLE){
printf("Codec configuration can only be changed in idle state\n");
break;
}
menu_variant++;
if (menu_variant >= codec_configurations[menu_sampling_frequency].num_variants){
menu_variant = 0;
}
print_config();
break;
case 'x':
#ifdef COUNT_MODE
printf("Send statistic:\n");
{
uint16_t i;
for (i=0;i<MAX_PACKET_INTERVAL_BINS_MS;i++){
printf("%2u: %5u\n", i, send_time_bins[i]);
}
}
#endif
printf("Shutdown...\n");
hci_power_control(HCI_POWER_OFF);
break;
case 's':
if (app_state != APP_IDLE){
printf("Cannot start broadcast - not in idle state\n");
break;
}
// use values from table
sampling_frequency_hz = codec_configurations[menu_sampling_frequency].samplingrate_hz;
octets_per_frame = codec_configurations[menu_sampling_frequency].variants[menu_variant].octets_per_frame;
frame_duration = codec_configurations[menu_sampling_frequency].variants[menu_variant].frame_duration;
// get num samples per frame
setup_lc3_encoder();
// update BASEs
periodic_adv_data_1[17] = codec_configurations[menu_sampling_frequency].samplingrate_index;
periodic_adv_data_1[20] = (frame_duration == LC3_FRAME_DURATION_7500US) ? 0 : 1;
little_endian_store_16(periodic_adv_data_1, 23, octets_per_frame);
periodic_adv_data_2[17] = codec_configurations[menu_sampling_frequency].samplingrate_index;
periodic_adv_data_2[20] = (frame_duration == LC3_FRAME_DURATION_7500US) ? 0 : 1;
little_endian_store_16(periodic_adv_data_2, 23, octets_per_frame);
// setup mod player
setup_mod_player();
// setup sine generator
if (sampling_frequency_hz == 44100){
sine_step = 2;
} else {
sine_step = 96000 / sampling_frequency_hz;
}
// setup
app_state = APP_W4_PERIODIC_ENABLED;
gap_extended_advertising_setup(&le_advertising_set, &extended_params, &adv_handle);
gap_extended_advertising_set_adv_data(adv_handle, sizeof(extended_adv_data), extended_adv_data);
gap_periodic_advertising_set_params(adv_handle, &periodic_params);
switch(num_bis){
case 1:
gap_periodic_advertising_set_data(adv_handle, sizeof(periodic_adv_data_1), periodic_adv_data_1);
printf("BASE: ");
printf_hexdump(periodic_adv_data_1, sizeof(periodic_adv_data_1));
break;
case 2:
gap_periodic_advertising_set_data(adv_handle, sizeof(periodic_adv_data_2), periodic_adv_data_2);
printf("BASE: ");
printf_hexdump(periodic_adv_data_2, sizeof(periodic_adv_data_2));
break;
default:
btstack_unreachable();
break;
}
gap_periodic_advertising_start(adv_handle, 0);
gap_extended_advertising_start(adv_handle, 0, 0);
break;
case 't':
audio_source = 1 - audio_source;
print_config();
break;
case '\n':
case '\r':
break;
default:
show_usage();
break;
}
}
int btstack_main(int argc, const char * argv[]);
int btstack_main(int argc, const char * argv[]){
(void) argv;
(void) argc;
// register for HCI events
hci_event_callback_registration.callback = &packet_handler;
hci_add_event_handler(&hci_event_callback_registration);
// turn on!
hci_power_control(HCI_POWER_ON);
btstack_stdin_setup(stdin_process);
return 0;
}

235
test/le_audio/main.c Normal file
View File

@ -0,0 +1,235 @@
/*
* Copyright (C) 2014 BlueKitchen GmbH
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* 4. Any redistribution, use, or modification is done solely for
* personal benefit and not for any commercial purpose or for
* monetary gain.
*
* THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
* GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Please inquire about commercial licensing options at
* contact@bluekitchen-gmbh.com
*
*/
#define BTSTACK_FILE__ "main.c"
// *****************************************************************************
//
// minimal setup for HCI code
//
// *****************************************************************************
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include "btstack_config.h"
#include "ble/le_device_db_tlv.h"
#include "bluetooth_company_id.h"
#include "btstack_audio.h"
#include "btstack_debug.h"
#include "btstack_event.h"
#include "btstack_memory.h"
#include "btstack_run_loop.h"
#include "btstack_run_loop_posix.h"
#include "btstack_signal.h"
#include "btstack_stdin.h"
#include "btstack_tlv_posix.h"
#include "btstack_uart.h"
#include "classic/btstack_link_key_db_tlv.h"
#include "hci.h"
#include "hci_dump.h"
#include "hci_dump_posix_fs.h"
#include "hci_transport.h"
#include "hci_transport_h4.h"
#define TLV_DB_PATH_PREFIX "/tmp/btstack_"
#define TLV_DB_PATH_POSTFIX ".tlv"
static char tlv_db_path[100];
static const btstack_tlv_t * tlv_impl;
static btstack_tlv_posix_t tlv_context;
static bd_addr_t local_addr;
static int is_bcm;
// shutdown
static bool shutdown_triggered;
int btstack_main(int argc, const char * argv[]);
static void local_version_information_handler(uint8_t * packet);
static hci_transport_config_uart_t config = {
HCI_TRANSPORT_CONFIG_UART,
115200,
0, // main baudrate
1, // flow control
NULL,
};
static btstack_packet_callback_registration_t hci_event_callback_registration;
static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
if (packet_type != HCI_EVENT_PACKET) return;
switch (hci_event_packet_get_type(packet)){
case BTSTACK_EVENT_STATE:
switch(btstack_event_state_get_state(packet)){
case HCI_STATE_WORKING:
gap_local_bd_addr(local_addr);
printf("BTstack up and running on %s.\n", bd_addr_to_str(local_addr));
strcpy(tlv_db_path, TLV_DB_PATH_PREFIX);
strcat(tlv_db_path, bd_addr_to_str(local_addr));
strcat(tlv_db_path, TLV_DB_PATH_POSTFIX);
tlv_impl = btstack_tlv_posix_init_instance(&tlv_context, tlv_db_path);
btstack_tlv_set_instance(tlv_impl, &tlv_context);
#ifdef ENABLE_CLASSIC
hci_set_link_key_db(btstack_link_key_db_tlv_get_instance(tlv_impl, &tlv_context));
#endif
#ifdef ENABLE_BLE
le_device_db_tlv_configure(tlv_impl, &tlv_context);
#endif
break;
case HCI_STATE_OFF:
btstack_tlv_posix_deinit(&tlv_context);
if (!shutdown_triggered) break;
// reset stdin
btstack_stdin_reset();
log_info("Good bye, see you.\n");
exit(0);
break;
default:
break;
}
break;
case HCI_EVENT_COMMAND_COMPLETE:
if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
if (hci_event_command_complete_get_return_parameters(packet)[0]) break;
// terminate, name 248 chars
packet[6+248] = 0;
printf("Local name: %s\n", &packet[6]);
}
if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
local_version_information_handler(packet);
}
break;
default:
break;
}
}
static void trigger_shutdown(void){
printf("CTRL-C - SIGINT received, shutting down..\n");
log_info("sigint_handler: shutting down");
shutdown_triggered = true;
hci_power_control(HCI_POWER_OFF);
}
static int led_state = 0;
void hal_led_toggle(void){
led_state = 1 - led_state;
printf("LED State %u\n", led_state);
}
static void local_version_information_handler(uint8_t * packet){
printf("Local version information:\n");
uint16_t hci_version = packet[6];
uint16_t hci_revision = little_endian_read_16(packet, 7);
uint16_t lmp_version = packet[9];
uint16_t manufacturer = little_endian_read_16(packet, 10);
uint16_t lmp_subversion = little_endian_read_16(packet, 12);
printf("- HCI Version 0x%04x\n", hci_version);
printf("- HCI Revision 0x%04x\n", hci_revision);
printf("- LMP Version 0x%04x\n", lmp_version);
printf("- LMP Subversion 0x%04x\n", lmp_subversion);
printf("- Manufacturer 0x%04x\n", manufacturer);
switch (manufacturer){
case BLUETOOTH_COMPANY_ID_PACKETCRAFT_INC:
printf("PacketCraft HCI Controller\n");
break;
default:
printf("Unknown manufacturer / manufacturer not supported yet.\n");
break;
}
}
int main(int argc, const char * argv[]){
/// GET STARTED with BTstack ///
btstack_memory_init();
btstack_run_loop_init(btstack_run_loop_posix_get_instance());
// pre-select serial device
config.device_name = "/dev/tty.usbmodemD5D5237DC25B1"; // BL654 with PTS Firmware
// accept path from command line
bool second_device = false;
if (argc >= 3 && strcmp(argv[1], "-u") == 0){
config.device_name = argv[2];
second_device = true;
argc -= 2;
memmove(&argv[1], &argv[3], (argc-1) * sizeof(char *));
}
printf("H4 device: %s\n", config.device_name);
// log into file using HCI_DUMP_BTSNOOP format
char * pklg_path = "/tmp/hci_dump.btsnoop";
if (second_device){
pklg_path = "/tmp/hci_dump2.btsnoop";
}
hci_dump_posix_fs_open(pklg_path, HCI_DUMP_BTSNOOP);
const hci_dump_t * hci_dump_impl = hci_dump_posix_fs_get_instance();
hci_dump_init(hci_dump_impl);
printf("Packet Log: %s\n", pklg_path);
// init HCI
const btstack_uart_t * uart_driver = btstack_uart_posix_instance();
const hci_transport_t * transport = hci_transport_h4_instance_for_uart(uart_driver);
hci_init(transport, (void*) &config);
#ifdef HAVE_PORTAUDIO
btstack_audio_sink_set_instance(btstack_audio_portaudio_sink_get_instance());
btstack_audio_source_set_instance(btstack_audio_portaudio_source_get_instance());
#endif
// inform about BTstack state
hci_event_callback_registration.callback = &packet_handler;
hci_add_event_handler(&hci_event_callback_registration);
// register callback for CTRL-c
btstack_signal_register_callback(SIGINT, &trigger_shutdown);
// setup app
btstack_main(argc, argv);
// go
btstack_run_loop_execute();
return 0;
}