xref: /btstack/test/le_audio/le_audio_broadcast_source.c (revision 8b6f0b06f217772ac951dd39e5fdd5e40378da3d)
1 /*
2  * Copyright (C) 2022 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 MATTHIAS
24  * RINGWALD 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__ "le_audio_broadcast_source.c"
39 
40 /*
41  * LE Audio Broadcast Source
42  */
43 
44 #include <stdint.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <btstack_debug.h>
48 
49 #include "bluetooth_data_types.h"
50 #include "btstack_stdin.h"
51 #include "btstack_event.h"
52 #include "btstack_run_loop.h"
53 #include "gap.h"
54 #include "hci.h"
55 #include "hci_cmd.h"
56 #include "hci_dump.h"
57 #include "btstack_lc3.h"
58 #include "btstack_lc3_google.h"
59 #include "le-audio/le_audio_base_builder.h"
60 
61 #include "hxcmod.h"
62 #include "mods/mod.h"
63 #include "le_audio_demo_util_source.h"
64 
65 // PTS mode
66 // #define PTS_MODE
67 
68 // Count mode - send packet count as test data for manual analysis
69 // #define COUNT_MODE
70 
71 // max config
72 #define MAX_NUM_BIS 2
73 #define MAX_SAMPLES_PER_FRAME 480
74 #define MAX_LC3_FRAME_BYTES   155
75 
76 static const uint8_t adv_sid = 0;
77 
78 static le_advertising_set_t le_advertising_set;
79 
80 static le_extended_advertising_parameters_t extended_params = {
81         .advertising_event_properties = 0,
82         .primary_advertising_interval_min = 0x4b0, // 750 ms
83         .primary_advertising_interval_max = 0x4b0, // 750 ms
84         .primary_advertising_channel_map = 7,
85         .own_address_type = BD_ADDR_TYPE_LE_PUBLIC,
86         .peer_address_type = 0,
87         .peer_address =  { 0 },
88         .advertising_filter_policy = 0,
89         .advertising_tx_power = 10, // 10 dBm
90         .primary_advertising_phy = 1, // LE 1M PHY
91         .secondary_advertising_max_skip = 0,
92         .secondary_advertising_phy = 1, // LE 1M PHY
93         .advertising_sid = adv_sid,
94         .scan_request_notification_enable = 0,
95 };
96 
97 // Random Broadcast ID, valid for lifetime of BIG
98 #define BROADCAST_ID (0x112233u)
99 
100 static const uint8_t extended_adv_data[] = {
101         // 16 bit service data, ORG_BLUETOOTH_SERVICE_BASIC_AUDIO_ANNOUNCEMENT_SERVICE, Broadcast ID
102         6, BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID, 0x52, 0x18,
103         BROADCAST_ID >> 16,
104         (BROADCAST_ID >> 8) & 0xff,
105         BROADCAST_ID & 0xff,
106         // name
107 #ifdef PTS_MODE
108         7, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'P', 'T', 'S', '-', 'x', 'x'
109 #elif defined(COUNT_MODE)
110         6, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'C', 'O', 'U', 'N', 'T'
111 #else
112         7, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'S', 'o', 'u', 'r', 'c', 'e'
113 #endif
114 };
115 
116 static const le_periodic_advertising_parameters_t periodic_params = {
117         .periodic_advertising_interval_min = 0x258, // 375 ms
118         .periodic_advertising_interval_max = 0x258, // 375 ms
119         .periodic_advertising_properties = 0
120 };
121 
122 static bd_addr_t remote;
123 static const char * remote_addr_string = "00:1B:DC:08:E2:72";
124 
125 static btstack_packet_callback_registration_t hci_event_callback_registration;
126 static uint8_t period_adv_data[255];
127 static uint16_t period_adv_data_len;
128 
129 static uint8_t adv_handle = 0;
130 static unsigned int     next_bis_index;
131 static hci_con_handle_t bis_con_handles[MAX_NUM_BIS];
132 static uint16_t packet_sequence_numbers[MAX_NUM_BIS];
133 static uint8_t framed_pdus;
134 static bool bis_can_send[MAX_NUM_BIS];
135 static bool bis_has_data[MAX_NUM_BIS];
136 static uint8_t iso_frame_counter;
137 static uint16_t frame_duration_us;
138 
139 static le_audio_big_t big_storage;
140 static le_audio_big_params_t big_params;
141 
142 // time stamping
143 #ifdef COUNT_MODE
144 #define MAX_PACKET_INTERVAL_BINS_MS 50
145 static uint32_t send_time_bins[MAX_PACKET_INTERVAL_BINS_MS];
146 static uint32_t send_last_ms;
147 #endif
148 
149 // lc3 codec config
150 static uint16_t sampling_frequency_hz;
151 static btstack_lc3_frame_duration_t frame_duration;
152 static uint16_t number_samples_per_frame;
153 static uint16_t octets_per_frame;
154 static uint8_t  num_bis = 1;
155 
156 // codec menu
157 static uint8_t menu_sampling_frequency;
158 static uint8_t menu_variant;
159 
160 // encryption
161 static uint8_t encryption = 0;
162 static uint8_t broadcast_code [] = {0x01, 0x02, 0x68, 0x05, 0x53, 0xF1, 0x41, 0x5A, 0xA2, 0x65, 0xBB, 0xAF, 0xC6, 0xEA, 0x03, 0xB8, };
163 
164 // audio producer
165 static le_audio_demo_source_generator audio_source = AUDIO_SOURCE_MODPLAYER;
166 
167 static enum {
168     APP_IDLE,
169     APP_W4_CREATE_BIG_COMPLETE,
170     APP_STREAMING,
171 } app_state = APP_IDLE;
172 
173 // enumerate default codec configs
174 static struct {
175     uint16_t samplingrate_hz;
176     uint8_t  samplingrate_index;
177     uint8_t  num_variants;
178     struct {
179         const char * name;
180         btstack_lc3_frame_duration_t frame_duration;
181         uint16_t octets_per_frame;
182     } variants[6];
183 } codec_configurations[] = {
184     {
185         8000, 0x01, 2,
186         {
187             {  "8_1",  BTSTACK_LC3_FRAME_DURATION_7500US, 26},
188             {  "8_2", BTSTACK_LC3_FRAME_DURATION_10000US, 30}
189         }
190     },
191     {
192        16000, 0x03, 2,
193        {
194             {  "16_1",  BTSTACK_LC3_FRAME_DURATION_7500US, 30},
195             {  "16_2", BTSTACK_LC3_FRAME_DURATION_10000US, 40}
196        }
197     },
198     {
199         24000, 0x05, 2,
200         {
201             {  "24_1",  BTSTACK_LC3_FRAME_DURATION_7500US, 45},
202             {  "24_2", BTSTACK_LC3_FRAME_DURATION_10000US, 60}
203        }
204     },
205     {
206         32000, 0x06, 2,
207         {
208             {  "32_1",  BTSTACK_LC3_FRAME_DURATION_7500US, 60},
209             {  "32_2", BTSTACK_LC3_FRAME_DURATION_10000US, 80}
210         }
211     },
212     {
213         44100, 0x07, 2,
214         {
215             { "441_1",  BTSTACK_LC3_FRAME_DURATION_7500US,  97},
216             { "441_2", BTSTACK_LC3_FRAME_DURATION_10000US, 130}
217         }
218     },
219     {
220         48000, 0x08, 6,
221         {
222             {  "48_1", BTSTACK_LC3_FRAME_DURATION_7500US, 75},
223             {  "48_2", BTSTACK_LC3_FRAME_DURATION_10000US, 100},
224             {  "48_3", BTSTACK_LC3_FRAME_DURATION_7500US, 90},
225             {  "48_4", BTSTACK_LC3_FRAME_DURATION_10000US, 120},
226             {  "48_5", BTSTACK_LC3_FRAME_DURATION_7500US, 117},
227             {  "48_6", BTSTACK_LC3_FRAME_DURATION_10000US, 155}
228         }
229     },
230 };
231 
232 static void show_usage(void);
233 
234 static void print_config(void) {
235     printf("Config '%s_%u': %u, %s ms, %u octets - %s%s\n",
236            codec_configurations[menu_sampling_frequency].variants[menu_variant].name,
237            num_bis,
238            codec_configurations[menu_sampling_frequency].samplingrate_hz,
239            codec_configurations[menu_sampling_frequency].variants[menu_variant].frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? "7.5" : "10",
240            codec_configurations[menu_sampling_frequency].variants[menu_variant].octets_per_frame,
241            audio_source == AUDIO_SOURCE_SINE ? "Sine" : "Modplayer", encryption ? " (encrypted)" : "");
242 }
243 
244 static void setup_advertising() {
245     bd_addr_t local_addr;
246     gap_local_bd_addr(local_addr);
247     bool local_address_invalid = btstack_is_null_bd_addr( local_addr );
248     if( local_address_invalid ) {
249         extended_params.own_address_type = BD_ADDR_TYPE_LE_RANDOM;
250     }
251     gap_extended_advertising_setup(&le_advertising_set, &extended_params, &adv_handle);
252     if( local_address_invalid ) {
253         bd_addr_t random_address = { 0xC1, 0x01, 0x01, 0x01, 0x01, 0x01 };
254         gap_extended_advertising_set_random_address( adv_handle, random_address );
255     }
256     gap_extended_advertising_set_adv_data(adv_handle, sizeof(extended_adv_data), extended_adv_data);
257     gap_periodic_advertising_set_params(adv_handle, &periodic_params);
258     gap_periodic_advertising_set_data(adv_handle, period_adv_data_len, period_adv_data);
259     gap_periodic_advertising_start(adv_handle, 0);
260     gap_extended_advertising_start(adv_handle, 0, 0);
261 }
262 
263 static void setup_big(void){
264     // Create BIG
265     big_params.big_handle = 0;
266     big_params.advertising_handle = adv_handle;
267     big_params.num_bis = num_bis;
268     big_params.max_sdu = octets_per_frame;
269     big_params.max_transport_latency_ms = 31;
270     big_params.rtn = 2;
271     big_params.phy = 2;
272     big_params.packing = 0;
273     big_params.encryption = encryption;
274     if (encryption) {
275         memcpy(big_params.broadcast_code, &broadcast_code[0], 16);
276     } else {
277         memset(big_params.broadcast_code, 0, 16);
278     }
279     if (sampling_frequency_hz == 44100){
280         // same config as for 48k -> frame is longer by 48/44.1
281         big_params.sdu_interval_us = frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? 8163 : 10884;
282         big_params.framing = 1;
283     } else {
284         big_params.sdu_interval_us = frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? 7500 : 10000;
285         big_params.framing = 0;
286     }
287     app_state = APP_W4_CREATE_BIG_COMPLETE;
288     gap_big_create(&big_storage, &big_params);
289 }
290 
291 
292 static void start_broadcast() {// use values from table
293     sampling_frequency_hz = codec_configurations[menu_sampling_frequency].samplingrate_hz;
294     octets_per_frame      = codec_configurations[menu_sampling_frequency].variants[menu_variant].octets_per_frame;
295     frame_duration        = codec_configurations[menu_sampling_frequency].variants[menu_variant].frame_duration;
296 
297     number_samples_per_frame = btstack_lc3_samples_per_frame(sampling_frequency_hz, frame_duration);
298 
299     printf("LC3 Encoder config: %u hz, frame duration %s ms, num samples %u, num octets %u\n",
300            sampling_frequency_hz, frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? "7.5" : "10",
301            number_samples_per_frame, octets_per_frame);
302 
303     le_audio_demo_util_source_configure(num_bis, 1, sampling_frequency_hz, frame_duration, octets_per_frame);
304     le_audio_demo_util_source_generate_iso_frame(audio_source);
305 
306     // setup base
307     uint8_t codec_id[] = { 0x06, 0x00, 0x00, 0x00, 0x00 };
308     uint8_t subgroup_codec_specific_configuration[] = {
309             0x02, 0x01, 0x01,
310             0x02, 0x02, 0x01,
311             0x03, 0x04, 0x1E, 0x00,
312     };
313     subgroup_codec_specific_configuration[2] = codec_configurations[menu_sampling_frequency].samplingrate_index;
314     subgroup_codec_specific_configuration[5] =  (frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US) ? 0 : 1;;
315     uint8_t subgroup_metadata[] = {
316             0x03, 0x02, 0x04, 0x00, // Metadata[i]
317     };
318     little_endian_store_16(subgroup_codec_specific_configuration, 8, octets_per_frame);
319     uint8_t bis_codec_specific_configuration_1[] = {
320             0x05, 0x03, 0x01, 0x00, 0x00, 0x00
321     };
322     uint8_t bis_codec_specific_configuration_2[] = {
323             0x05, 0x03, 0x02, 0x00, 0x00, 0x00
324     };
325     le_audio_base_builder_t builder;
326     le_audio_base_builder_init(&builder, period_adv_data, sizeof(period_adv_data), 40);
327     le_audio_base_builder_add_subgroup(&builder, codec_id,
328                                        sizeof(subgroup_codec_specific_configuration),
329                                        subgroup_codec_specific_configuration,
330                                        sizeof(subgroup_metadata), subgroup_metadata);
331     le_audio_base_builder_add_bis(&builder, 1, sizeof(bis_codec_specific_configuration_1),
332                                   bis_codec_specific_configuration_1);
333     if (num_bis == 2){
334         le_audio_base_builder_add_bis(&builder, 2, sizeof(bis_codec_specific_configuration_2),
335                                       bis_codec_specific_configuration_2);
336     }
337     period_adv_data_len = le_audio_base_builder_get_ad_data_size(&builder);
338 
339     // setup extended and periodic advertising
340     setup_advertising();
341 
342     // setup big
343     setup_big();
344 }
345 
346 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
347     UNUSED(channel);
348     if (packet_type != HCI_EVENT_PACKET) return;
349     uint8_t bis_index;
350 
351     switch (packet[0]) {
352         case BTSTACK_EVENT_STATE:
353             switch(btstack_event_state_get_state(packet)) {
354                 case HCI_STATE_WORKING:
355 #ifdef ENABLE_DEMO_MODE
356                     // start broadcast automatically, mod player, 48_5_1
357                     num_bis = 1;
358                     menu_sampling_frequency = 5;
359                     menu_variant = 4;
360                     start_broadcast();
361 #else
362                     show_usage();
363                     printf("Please select sample frequency and variation, then start broadcast\n");
364 #endif
365                     break;
366                 case HCI_STATE_OFF:
367                     printf("Goodbye\n");
368                     exit(0);
369                     break;
370                 default:
371                     break;
372             }
373             break;
374         case HCI_EVENT_META_GAP:
375             switch (hci_event_gap_meta_get_subevent_code(packet)){
376                 case GAP_SUBEVENT_BIG_CREATED:
377                     printf("BIG Created with BIS Connection handles: \n");
378                     for (bis_index=0;bis_index<num_bis;bis_index++){
379                         bis_con_handles[bis_index] = gap_subevent_big_created_get_bis_con_handles(packet, bis_index);
380                         printf("0x%04x ", bis_con_handles[bis_index]);
381                     }
382 
383                     app_state = APP_STREAMING;
384                     printf("Start streaming\n");
385                     hci_request_bis_can_send_now_events(big_params.big_handle);
386                     break;
387                 default:
388                     break;
389             }
390             break;
391         case HCI_EVENT_BIS_CAN_SEND_NOW:
392             bis_index = hci_event_bis_can_send_now_get_bis_index(packet);
393             le_audio_demo_util_source_send(bis_index, bis_con_handles[bis_index]);
394             bis_index++;
395             if (bis_index == num_bis){
396                 le_audio_demo_util_source_generate_iso_frame(audio_source);
397                 hci_request_bis_can_send_now_events(big_params.big_handle);
398             }
399             break;
400         default:
401             break;
402     }
403 }
404 
405 static void show_usage(void){
406     printf("\n--- LE Audio Broadcast Source Test Console ---\n");
407     print_config();
408     printf("---\n");
409     printf("c - toggle channels\n");
410     printf("e - toggle encryption\n");
411     printf("f - next sampling frequency\n");
412     printf("v - next codec variant\n");
413     printf("t - toggle sine / modplayer\n");
414     printf("s - start broadcast\n");
415     printf("---\n");
416 }
417 static void stdin_process(char c){
418     switch (c){
419         case 'c':
420             if (app_state != APP_IDLE){
421                 printf("Codec configuration can only be changed in idle state\n");
422                 break;
423             }
424             num_bis = 3 - num_bis;
425             print_config();
426             break;
427         case 'e':
428             if (app_state != APP_IDLE){
429                 printf("Encryption can only be changed in idle state\n");
430                 break;
431             }
432             encryption = 1 - encryption;
433             print_config();
434             break;
435         case 'f':
436             if (app_state != APP_IDLE){
437                 printf("Codec configuration can only be changed in idle state\n");
438                 break;
439             }
440             menu_sampling_frequency++;
441             if (menu_sampling_frequency >= 6){
442                 menu_sampling_frequency = 0;
443             }
444             if (menu_variant >= codec_configurations[menu_sampling_frequency].num_variants){
445                 menu_variant = 0;
446             }
447             print_config();
448             break;
449         case 'v':
450             if (app_state != APP_IDLE){
451                 printf("Codec configuration can only be changed in idle state\n");
452                 break;
453             }
454             menu_variant++;
455             if (menu_variant >= codec_configurations[menu_sampling_frequency].num_variants){
456                 menu_variant = 0;
457             }
458             print_config();
459             break;
460         case 's':
461             if (app_state != APP_IDLE){
462                 printf("Cannot start broadcast - not in idle state\n");
463                 break;
464             }
465             start_broadcast();
466             break;
467         case 't':
468             audio_source = 1 - audio_source;
469             print_config();
470             break;
471         case '\n':
472         case '\r':
473             break;
474         default:
475             show_usage();
476             break;
477     }
478 }
479 
480 int btstack_main(int argc, const char * argv[]);
481 int btstack_main(int argc, const char * argv[]){
482     (void) argv;
483     (void) argc;
484 
485     // register for HCI events
486     hci_event_callback_registration.callback = &packet_handler;
487     hci_add_event_handler(&hci_event_callback_registration);
488 
489     // setup audio processing
490     le_audio_demo_util_source_init();
491 
492     // turn on!
493     hci_power_control(HCI_POWER_ON);
494 
495     btstack_stdin_setup(stdin_process);
496     return 0;
497 }
498