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