The main goal of this document -- and aim of the libsndio API itself -- is to ease writing correct code, improving audio software quality and robustness. An easy approach to correctness is to keep things as simple as possible and the libsndio API design goal is to allow to do so. So, if something looks complicated, the approach may be wrong. In some cases it's even better not to have a given useful -- but complicated -- feature rather that adding hackish code that may hurt the overall correctness and robustness of the application.
Certain applications support multiple parameters sets, so if the above steps failed, you may want to retry with another set. But that's unlikely to work in real life for two reasons:
There's a special case. Some very rare applications support any format and want direct access to the hardware. They have another possibility:
...
par.pchan = 2;
par.sig = 1;
par.bits = 16;
par.le = SIO_LE_NATIVE;
par.rate = 44100;
if (!sio_setpar(hdl, &par))
errx(1, "internal error, sio_setpar() failed");
if (!sio_getpar(hdl, &par))
errx(1, "internal error, sio_getpar() failed");
if (par.pchan != 2)
errx(1, "couldn't set number of channels");
if (!par.sig || par.bits != 16 || par.le != SIO_LE_NATIVE)
errx(1, "couldn't set format");
if (par.bits != 16 || par.bps != 2)
errx(1, "couldn't set precision");
if (par.rate < 44100 * 995 / 1000 ||
par.rate > 44100 * 1005 / 1000)
errx(1, "couldn't set rate");
...
If the aucat(1) backend is used, sio_setpar(3) will always use the correct parameters. If the audio(4) backend is used, sio_setpar(3) may set the device to other parameters, so the new ones must be checked with sio_getpar(3).
So the code looks exactly as the above example but without the rate setting.
So the application must estimate the maximum time it will take to prepare the data and to fill the buffer and then choose a slightly larger buffer size by setting the appbufsz parameter in the sio_par structure.
On a multitasking system, the delay estimation must take into account the other processes hogging the system. On OpenBSD a margin of around ~5-10ms seems OK. If the buffer size is not set, the audio subsystem will choose a reasonable value, something around 50ms.
Example, consider a file player. It's organized as follows:
for (;;) {
read_file_to_fifo();
play_from_fifo();
}
the maximum time it takes to the application to call play_from_fifo()
is roughly equal to the maximum time read_file_to_fifo() takes to
complete. Reading from a file, may block for around 50ms, so say
~100ms of buffer is largely OK. If the file uses 44.1kHz sampling
rate, then the buffer size is:
0.1s * 44100Hz = 4410 frames
Below are few orders of magnitudes of maximum delays measured on a slow i386 with ~2 users doing simple stuff (editors, basic X11, compilations):
| operation | max delay |
|---|---|
| extract a block from a CD | 300ms |
| read less than 64kB from hard disk | 50ms |
| read from a pipe + pair of context switches | 10ms |
struct sio_par par;
long long writecnt; /* frames written (in bytes) */
long long readcnt; /* frames read (in bytes) */
long long realpos; /* frame number Joe is hearing */
void
cb(void *addr, int delta)
{
realpos += delta;
}
int
main(void)
{
sio_hdl *hdl;
sio_par par;
...
writecnt = readcnt = realpos = 0;
sio_onmove(hdl, cb, NULL);
...
for (;;) {
...
writepos += sio_write(hdl, buf, count);
...
readpos += sio_read(hdl, buf, count);
...
}
...
}
The callback is invoked every time a block is processed by the hardware.
It's called from one of the following functions:
realpos_sec = realpos / par.rate;Note that in earlier versions of libsndio, ``realpos'' could be negative, but that feature is being removed.
writepos = writecnt / (par.pchan * par.bps); /* convert to frames */ bufused = writepos - realpos;
The recording latency is generally zero, since the application is waiting and consuming the data immediately.
space_avail = par.bufsz - bufused;Note that we don't use par.appbufsz, but par.bufsz which is read-only but takes into account any buffering, including uncontrolled network buffers.
readpos = readcnt / (par.rchan * par.bps); bufused = realpos - readpos;
void
wait_space_avail(void)
{
int nfds, revents;
struct pollfd pfds[1];
do {
nfds = sio_pollfd(hdl, pfds, POLLOUT);
while (poll(pfds, nfds, -1) < 0) {
if (errno != EINTR)
err(1, "poll failed");
}
revents = sio_revents(hdl, pfds);
if (revents & POLLHUP)
errx(1, "device disappeared");
} while (!(revents & POLLOUT));
}
Another approach would probably lead to stuttering or to a busy loop
which, in turn, may lead to stuttering.
Audio is a continuous stream of frames, however the hardware processes them in blocks. A typical player will have an internal ring that will be filled by the player and consumed using sio_write(3). If the ring size is multiple of the hardware block size, then calls to sio_write(3) will be optimal.
The block size is stored in the ``round'' field of the sio_par structure, and is negotiated using sio_setpar(3) and sio_getpar(3). Application should round their internal buffer sizes as follows:
buf_size = desired_buf_size + par.round - 1; buf_size -= buf_size % par.round;
The ``round'' parameter is very constrained by the hardware, so sio_setpar(3) only uses it as a hint.
When changing the ``appbufsz'' parameter, an optimal block size is calculated by the sio_setpar(3) function. The sio_setpar(3) function will evolve to cope with future hardware and software constraints, so it's supposed to always do the right thing, on any hardware. So, to get the maximum robustness, don't change the block size.
If the block size is large, the tick rate is low, and the time makes big steps, that may not be desirable for applications requiring higher clock resolution. The easier solution is to use a smaller block size to get a higher tick rate. This approach has the advantage of being very accurate, but it's CPU intensive. Also it's not always possible to choose the block size (eg. because of hardware constraints).
Example: a video player plays 25 images per second. To get a smooth video, images must be displayed at regular time intervals. Thus the clock resolution must be at least twice the image rate, so 50 ticks per second. If the audio is at 44.1kHz, the maximum block size to get smooth video is:
44100Hz / 50Hz = 882 frames per block
Another solution is to use large block size, and extrapolate the time between clock ticks using gettimeofday(2). This is more complicated to get right, but works in all situations, is less CPU intensive and works even if very high clock resolution is needed.
#define PCT_TO_SIO(pct) ((SIO_MAXVOL * (pct) + 50) / 100)
#define SIO_TO_PCT(vol) ((100 * (vol) + ((SIO_MAXVOL + 1) / 2)) / SIO_MAXVOL)
void setvol(int p)
{
...
sio_setvol(hdl, PCT_TO_SIO(p));
}
void
cb(void *addr, unsigned vol)
{
redraw_volume_slider(SIO_TO_PCT(vol));
}
int
main(void)
{
...
sio_onvol(hdl, cb, NULL);
...
for (;;) {
p = mouse_event_to_pct();
setvol(p);
}
}
for (;;) {
p = volume_slider_to_pct();
setvol(p);
p = getvol();
move_volume_slider(p);
}
One may think that it's enough to set a global ``current volume''
variable in the callback and to return it in the getter. This can't
work because the below property is required:
x == SIO_TO_PCT(PCT_TO_SIO(x)) /* for all x */ y == PCT_TO_SIO(SIO_TO_PCT(y)) /* for all y */So it may lead to various weired effects like the cursor stuttering around a given position, or ``+/- volume'' keyboard shortcuts not working. The correct implementation is to use feedback as in the above section, if that's not possible, a fake getter can be implemented as follows:
unsigned current_pct;
void
cb(void *addr, unsigned vol)
{
if (vol != PCT_TO_SIO(current_pct))
current_pct = SIO_TO_PCT(vol);
}
unsigned
getvol(int p)
{
return current_pct;
}
A possible (but not necessary) improvement would be to fill the play buffer with silence when resuming. The buffer size is obtained in the ``appbufsz'' parameter using sio_getpar()
The ``bufsz'' parameter is read-only and gives the total buffering between the application and Joe's ears, it's actually the latency. It takes into account any buffering including uncontrolled buffering of network sockets.
However that's not always the case: .wav and .aiff files store 24-bit samples in 3-byte words to save space. This encoding is often referred as ``s24le3'' or ``s24be3''. If a program just reads and plays such files without any processing, it's likely it will try to send the file contents on the audio stream as-is. If so, the parameters should be set as follows:
par.bits = 24; par.bps = 3;
void
wait_ready(void)
{
/*
* wait buffer to be consumed, sleep not to hog the CPU
*/
while (bufused > threshold)
usleep(5);
}
where the ``bufused'' variable is updated asynchronously by the
callback set with sio_onmove(3). Then suppose it's called as
follows:
for (;;) {
prepare_data(some_data);
wait_ready();
sio_write(hdl, some_data, count);
}
This will deadlock. The callback is invoked from sio_write(3), but sio_write(3) is not called until the ``bufused'' is updated by the callback. The correct implementation is by using poll(2), as follows, it's also more efficient:
void
wait_ready(void)
{
int nfds, revents;
struct pollfd pfds[1];
do {
nfds = sio_pollfd(hdl, pfds, POLLOUT);
if (poll(pfds, nfds, -1) < 0)
err(1, "poll failed");
revents = sio_revents(hdl, pfds);
} while (!(revents & POLLOUT));
}
That said, multiple threads can use concurrently the sndio library on the same handle as long as all calls to functions taking the same ``sio_hdl *'' argument are serialized.
channels numbers start from zero and are ordered as follows:
| channel number | physical meaning |
|---|---|
| 0 | main left |
| 1 | main right |
| 2 | rear left |
| 3 | rear right |
| 4 | center |
| 5 | lfe |
above, 0 is the origin, but that's arbitrary. The important point is that ``main left'' is just before ``main right''. This allows for instance the rear speakers to be viewed as a stereo substream.