comparison include/BeagleRT.h @ 108:3068421c0737 ultra-staging

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