The Synthesis ToolKit in C++ (STK)

Home Information Classes Download Usage Mail List Requirements Links FAQ Tutorial

Realtime Audio (callback)

An alternative scheme for audio input/output is to define a specific function in which audio computations are performed and to let the audio system call this function when more input/output data can be accepted by the hardware (referred to as a callback scheme). In this section, we show how the previous `rtsine.cpp` program can be modified to work in a callback scenario. There is no "single-sample" interface for this functionality. The callback function will be invoked automatically by the audio system controller (RtAudio) when new data is needed and it is necessary to compute a full audio buffer of samples at that time (see Blocking vs. Callbacks for further information).

The previous section described the use of the stk::RtWvOut class for realtime audio output. The stk::RtWvOut::tick() function writes data to a large ring-buffer, from which data is periodically written to the computer's audio hardware via an underlying callback routine.

// crtsine.cpp STK tutorial program
#include "SineWave.h"
#include "RtAudio.h"
using namespace stk;
// This tick() function handles sample computation only. It will be
// called automatically when the system needs a new buffer of audio
// samples.
int tick( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
double streamTime, RtAudioStreamStatus status, void *dataPointer )
{
SineWave *sine = (SineWave *) dataPointer;
StkFloat *samples = (StkFloat *) outputBuffer;
for ( unsigned int i=0; i<nBufferFrames; i++ )
*samples++ = sine->tick();
return 0;
}
int main()
{
// Set the global sample rate before creating class instances.
Stk::setSampleRate( 44100.0 );
SineWave sine;
RtAudio dac;
// Figure out how many bytes in an StkFloat and setup the RtAudio stream.
RtAudio::StreamParameters parameters;
parameters.deviceId = dac.getDefaultOutputDevice();
parameters.nChannels = 1;
RtAudioFormat format = ( sizeof(StkFloat) == 8 ) ? RTAUDIO_FLOAT64 : RTAUDIO_FLOAT32;
unsigned int bufferFrames = RT_BUFFER_SIZE;
if ( dac.openStream( &parameters, NULL, format, (unsigned int)Stk::sampleRate(), &bufferFrames, &tick, (void *)&sine ) ) {
std::cout << dac.getErrorText() << std::endl;
goto cleanup;
}
sine.setFrequency(440.0);
if ( dac.startStream() ) {
std::cout << dac.getErrorText() << std::endl;
goto cleanup;
}
// Block waiting here.
char keyhit;
std::cout << "\nPlaying ... press <enter> to quit.\n";
std::cin.get( keyhit );
// Shut down the output stream.
dac.closeStream();
cleanup:
return 0;
}
RtAudio.h
RtAudioStreamStatus
unsigned int RtAudioStreamStatus
RtAudio stream status (over- or underflow) flags.
Definition RtAudio.h:178
RtAudioFormat
unsigned long RtAudioFormat
RtAudio data format type.
Definition RtAudio.h:105
RtAudio
Realtime audio i/o C++ classes.
Definition RtAudio.h:268
RtAudio::getDefaultOutputDevice
unsigned int getDefaultOutputDevice(void)
A function that returns the ID of the default output device.
Definition RtAudio.h:915
RtAudio::getErrorText
const std::string getErrorText(void)
Retrieve the error message corresponding to the last error or warning condition.
Definition RtAudio.h:920
RtAudio::closeStream
void closeStream(void)
A function that closes a stream and frees any associated stream memory.
Definition RtAudio.h:916
RtAudio::openStream
RtAudioErrorType openStream(RtAudio::StreamParameters *outputParameters, RtAudio::StreamParameters *inputParameters, RtAudioFormat format, unsigned int sampleRate, unsigned int *bufferFrames, RtAudioCallback callback, void *userData=NULL, RtAudio::StreamOptions *options=NULL)
A public function for opening a stream with the specified parameters.
RtAudio::startStream
RtAudioErrorType startStream(void)
A function that starts a stream.
Definition RtAudio.h:917
stk::SineWave
STK sinusoid oscillator class.
Definition SineWave.h:26
stk::SineWave::setFrequency
void setFrequency(StkFloat frequency)
Set the data interpolation rate based on a looping frequency.
stk::SineWave::tick
StkFloat tick(void)
Compute and return one output sample.
Definition SineWave.h:99
stk
The STK namespace.
Definition ADSR.h:6
RtAudio::StreamParameters
The structure for specifying input or output stream parameters.
Definition RtAudio.h:302
RtAudio::StreamParameters::nChannels
unsigned int nChannels
Definition RtAudio.h:305
RtAudio::StreamParameters::deviceId
unsigned int deviceId
Definition RtAudio.h:304

The sinusoidal oscillator is created as before. The instantiation of RtAudio requires quite a few more parameters, including output/input device and channel specifiers, the data format, and the desired buffer length (in frames). In this example, we request a single output channel using the default output device, zero channels of input, the RtAudio data format which corresponds to an `StkFloat`, and the RT_BUFFER_SIZE defined in Stk.h. The `bufferFrames` argument is an API-dependent buffering parameter (see RtAudio for further information).

We also provide the audio system controller with a pointer to our callback function and an optional pointer to data that will be made available in the callback. In this example, we need to pass only the pointer to the oscillator. In more complex programs, it is typically necessary to put all shared data in a `struct` (see the next tutorial program for an example) or make use of global variables.

Our callback routine is the `tick()` function. Function arguments include pointers to the audio input and output data buffers, the buffer size (in frames), a stream time argument, a status argument to test for over/underruns, and the data pointer passed in the openStream() function (if it exists). It is necessary to cast these pointers to their corresponding data types before use. Our tick() routine simply "ticks" the oscillator for `nBufferFrames` counts and writes the result into the audio data buffer before returning.

The `main()` function blocks at the std::cin.get() call until the user hits the "enter" key, after which the audio controller is shut down and program execution ends.

# Blocking vs. Callbacks

Prior to version 4.2.0, all STK example projects and programs used blocking audio input/output functionality (typically with the RtWvIn, RtWvOut, or RtDuplex classes). In many instances, a blocking scheme results in a clearer and more straight-forward program structure. Within a graphical user interface (GUI) programming context, however, callback routines are often more natural.

In order to allow all STK programs to function with equal proficiency on all supported computer platforms, a decision was made to modify the example projects to use audio callback routines. The result is a more complicated code structure, which is unfortunate given that we generally strive to make STK code as clear as possible for educational purposes. This was especially an issue with the demo program because it is designed to function in both realtime and non-realtime contexts. The use of global variables has been avoided by defining data structures to hold all variables that must be accessible to the callback routine and other functions. Alternative schemes for making control updates could be designed depending on particular program needs and constraints.

[Main tutorial page] [Next tutorial]

The Synthesis ToolKit in C++ (STK)
©1995--2023 Perry R. Cook and Gary P. Scavone. All Rights Reserved.