comparison include/Bela.h @ 301:e4392164b458 prerelease

RENAMED BeagleRT to Bela AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, scripts probably not working
author Giulio Moro <giuliomoro@yahoo.it>
date Fri, 27 May 2016 14:34:41 +0100
parents include/BeagleRT.h@c55c6f6c233c
children 421a69d42943
comparison
equal deleted inserted replaced
300:dbeed520b014 301:e4392164b458
1 /**
2 * @file
3 * @brief Main Bela public API
4 *
5 * Central control code for hard real-time audio on BeagleBone Black
6 * using PRU and Xenomai Linux extensions. This code began as part
7 * of the Hackable Instruments project (EPSRC) at Queen Mary University
8 * of London, 2013-14.
9 *
10 * (c) 2014-15 Andrew McPherson, Victor Zappi and Giulio Moro,
11 * Queen Mary University of London
12 */
13
14 /**
15 * \mainpage
16 *
17 * Bela is a hard-real-time, ultra-low latency audio and sensor environment for
18 * BeagleBone Black, which works with the BeagleBone Audio Cape or a custom "Bela Cape"
19 * which incorporates stereo audio with 8x, 16-bit analog inputs and outputs.
20 *
21 * Bela is based on the Xenomai real-time Linux extensions (http://xenomai.org) and
22 * uses the BeagleBone %PRU subsystem to address the audio and sensor hardware.
23 *
24 * Further information can be found at http://beaglert.cc
25 */
26
27
28 #ifndef BEAGLERT_H_
29 #define BEAGLERT_H_
30
31 #include <stdint.h>
32 #include <unistd.h>
33 #include <rtdk.h>
34 #include "digital_gpio_mapping.h"
35 #include <GPIOcontrol.h>
36
37 // Useful constants
38
39 /** \cond PRIVATE */
40 #define DBOX_CAPE // New custom cape
41 #ifdef DBOX_CAPE
42 #define CODEC_I2C_ADDRESS 0x18 // Address of TLV320AIC3104 codec
43 #else
44 #define CODEC_I2C_ADDRESS 0x1B // Address of TLV320AIC3106 codec
45 #endif
46
47 #define MAX_PRU_FILENAME_LENGTH 256
48 #define MAX_SERVERNAME_LENGTH 256
49 /** \endcond */
50
51 /**
52 * \ingroup auxtask
53 *
54 * Xenomai priority level for audio processing. Maximum possible priority is 99.
55 * In general, all auxiliary tasks should have a level lower than this unless for\
56 * special purposes where the task needs to interrupt audio processing.
57 */
58 #define BEAGLERT_AUDIO_PRIORITY 95
59
60 // Default volume levels
61
62 /**
63 * \addtogroup levels
64 *
65 * @{
66 */
67
68 /**
69 * Default level of the audio DAC in decibels. See Bela_setDACLevel().
70 */
71 #define DEFAULT_DAC_LEVEL 0.0
72
73 /**
74 * Default level of the audio ADC in decibels. See Bela_setADCLevel().
75 */
76 #define DEFAULT_ADC_LEVEL -6.0
77
78
79 /**
80 * Default level of the Programmable Gain Amplifier in decibels.
81 */
82 #define DEFAULT_PGA_GAIN 16
83
84 /**
85 * Default level of the headphone output in decibels. See Bela_setHeadphoneLevel().
86 */
87 #define DEFAULT_HP_LEVEL -6.0
88 /** @} */
89
90 /**
91 * Flag for BelaContext. If set, indicates the audio and analog buffers are interleaved.
92 */
93 #define BEAGLERT_FLAG_INTERLEAVED (1 << 0) // Set if buffers are interleaved
94 /**
95 * Flag for BelaContext. If set, indicates analog outputs persist for future frames.
96 */
97 #define BEAGLERT_FLAG_ANALOG_OUTPUTS_PERSIST (1 << 1) // Set if analog/digital outputs persist for future buffers
98
99 /**
100 * \ingroup control
101 * \brief Structure containing initialisation parameters for the real-time
102 * audio control system.
103 *
104 * This structure is initialised using Bela_defaultSettings(). Its contents
105 * are used up through the point of calling
106 * Bela_initAudio() at which point it is no longer needed.
107 */
108 typedef struct {
109 // These items might be adjusted by the user:
110
111 /// \brief Number of (analog) frames per period.
112 ///
113 /// Number of audio frames depends on relative sample rates of the two. By default,
114 /// audio is twice the sample rate, so has twice the period size.
115 int periodSize;
116 /// Whether to use the analog input and output
117 int useAnalog;
118 /// Whether to use the 16 programmable GPIOs
119 int useDigital;
120 /// How many channels for the ADC and DAC
121 int numAnalogChannels;
122 /// How many channels for the GPIOs
123 int numDigitalChannels;
124
125 /// Whether to begin with the speakers muted
126 int beginMuted;
127 /// Level for the audio DAC output
128 float dacLevel;
129 /// Level for the audio ADC input
130 float adcLevel;
131 /// Gains for the PGA, left and right channels
132 float pgaGain[2];
133 /// Level for the headphone output
134 float headphoneLevel;
135 /// How many channels to use on the multiplexer capelet, if enabled
136 int numMuxChannels;
137
138 /// Which PRU (0 or 1) the code should run on
139 int pruNumber;
140 /// The external .bin file to load. If empty will use PRU code from pru_rtaudio_bin.h
141 char pruFilename[MAX_PRU_FILENAME_LENGTH];
142 /// Whether to use verbose logging
143 int verbose;
144
145 // These items are application-dependent but should probably be
146 // determined by the programmer rather than the user
147
148 /// Whether audio/analog data should be interleaved
149 int interleave;
150 /// \brief Whether analog outputs should persist to future frames.
151 ///
152 /// n.b. digital pins always persist, audio never does
153 int analogOutputsPersist;
154
155 // These items are hardware-dependent and should only be changed
156 // to run on different hardware
157
158 /// Where the codec can be found on the I2C bus
159 int codecI2CAddress;
160 /// Pin where amplifier mute can be found
161 int ampMutePin;
162 /// Port where the UDP server will listen
163 int receivePort;
164 /// Port where the UDP client will transmit
165 int transmitPort;
166 char serverName[MAX_SERVERNAME_LENGTH];
167 } BelaInitSettings;
168
169
170 /**
171 * \ingroup render
172 * \brief Structure holding current audio and sensor settings and pointers to data buffers.
173 *
174 * This structure is passed to setup(), render() and cleanup(). It is
175 * initialised in Bela_initAudio() based on the contents of the BelaInitSettings
176 * structure.
177 */
178 typedef struct {
179 /// \brief Buffer holding audio input samples
180 ///
181 /// This buffer may be in either interleaved or non-interleaved format,
182 /// depending on the contents of the BelaInitSettings structure.
183 /// \b Note: this element is available in render() only.
184 float *audioIn;
185
186 /// \brief Buffer holding audio output samples
187 ///
188 /// This buffer may be in either interleaved or non-interleaved format,
189 /// depending on the contents of the BelaInitSettings structure.
190 /// \b Note: this element is available in render() only.
191 float *audioOut;
192
193 /// \brief Buffer holding analog input samples
194 ///
195 /// This buffer may be in either interleaved or non-interleaved format,
196 /// depending on the contents of the BelaInitSettings structure.
197 /// \b Note: this element is available in render() only.
198 float *analogIn;
199
200 /// \brief Buffer holding analog output samples
201 ///
202 /// This buffer may be in either interleaved or non-interleaved format,
203 /// depending on the contents of the BelaInitSettings structure.
204 /// \b Note: this element is available in render() only.
205 float *analogOut;
206
207 /// \brief Buffer holding digital input/output samples
208 ///
209 /// \b Note: this element is available in render() only.
210 uint32_t *digital;
211
212 /// Number of audio frames per period
213 uint32_t audioFrames;
214 /// Number of audio channels (currently always 2)
215 uint32_t audioChannels;
216 /// Audio sample rate in Hz (currently always 44100.0)
217 float audioSampleRate;
218
219 /// \brief Number of analog frames per period
220 ///
221 /// This will be 0 if analog I/O is disabled.
222 uint32_t analogFrames;
223
224 /// \brief Number of analog channels
225 ///
226 /// This could take a value of 8, 4 or 2. This will be 0 if analog I/O is disabled.
227 uint32_t analogChannels;
228
229 /// \brief Analog sample rate in Hz
230 ///
231 /// The analog sample rate depends on the number of analog channels used. If
232 /// 8 channels are used, the sample rate is 22050. If 4 channels are used, the sample
233 /// rate is 44100. If 2 channels are used, the sample rate is 88200. If analog I/O
234 /// is disabled, the sample rate is 0.
235 float analogSampleRate;
236
237 /// Number of digital frames per period
238 uint32_t digitalFrames;
239 /// \brief Number of digital channels
240 ///
241 /// Currently this will always be 16, unless digital I/O is disabled, in which case it will be 0.
242 uint32_t digitalChannels;
243 /// Digital sample rate in Hz (currently always 44100.0)
244 float digitalSampleRate;
245
246 /// \brief Number of elapsed audio samples since the start of rendering.
247 ///
248 /// This holds the total number of audio samples as of the beginning of the current period. To
249 /// find the current number of analog or digital samples elapsed, multiply by the ratio of the
250 /// sample rates (e.g. half the number of analog samples will have elapsed if the analog sample
251 /// rate is 22050).
252 uint64_t audioSampleCount;
253
254 /// \brief Other audio/sensor settings
255 ///
256 /// Binary combination of flags including:
257 ///
258 /// BEAGLERT_FLAG_INTERLEAVED: indicates the audio and analog buffers are interleaved
259 ///
260 /// BEAGLERT_FLAG_ANALOG_OUTPUTS_PERSIST: indicates that writes to the analog outputs will
261 /// persist for future frames. If not set, writes affect one frame only.
262 uint32_t flags;
263 } BelaContext;
264
265 /** \ingroup auxtask
266 *
267 * Auxiliary task variable. Auxiliary tasks are created using createAuxiliaryTask() and
268 * automatically cleaned up after cleanup() finishes.
269 */
270 typedef void* AuxiliaryTask; // Opaque data type to keep track of aux tasks
271
272 /** \ingroup render
273 *
274 * Flag that indicates when the audio will stop. Threads can poll this variable to indicate when
275 * they should stop. Additionally, a program can set this to \c true
276 * to indicate that audio processing should terminate. Calling Bela_stopAudio()
277 * has the effect of setting this to \c true.
278 */
279 extern int gShouldStop;
280
281 // *** User-defined render functions ***
282
283 /**
284 * \defgroup render User-defined render functions
285 *
286 * These three functions must be implemented by the developer in every Bela program.
287 * Typically they appear in their own .cpp source file.
288 *
289 * @{
290 */
291
292 /**
293 * \brief User-defined initialisation function which runs before audio rendering begins.
294 *
295 * This function runs once at the beginning of the program, after most of the system
296 * initialisation has begun but before audio rendering starts. Use it to prepare any
297 * memory or resources that will be needed in render().
298 *
299 * \param context Data structure holding information on sample rates, numbers of channels,
300 * frame sizes and other state. Note: the buffers for audio, analog and digital data will
301 * \b not yet be available to use. Do not attempt to read or write audio or sensor data
302 * in setup().
303 * \param userData An opaque pointer to an optional user-defined data structure. Whatever
304 * is passed as the second argument to Bela_initAudio() will appear here.
305 *
306 * \return true on success, or false if an error occurred. If no initialisation is
307 * required, setup() should return true.
308 */
309 bool setup(BelaContext *context, void *userData);
310
311 /**
312 * \brief User-defined callback function to process audio and sensor data.
313 *
314 * This function is called regularly by the system every time there is a new block of
315 * audio and/or sensor data to process. Your code should process the requested samples
316 * of data, store the results within \c context, and return.
317 *
318 * \param context Data structure holding buffers for audio, analog and digital data. The
319 * structure also holds information on numbers of channels, frame sizes and sample rates,
320 * which are guaranteed to remain the same throughout the program and to match what was
321 * passed to setup().
322 * \param userData An opaque pointer to an optional user-defined data structure. Will
323 * be the same as the \c userData parameter passed to setup().
324 */
325 void render(BelaContext *context, void *userData);
326
327 /**
328 * \brief User-defined cleanup function which runs when the program finishes.
329 *
330 * This function is called by the system once after audio rendering has finished, before the
331 * program quits. Use it to release any memory allocated in setup() and to perform
332 * any other required cleanup. If no initialisation is performed in setup(), then
333 * this function will usually be empty.
334 *
335 * \param context Data structure holding information on sample rates, numbers of channels,
336 * frame sizes and other state. Note: the buffers for audio, analog and digital data will
337 * no longer be available to use. Do not attempt to read or write audio or sensor data
338 * in cleanup().
339 * \param userData An opaque pointer to an optional user-defined data structure. Will
340 * be the same as the \c userData parameter passed to setup() and render().
341 */
342 void cleanup(BelaContext *context, void *userData);
343
344 /** @} */
345
346 /**
347 * \defgroup control Control and command line functions
348 *
349 * These functions are used to initialise the Bela settings, process arguments
350 * from the command line, and start/stop the audio and sensor system.
351 *
352 * @{
353 */
354
355 // *** Command-line settings ***
356
357 /**
358 * \brief Initialise the data structure containing settings for Bela.
359 *
360 * This function should be called in main() before parsing any command-line arguments. It
361 * sets default values in the data structure which specifies the Bela settings, including
362 * frame sizes, numbers of channels, volume levels and other parameters.
363 *
364 * \param settings Structure holding initialisation data for Bela.
365 */
366 void Bela_defaultSettings(BelaInitSettings *settings);
367
368 /**
369 * \brief Get long options from command line argument list, including Bela standard options
370 *
371 * This function should be used in main() to process command line options, in place of the
372 * standard library getopt_long(). Internally, it parses standard Bela command-line options,
373 * storing the results in the settings data structure. Any options which are not part of the
374 * Bela standard options will be returned, as they would normally be in getopt_long().
375 *
376 * \param argc Number of command line options, as passed to main().
377 * \param argv Array of command line options, as passed to main().
378 * \param customShortOptions List of short options to be parsed, analogous to getopt_long(). This
379 * list should not include any characters already parsed as part of the Bela standard options.
380 * \param customLongOptions List of long options to parsed, analogous to getopt_long(). This
381 * list should not include any long options already parsed as part of the Bela standard options.
382 * \param settings Data structure holding initialisation settings for Bela. Any standard options
383 * parsed will automatically update this data structure.
384 *
385 * \return Value of the next option parsed which is not a Bela standard option, or -1 when the
386 * argument list has been exhausted. Similar to the return value of getopt_long() except that Bela
387 * standard options are handled internally and not returned.
388 */
389 int Bela_getopt_long(int argc, char *argv[], const char *customShortOptions,
390 const struct option *customLongOptions, BelaInitSettings *settings);
391
392 /**
393 * \brief Print usage information for Bela standard options.
394 *
395 * This function should be called from your code wherever you wish to print usage information for the
396 * user. It will print usage information on Bela standard options, after which you can print usage
397 * information for your own custom options.
398 */
399 void Bela_usage();
400
401 /**
402 * \brief Set level of verbose (debugging) printing.
403 *
404 * \param level Verbosity level of the internal Bela system. 0 by default; higher values will
405 * print more information. Presently all positive numbers produce the same level of printing.
406 */
407 void Bela_setVerboseLevel(int level);
408
409
410 // *** Audio control functions ***
411
412 /**
413 * \brief Initialise audio and sensor rendering environment.
414 *
415 * This function prepares audio rendering in Bela. It should be called from main() sometime
416 * after command line option parsing has finished. It will initialise the rendering system, which
417 * in the process will result in a call to the user-defined setup() function.
418 *
419 * \param settings Data structure holding system settings, including numbers of channels, frame sizes,
420 * volume levels and other information.
421 * \param userData An opaque pointer to a user-defined data structure which will be passed to
422 * setup(), render() and cleanup(). You can use this to pass custom information
423 * to the rendering functions, as an alternative to using global variables.
424 *
425 * \return 0 on success, or nonzero if an error occurred.
426 */
427 int Bela_initAudio(BelaInitSettings *settings, void *userData);
428
429 /**
430 * \brief Begin processing audio and sensor data.
431 *
432 * This function will start the Bela audio/sensor system. After this function is called, the
433 * system will make periodic calls to render() until Bela_stopAudio() is called.
434 *
435 * \return 0 on success, or nonzero if an error occurred.
436 */
437 int Bela_startAudio();
438
439 /**
440 * \brief Stop processing audio and sensor data.
441 *
442 * This function will stop the Bela audio/sensor system. After this function returns, no further
443 * calls to render() will be issued.
444 */
445 int Bela_startAuxiliaryTask(AuxiliaryTask it);
446 void Bela_stopAudio();
447
448 /**
449 * \brief Clean up resources from audio and sensor processing.
450 *
451 * This function should only be called after Bela_stopAudio(). It will release any
452 * internal resources for audio and sensor processing. In the process, it will call the
453 * user-defined cleanup() function.
454 */
455 void Bela_cleanupAudio();
456
457 /** @} */
458
459 /**
460 * \defgroup levels Audio level controls
461 *
462 * These functions control the input and output levels for the audio codec. If a Bela program
463 * does not call these functions, sensible default levels will be used.
464 *
465 * @{
466 */
467
468 // *** Volume and level controls ***
469
470 /**
471 * \brief Set the level of the audio DAC.
472 *
473 * This function sets the level of all audio outputs (headphone, line, speaker). It does
474 * not affect the level of the (non-audio) analog outputs.
475 *
476 * \b Important: do not call this function from within render(), as it does not make
477 * any guarantees on real-time performance.
478 *
479 * \param decibels Level of the DAC output. Valid levels range from -63.5 (lowest) to
480 * 0 (highest) in steps of 0.5dB. Levels between increments of 0.5 will be rounded down.
481 *
482 * \return 0 on success, or nonzero if an error occurred.
483 */
484 int Bela_setDACLevel(float decibels);
485
486 /**
487 * \brief Set the level of the audio ADC.
488 *
489 * This function sets the level of the audio input. It does not affect the level of the
490 * (non-audio) analog inputs.
491 *
492 * \b Important: do not call this function from within render(), as it does not make
493 * any guarantees on real-time performance.
494 *
495 * \param decibels Level of the ADC input. Valid levels range from -12 (lowest) to
496 * 0 (highest) in steps of 1.5dB. Levels between increments of 1.5 will be rounded down.
497 *
498 * \return 0 on success, or nonzero if an error occurred.
499 */
500 int Bela_setADCLevel(float decibels);
501
502
503 /**
504 * \brief Set the gain of the audio preamplifier.
505 *
506 * This function sets the level of the Programmable Gain Amplifier(PGA), which
507 * amplifies the signal before the ADC.
508 *
509 * \b Important: do not call this function from within render(), as it does not make
510 * any guarantees on real-time performance.
511 *
512 * \param decibels Level of the PGA Valid levels range from 0 (lowest) to
513 * 59.5 (highest) in steps of 0.5dB. Levels between increments of 0.5 will be rounded.
514 * \param channel Specifies which channel to apply the gain to. Channel 0 is left,
515 * channel 1 is right
516 *
517 * \return 0 on success, or nonzero if an error occurred.
518 */
519 int Bela_setPgaGain(float decibels, int channel);
520
521 /**
522 * \brief Set the level of the onboard headphone amplifier.
523 *
524 * This function sets the level of the headphone output only (3-pin connector on the Bela
525 * cape or the output jack on the BeagleBone Audio Cape). It does not affect the level of the
526 * speakers or the line out pads on the cape.
527 *
528 * \b Important: do not call this function from within render(), as it does not make
529 * any guarantees on real-time performance.
530 *
531 * \param decibels Level of the DAC output. Valid levels range from -63.5 (lowest) to
532 * 0 (highest) in steps of 0.5dB. Levels between increments of 0.5 will be rounded down.
533 *
534 * \return 0 on success, or nonzero if an error occurred.
535 */
536 int Bela_setHeadphoneLevel(float decibels);
537
538 /**
539 * \brief Mute or unmute the onboard speaker amplifiers.
540 *
541 * This function mutes or unmutes the amplifiers on the Bela cape. Whether the speakers begin
542 * muted or unmuted depends on the BelaInitSettings structure passed to Bela_initAudio().
543 *
544 * \b Important: do not call this function from within render(), as it does not make
545 * any guarantees on real-time performance.
546 *
547 * \param mute 0 to enable the speakers, nonzero to mute the speakers.
548 *
549 * \return 0 on success, or nonzero if an error occurred.
550 */
551 int Bela_muteSpeakers(int mute);
552
553 /** @} */
554
555 /**
556 * \defgroup auxtask Auxiliary task support
557 *
558 * These functions are used to create separate real-time tasks (threads) which run at lower
559 * priority than the audio processing. They can be used, for example, for large time-consuming
560 * calculations which would take more than one audio frame length to process, or they could be
561 * used to communicate with external hardware when that communication might block or be delayed.
562 *
563 * All auxiliary tasks used by the program should be created in setup(). The tasks
564 * can then be scheduled at will within the render() function.
565 *
566 * @{
567 */
568
569 // *** Functions for creating auxiliary tasks ***
570
571 /**
572 * \brief Create a new auxiliary task.
573 *
574 * This function creates a new auxiliary task which, when scheduled, runs the function specified
575 * in the first argument. Note that the task does not run until scheduleAuxiliaryTask() is called.
576 * Auxiliary tasks should be created in setup() and never in render() itself.
577 *
578 * The second argument specifies the real-time priority. Valid values are between 0
579 * and 99, and usually should be lower than \ref BEAGLERT_AUDIO_PRIORITY. Tasks with higher priority always
580 * preempt tasks with lower priority.
581 *
582 * \param functionToCall Function which will run each time the auxiliary task is scheduled.
583 * \param priority Xenomai priority level at which the task should run.
584 * \param name Name for this task, which should be unique system-wide (no other running program should use this name).
585 */
586 AuxiliaryTask Bela_createAuxiliaryTask(void (*functionToCall)(void*), int priority, const char *name, void* args, bool autoSchedule = false);
587 AuxiliaryTask Bela_createAuxiliaryTask(void (*functionToCall)(void), int priority, const char *name, bool autoSchedule = false);
588
589 /**
590 * \brief Start an auxiliary task so that it can be run.
591 *
592 * This function will start an auxiliary task but will NOT schedule it.
593 * It will also set a flag in the associate InternalAuxiliaryTask to flag the
594 * task as "started", so that successive calls to the same function for a given AuxiliaryTask
595 * have no effect.
596 * The user should never be required to call this function directly, as it is called
597 * by Bela_scheduleAuxiliaryTask if needed (e.g.: if a task is scheduled in setup() )
598 * or immediately after starting the audio thread.
599 *
600 * \param task Task to start.
601 */
602
603 int Bela_startAuxiliaryTask(AuxiliaryTask task);
604 /**
605 * \brief Run an auxiliary task which has previously been created.
606 *
607 * This function will schedule an auxiliary task to run. When the task runs, the function in the first
608 * argument of createAuxiliaryTaskLoop() will be called.
609 *
610 * scheduleAuxiliaryTask() is typically called from render() to start a lower-priority task. The function
611 * will not run immediately, but only once any active higher priority tasks have finished.
612 *
613 * \param task Task to schedule for running.
614 */
615 void Bela_scheduleAuxiliaryTask(AuxiliaryTask task);
616 void Bela_autoScheduleAuxiliaryTasks();
617
618 /** @} */
619 #include <Utilities.h>
620
621 #endif /* BEAGLERT_H_ */