SuperTinyKernel™ RTOS 1.08.x
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
audio_mic/main.cpp
Go to the documentation of this file.
1/*
2 * The MIT License (MIT)
3 *
4 * Copyright (c) 2020 Reinhard Panhuber
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 */
25
31
32/* plot_audio_samples.py requires following modules:
33 * $ sudo apt install libportaudio
34 * $ pip3 install sounddevice matplotlib
35 *
36 * Then run
37 * $ python3 plot_audio_samples.py
38 */
39
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43
44#include "bsp/board_api.h"
45#include "tusb.h"
46
47// Converted to STK's native C++ API: task control blocks, kernel instance and
48// scheduling strategy are now expressed via templates instead of the STK_C_KERNEL_TYPE_CPU_0
49// stk_config.h setting + stk_c.h factory functions. Single <stk.h> include, same as example.cpp.
50#include "stk.h"
51
52// STK has no built-in equivalent of FreeRTOS's configMINIMAL_STACK_SIZE (stack sizes are always
53// caller-supplied, in words of stk::Word, via the Task<> template's _StackSize parameter) -
54// pick a baseline here and size up per task below. Adjust for your target/toolchain.
55#define STK_MINIMAL_STACK_SIZE 128U
56
57// Increase stack size when debug log is enabled
58#define USBD_STACK_SIZE ((4U * STK_MINIMAL_STACK_SIZE / 2U) * (CFG_TUSB_DEBUG ? 2U : 1U))
59
60#define BLINKY_STACK_SIZE STK_MINIMAL_STACK_SIZE
61#define AUDIO_STACK_SIZE STK_MINIMAL_STACK_SIZE
62
63// Task priorities. Only meaningful because the kernel below is instantiated with
64// stk::sched::SwitchStrategyFP32 (fixed-priority); with the default round-robin strategy
65// (stk::sched::SwitchStrategyRR, as used in example.cpp) GetWeight() would be a no-op.
66enum
67{
71};
72
73//--------------------------------------------------------------------+
74// MACRO CONSTANT TYPEDEF PROTYPES
75//--------------------------------------------------------------------+
76
77/* Blink pattern
78 * - 250 ms : device not mounted
79 * - 1000 ms : device mounted
80 * - 2500 ms : device is suspended
81 */
82enum
83{
87};
88
90
91// Audio controls
92// Current states
93bool mute[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX + 1]; // +1 for master channel 0
94uint16_t volume[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX + 1];// +1 for master channel 0
95uint32_t sampFreq;
96uint8_t clkValid;
97
98// Range states
99audio20_control_range_2_n_t(1) volumeRng[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX + 1];// Volume range state
100audio20_control_range_4_n_t(1) sampleFreqRng; // Sample frequency range state
101
102// Audio test data
104uint16_t startVal = 0;
105
107{
108 // nothing
109}
110
111//--------------------------------------------------------------------+
112// STK tasks (C++ API): each STK C task (entry function + void* param) becomes a
113// class deriving from stk::Task<StackSize, AccessMode>, with the task body in Run().
114//--------------------------------------------------------------------+
115
116// BLINKING TASK
117class BlinkyTask : public stk::Task<BLINKY_STACK_SIZE, stk::ACCESS_PRIVILEGED>
118{
119 const char *GetTraceName() const override { return "blinky"; }
120 stk::Weight GetWeight() const override { return PRIO_BLINKY; }
121
122 void Run() override
123 {
124 static bool led_state = false;
125
126 while (true)
127 {
128 // Blink every interval ms
130
131 board_led_write(led_state);
132 led_state = 1 - led_state;// toggle
133 }
134 }
135};
136
137// USB Device Driver task
138// This top level thread process all usb events and invoke callbacks
139class UsbDeviceTask : public stk::Task<USBD_STACK_SIZE, stk::ACCESS_PRIVILEGED>
140{
141 const char *GetTraceName() const override { return "usbd"; }
142 stk::Weight GetWeight() const override { return PRIO_USBD; }
143
144 void Run() override
145 {
146 // init device stack on configured roothub port
147 // This should be called after scheduler/kernel is started.
148 // Otherwise it could cause kernel issue since USB IRQ handler does use RTOS queue API.
149 tusb_rhport_init_t dev_init =
150 {
151 .role = TUSB_ROLE_DEVICE,
152 .speed = TUSB_SPEED_AUTO
153 };
154 tusb_init(BOARD_TUD_RHPORT, &dev_init);
155
157
158 // RTOS forever loop
159 while (true)
160 {
161 // tinyusb device task
162 tud_task();
163 }
164 }
165};
166
167// AUDIO Task
168// This task simulates an audio receive ISR, one frame is received every 1ms.
169// We assume that the audio data is read from an I2S buffer.
170// In a real application, this would be replaced with actual I2S receive callback.
171class AudioIsrTask : public stk::Task<AUDIO_STACK_SIZE, stk::ACCESS_USER>
172{
173 const char *GetTraceName() const override { return "audio"; }
174 stk::Weight GetWeight() const override { return PRIO_AUDIO; }
175
176 void Run() override
177 {
178 while (true)
179 {
180 stk::SleepMs(1);
181 for (size_t cnt = 0; cnt < sizeof(test_buffer_audio) / 2; cnt++)
182 {
184 }
185
186 tud_audio_write((uint8_t *) test_buffer_audio, sizeof(test_buffer_audio));
187 }
188 }
189};
190
191/*------------- MAIN -------------*/
192int main(int argc, char* argv[])
193{
194 (void) argc;
195 (void) argv;
196
197 board_init();
198
199 // shall be done in family.c similar to (CFG_TUSB_OS == OPT_OS_FREERTOS) case
200 {
201 // disable SysTick on init, kernel will manage it
202 SysTick->CTRL &= ~1U;
203
204 // Priority must be less than SVCall to allow Privileged/non-Privileged tasks.
205 NVIC_SetPriority(OTG_FS_IRQn, STK_CORTEX_M_SVCALL_ISR_PRIORITY + 1U);
206 }
207
208 // Init values
210 clkValid = 1;
211
212 sampleFreqRng.wNumSubRanges = 1;
213 sampleFreqRng.subrange[0].bMin = CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE;
214 sampleFreqRng.subrange[0].bMax = CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE;
215 sampleFreqRng.subrange[0].bRes = 0;
216
217 // STK kernel/task setup. Unlike the C API (stk_kernel_create()/stk_task_create_*()
218 // taking effect only once passed to stk_kernel_add_task()), the C++ API expresses the
219 // kernel's mode, task-slot capacity, scheduling strategy and platform as template
220 // arguments, and each task is a self-contained object added directly with AddTask() -
221 // all of which (for a static kernel) must happen before kernel.Start().
222 using namespace stk;
223
224 const uint8_t KernelMode = KERNEL_STATIC | KERNEL_SYNC | (STK_TICKLESS_IDLE ? KERNEL_TICKLESS : 0);
225
226 // allocate scheduling kernel for 3 tasks (blinky, usbd, audio) with fixed-priority
227 // scheduling strategy so that GetWeight() (set above per task) is honored as priority
229
230 static BlinkyTask blinky_task;
232 static AudioIsrTask audio_task;
233
234 // init scheduling kernel
235 kernel.Initialize();
236
237 // register tasks
238 kernel.AddTask(&blinky_task);
239 kernel.AddTask(&usb_device_task);
240 kernel.AddTask(&audio_task);
241
242 // start the scheduler - never returns
243 kernel.Start();
244
245 // shall not reach here after Start() was called
246 STK_ASSERT(false);
247
248 return 0;
249}
250
251//--------------------------------------------------------------------+
252// Device callbacks
253//--------------------------------------------------------------------+
254
255// Invoked when device is mounted
256void tud_mount_cb(void)
257{
259}
260
261// Invoked when device is unmounted
266
267// Invoked when usb bus is suspended
268// remote_wakeup_en : if host allow us to perform remote wakeup
269// Within 7ms, device must draw an average of current less than 2.5 mA from bus
270void tud_suspend_cb(bool remote_wakeup_en)
271{
272 (void) remote_wakeup_en;
274}
275
276// Invoked when usb bus is resumed
278{
280}
281
282//--------------------------------------------------------------------+
283// Application Callback API Implementations
284//--------------------------------------------------------------------+
285
286// Invoked when audio class specific set request received for an EP
287bool tud_audio_set_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff)
288{
289 (void) rhport;
290 (void) pBuff;
291
292 // We do not support any set range requests here, only current value requests
293 TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
294
295 // Page 91 in UAC2 specification
296 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
297 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
298 uint8_t ep = TU_U16_LOW(p_request->wIndex);
299
300 (void) channelNum;
301 (void) ctrlSel;
302 (void) ep;
303
304 return false;// Yet not implemented
305}
306
307// Invoked when audio class specific set request received for an interface
308bool tud_audio_set_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff)
309{
310 (void) rhport;
311 (void) pBuff;
312
313 // We do not support any set range requests here, only current value requests
314 TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
315
316 // Page 91 in UAC2 specification
317 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
318 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
319 uint8_t itf = TU_U16_LOW(p_request->wIndex);
320
321 (void) channelNum;
322 (void) ctrlSel;
323 (void) itf;
324
325 return false;// Yet not implemented
326}
327
328// Invoked when audio class specific set request received for an entity
329bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff)
330{
331 (void) rhport;
332
333 // Page 91 in UAC2 specification
334 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
335 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
336 uint8_t itf = TU_U16_LOW(p_request->wIndex);
337 uint8_t entityID = TU_U16_HIGH(p_request->wIndex);
338
339 (void) itf;
340
341 // We do not support any set range requests here, only current value requests
342 TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
343
344 // If request is for our feature unit
345 if (entityID == 2)
346 {
347 switch (ctrlSel)
348 {
349 case AUDIO20_FU_CTRL_MUTE:
350 // Request uses format layout 1
351 TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_1_t));
352
353 mute[channelNum] = ((audio20_control_cur_1_t *) pBuff)->bCur;
354
355 TU_LOG1(" Set Mute: %d of channel: %u\r\n", mute[channelNum], channelNum);
356 return true;
357
358 case AUDIO20_FU_CTRL_VOLUME:
359 // Request uses format layout 2
360 TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_2_t));
361
362 volume[channelNum] = (uint16_t) ((audio20_control_cur_2_t *) pBuff)->bCur;
363 TU_LOG1(" Set Volume: %d dB of channel: %u\r\n", volume[channelNum], channelNum);
364 return true;
365
366 // Unknown/Unsupported control
367 default:
368 TU_BREAKPOINT();
369 return false;
370 }
371 }
372 return false;// Yet not implemented
373}
374
375// Invoked when audio class specific get request received for an EP
376bool tud_audio_get_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request)
377{
378 (void) rhport;
379
380 // Page 91 in UAC2 specification
381 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
382 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
383 uint8_t ep = TU_U16_LOW(p_request->wIndex);
384
385 (void) channelNum;
386 (void) ctrlSel;
387 (void) ep;
388
389 return false;// Yet not implemented
390}
391
392// Invoked when audio class specific get request received for an interface
393bool tud_audio_get_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request)
394{
395 (void) rhport;
396
397 // Page 91 in UAC2 specification
398 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
399 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
400 uint8_t itf = TU_U16_LOW(p_request->wIndex);
401
402 (void) channelNum;
403 (void) ctrlSel;
404 (void) itf;
405
406 return false;// Yet not implemented
407}
408
409// Invoked when audio class specific get request received for an entity
410bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request)
411{
412 (void) rhport;
413
414 // Page 91 in UAC2 specification
415 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
416 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
417 // uint8_t itf = TU_U16_LOW(p_request->wIndex); // Since we have only one audio function implemented, we do not need the itf value
418 uint8_t entityID = TU_U16_HIGH(p_request->wIndex);
419
420 // Input terminal (Microphone input)
421 if (entityID == 1)
422 {
423 switch (ctrlSel)
424 {
425 case AUDIO20_TE_CTRL_CONNECTOR:
426 {
427 // The terminal connector control only has a get request with only the CUR attribute.
428 audio20_desc_channel_cluster_t ret;
429
430 // Those are dummy values for now
431 ret.bNrChannels = 1;
432 ret.bmChannelConfig = (audio20_channel_config_t) 0;
433 ret.iChannelNames = 0;
434
435 TU_LOG1(" Get terminal connector\r\n");
436
437 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, (void *) &ret, sizeof(ret));
438 }
439 break;
440
441 // Unknown/Unsupported control selector
442 default:
443 TU_BREAKPOINT();
444 return false;
445 }
446 }
447
448 // Feature unit
449 if (entityID == 2)
450 {
451 switch (ctrlSel)
452 {
453 case AUDIO20_FU_CTRL_MUTE:
454 // Audio control mute cur parameter block consists of only one byte - we thus can send it right away
455 // There does not exist a range parameter block for mute
456 TU_LOG1(" Get Mute of channel: %u\r\n", channelNum);
457 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &mute[channelNum], 1);
458
459 case AUDIO20_FU_CTRL_VOLUME:
460 switch (p_request->bRequest)
461 {
462 case AUDIO20_CS_REQ_CUR:
463 TU_LOG1(" Get Volume of channel: %u\r\n", channelNum);
464 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &volume[channelNum], sizeof(volume[channelNum]));
465
466 case AUDIO20_CS_REQ_RANGE:
467 TU_LOG1(" Get Volume range of channel: %u\r\n", channelNum);
468
469 // Copy values - only for testing - better is version below
471 ret;
472
473 ret.wNumSubRanges = 1;
474 ret.subrange[0].bMin = -90;// -90 dB
475 ret.subrange[0].bMax = 90; // +90 dB
476 ret.subrange[0].bRes = 1; // 1 dB steps
477
478 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, (void *) &ret, sizeof(ret));
479
480 // Unknown/Unsupported control
481 default:
482 TU_BREAKPOINT();
483 return false;
484 }
485 break;
486
487 // Unknown/Unsupported control
488 default:
489 TU_BREAKPOINT();
490 return false;
491 }
492 }
493
494 // Clock Source unit
495 if (entityID == 4)
496 {
497 switch (ctrlSel)
498 {
499 case AUDIO20_CS_CTRL_SAM_FREQ:
500 // channelNum is always zero in this case
501 switch (p_request->bRequest)
502 {
503 case AUDIO20_CS_REQ_CUR:
504 TU_LOG1(" Get Sample Freq.\r\n");
505 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &sampFreq, sizeof(sampFreq));
506
507 case AUDIO20_CS_REQ_RANGE:
508 TU_LOG1(" Get Sample Freq. range\r\n");
509 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &sampleFreqRng, sizeof(sampleFreqRng));
510
511 // Unknown/Unsupported control
512 default:
513 TU_BREAKPOINT();
514 return false;
515 }
516 break;
517
518 case AUDIO20_CS_CTRL_CLK_VALID:
519 // Only cur attribute exists for this request
520 TU_LOG1(" Get Sample Freq. valid\r\n");
521 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &clkValid, sizeof(clkValid));
522
523 // Unknown/Unsupported control
524 default:
525 TU_BREAKPOINT();
526 return false;
527 }
528 }
529
530 TU_LOG1(" Unsupported entity: %d\r\n", entityID);
531 return false;// Yet not implemented
532}
533
534bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request)
535{
536 (void) rhport;
537 (void) p_request;
538 startVal = 0;
539
540 return true;
541}
static bool led_state[LED_MAX]
int main()
#define STK_CORTEX_M_SVCALL_ISR_PRIORITY
Priority of the SVCall exception (the most urgent one used by the kernel).
Top-level STK include. Provides the Kernel class template and all built-in task-switching strategies.
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
Namespace of STK package.
static bool SleepMs(Timeout ms)
Put calling process into a sleep state.
Definition stk_helper.h:509
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:216
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:236
@ KERNEL_TICKLESS
Tickless mode. To use this mode STK_TICKLESS_IDLE must be defined to 1 in stk_config....
Definition stk_common.h:51
@ KERNEL_SYNC
Synchronization support (see Event).
Definition stk_common.h:50
@ KERNEL_STATIC
All tasks are static and can not exit.
Definition stk_common.h:47
Concrete implementation of IKernel.
Definition stk.h:102
void Start() override
Start the scheduler. This call does not return until all tasks have exited (KERNEL_DYNAMIC mode) or i...
Definition stk.h:1999
EAddResult AddTask(ITask *user_task) override
Register task for a soft real-time (SRT) scheduling.
Definition stk.h:1465
void Initialize(uint32_t resolution_us=PERIODICITY_DEFAULT) override
Initialize kernel.
Definition stk.h:1425
Partial implementation of the user task.
Definition stk_helper.h:98
void Run() override
Entry point of the user task.
stk::Weight GetWeight() const override
Get static base weight of the task.
const char * GetTraceName() const override
Get task trace name set by application.
stk::Weight GetWeight() const override
Get static base weight of the task.
const char * GetTraceName() const override
Get task trace name set by application.
void Run() override
Entry point of the user task.
const char * GetTraceName() const override
Get task trace name set by application.
void Run() override
Entry point of the user task.
stk::Weight GetWeight() const override
Get static base weight of the task.
uint32_t sampFreq
void tud_umount_cb(void)
void tud_mount_cb(void)
void tud_resume_cb(void)
bool tud_audio_get_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request)
uint16_t startVal
static uint32_t blink_interval_ms
audio20_control_range_4_n_t(1) sampleFreqRng
uint16_t volume[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX+1]
bool tud_audio_get_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request)
void board_init_after_tusb(void)
audio20_control_range_2_n_t(1) volumeRng[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX+1]
bool mute[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX+1]
void tud_suspend_cb(bool remote_wakeup_en)
uint8_t clkValid
bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request)
bool tud_audio_set_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff)
bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request)
@ BLINK_SUSPENDED
@ BLINK_NOT_MOUNTED
@ BLINK_MOUNTED
uint16_t test_buffer_audio[CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE/1000 *CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_TX *CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX/2]
bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff)
@ PRIO_AUDIO
@ PRIO_BLINKY
@ PRIO_USBD
bool tud_audio_set_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff)
void usb_device_task(void *param)
#define CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE
#define BOARD_TUD_RHPORT
#define CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX
#define CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_TX