xref: /openbsd-src/lib/libsndio/sio_open.3 (revision edb9bfb9ca792dc8ffa3ff5dcd76aa8c1e886d0a)
1.\" $OpenBSD: sio_open.3,v 1.45 2016/02/11 16:30:35 tim Exp $
2.\"
3.\" Copyright (c) 2007 Alexandre Ratchov <alex@caoua.org>
4.\"
5.\" Permission to use, copy, modify, and distribute this software for any
6.\" purpose with or without fee is hereby granted, provided that the above
7.\" copyright notice and this permission notice appear in all copies.
8.\"
9.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16.\"
17.Dd $Mdocdate: February 11 2016 $
18.Dt SIO_OPEN 3
19.Os
20.Sh NAME
21.Nm sio_open ,
22.Nm sio_close ,
23.Nm sio_setpar ,
24.Nm sio_getpar ,
25.Nm sio_getcap ,
26.Nm sio_start ,
27.Nm sio_stop ,
28.Nm sio_read ,
29.Nm sio_write ,
30.Nm sio_onmove ,
31.Nm sio_nfds ,
32.Nm sio_pollfd ,
33.Nm sio_revents ,
34.Nm sio_eof ,
35.Nm sio_setvol ,
36.Nm sio_onvol ,
37.Nm sio_initpar
38.Nd sndio interface to audio devices
39.Sh SYNOPSIS
40.In sndio.h
41.Ft "struct sio_hdl *"
42.Fn sio_open "const char *name" "unsigned int mode" "int nbio_flag"
43.Ft "void"
44.Fn sio_close "struct sio_hdl *hdl"
45.Ft "int"
46.Fn sio_setpar "struct sio_hdl *hdl" "struct sio_par *par"
47.Ft "int"
48.Fn sio_getpar "struct sio_hdl *hdl" "struct sio_par *par"
49.Ft "int"
50.Fn sio_getcap "struct sio_hdl *hdl" "struct sio_cap *cap"
51.Ft "int"
52.Fn sio_start "struct sio_hdl *hdl"
53.Ft "int"
54.Fn sio_stop "struct sio_hdl *hdl"
55.Ft "size_t"
56.Fn sio_read "struct sio_hdl *hdl" "void *addr" "size_t nbytes"
57.Ft "size_t"
58.Fn sio_write "struct sio_hdl *hdl" "const void *addr" "size_t nbytes"
59.Ft "void"
60.Fn sio_onmove "struct sio_hdl *hdl" "void (*cb)(void *arg, int delta)" "void *arg"
61.Ft "int"
62.Fn sio_nfds "struct sio_hdl *hdl"
63.Ft "int"
64.Fn sio_pollfd "struct sio_hdl *hdl" "struct pollfd *pfd" "int events"
65.Ft "int"
66.Fn sio_revents "struct sio_hdl *hdl" "struct pollfd *pfd"
67.Ft "int"
68.Fn sio_eof "struct sio_hdl *hdl"
69.Ft "int"
70.Fn sio_setvol "struct sio_hdl *hdl" "unsigned int vol"
71.Ft "int"
72.Fn sio_onvol "struct sio_hdl *hdl" "void (*cb)(void *arg, unsigned int vol)" "void *arg"
73.Ft "void"
74.Fn sio_initpar "struct sio_par *par"
75.\"Fd #define SIO_BPS(bits)
76.\"Fd #define SIO_LE_NATIVE
77.Sh DESCRIPTION
78The
79.Nm sndio
80library allows user processes to access
81.Xr audio 4
82hardware and the
83.Xr sndiod 8
84audio server in a uniform way.
85.Ss Opening and closing an audio device
86First the application must call the
87.Fn sio_open
88function to obtain a handle to the device;
89later it will be passed as the
90.Fa hdl
91argument of most other functions.
92The
93.Fa name
94parameter gives the device string discussed in
95.Xr sndio 7 .
96In most cases it should be set to
97.Dv SIO_DEVANY
98to allow the user to select it using the
99.Ev AUDIODEVICE
100environment variable.
101.Pp
102The following values of the
103.Fa mode
104parameter are supported:
105.Bl -tag -width "SIO_PLAY | SIO_REC"
106.It Dv SIO_PLAY
107Play-only mode: data written will be played by the device.
108.It Dv SIO_REC
109Record-only mode: samples are recorded by the device and must be read.
110.It Dv SIO_PLAY | SIO_REC
111The device plays and records synchronously; this means that
112the n-th recorded sample was physically sampled exactly when
113the n-th played sample was actually played.
114.El
115.Pp
116If the
117.Fa nbio_flag
118argument is true (i.e. non-zero), then the
119.Fn sio_read
120and
121.Fn sio_write
122functions (see below) will be non-blocking.
123.Pp
124The
125.Fn sio_close
126function stops the device as if
127.Fn sio_stop
128is called and frees the handle.
129Thus, no samples submitted with
130.Fn sio_write
131are discarded.
132.Ss Negotiating audio parameters
133Audio samples are interleaved.
134A frame consists of one sample for each channel.
135For example, a 16-bit stereo encoding has two samples per frame
136and, two bytes per sample (thus 4 bytes per frame).
137.Pp
138The set of parameters of the device that can be controlled
139is given by the following structure:
140.Bd -literal
141struct sio_par {
142	unsigned int bits;	/* bits per sample */
143	unsigned int bps;	/* bytes per sample */
144	unsigned int sig;	/* 1 = signed, 0 = unsigned int */
145	unsigned int le;	/* 1 = LE, 0 = BE byte order */
146	unsigned int msb;	/* 1 = MSB, 0 = LSB aligned */
147	unsigned int rchan;	/* number channels for recording */
148	unsigned int pchan;	/* number channels for playback */
149	unsigned int rate;	/* frames per second */
150	unsigned int appbufsz;	/* minimum buffer size without xruns */
151	unsigned int bufsz;	/* end-to-end buffer size (read-only) */
152	unsigned int round;	/* optimal buffer size divisor */
153#define SIO_IGNORE	0	/* pause during xrun */
154#define SIO_SYNC	1	/* resync after xrun */
155#define SIO_ERROR	2	/* terminate on xrun */
156	unsigned int xrun;	/* what to do on overrun/underrun */
157};
158.Ed
159.Pp
160The parameters are as follows:
161.Bl -tag -width "appbufsz"
162.It Va bits
163Number of bits per sample: must be between 1 and 32.
164.It Va bps
165Bytes per samples; if specified, it must be large enough to hold all bits.
166By default it's set to the smallest power of two large enough to hold
167.Va bits .
168.It Va sig
169If set (i.e. non-zero) then the samples are signed, else unsigned.
170.It Va le
171If set, then the byte order is little endian, else big endian;
172it's meaningful only if
173.Va bps
174\*(Gt 1.
175.It Va msb
176If set, then the
177.Va bits
178are aligned in the packet to the most significant bit
179(i.e. lower bits are padded),
180else to the least significant bit
181(i.e. higher bits are padded);
182it's meaningful only if
183.Va bits
184\*(Lt
185.Va bps
186* 8.
187.It Va rchan
188The number of recorded channels; meaningful only if
189.Dv SIO_REC
190mode was selected.
191.It Va pchan
192The number of played channels; meaningful only if
193.Dv SIO_PLAY
194mode was selected.
195.It Va rate
196The sampling frequency in Hz.
197.It Va bufsz
198The maximum number of frames that may be buffered.
199This parameter takes into account any buffers, and
200can be used for latency calculations.
201It is read-only.
202.It Va appbufsz
203Size of the buffer in frames the application must maintain non-empty
204(on the play end) or non-full (on the record end) by calling
205.Fn sio_write
206or
207.Fn sio_read
208fast enough to avoid overrun or underrun conditions.
209The audio subsystem may use additional buffering, thus this
210parameter cannot be used for latency calculations.
211.It Va round
212Optimal number of frames that the application buffers
213should be a multiple of, to get best performance.
214Applications can use this parameter to round their block size.
215.It Va xrun
216The action when the client doesn't accept
217recorded data or doesn't provide data to play fast enough;
218it can be set to one of the
219.Dv SIO_IGNORE ,
220.Dv SIO_SYNC ,
221or
222.Dv SIO_ERROR
223constants.
224.El
225.Pp
226The following approach is recommended to negotiate device parameters:
227.Bl -bullet
228.It
229Initialize a
230.Vt sio_par
231structure using
232.Fn sio_initpar
233and fill it with
234the desired parameters.
235Then call
236.Fn sio_setpar
237to request the device to use them.
238Parameters left unset in the
239.Vt sio_par
240structure will be set to device-specific defaults.
241.It
242Call
243.Fn sio_getpar
244to retrieve the actual parameters of the device
245and check that they are usable.
246If they are not, then fail or set up a conversion layer.
247Sometimes the rate set can be slightly different to what was requested.
248A difference of about 0.5% is not audible and should be ignored.
249.El
250.Pp
251Parameters cannot be changed after
252.Fn sio_start
253has been called,
254.Fn sio_stop
255must be called before parameters can be changed.
256.Pp
257If the device is exposed by the
258.Xr sndiod 8
259server, which is the default configuration,
260a transparent emulation layer will
261automatically be set up, and in this case any combination of
262rate, encoding and numbers of channels is supported.
263.Pp
264To ease filling the
265.Vt sio_par
266structure, the
267following macros can be used:
268.Bl -tag -width "SIO_BPS(bits)"
269.It Dv SIO_BPS Ns Pq Fa bits
270Return the smallest value for
271.Va bps
272that is a power of two and that is large enough to
273hold
274.Fa bits .
275.It Dv SIO_LE_NATIVE
276Can be used to set the
277.Va le
278parameter when native byte order is required.
279.El
280.Ss Getting device capabilities
281There's no way to get an exhaustive list of all parameter
282combinations the device supports.
283Applications that need to have a set of working
284parameter combinations in advance can use the
285.Fn sio_getcap
286function.
287.Pp
288The
289.Vt sio_cap
290structure contains the list of parameter configurations.
291Each configuration contains multiple parameter sets.
292The application must examine all configurations, and
293choose its parameter set from
294.Em one
295of the configurations.
296Parameters of different configurations
297.Em are not
298usable together.
299.Bd -literal
300struct sio_cap {
301	struct sio_enc {		/* allowed encodings */
302		unsigned int bits;
303		unsigned int bps;
304		unsigned int sig;
305		unsigned int le;
306		unsigned int msb;
307	} enc[SIO_NENC];
308	unsigned int rchan[SIO_NCHAN];	/* allowed rchans */
309	unsigned int pchan[SIO_NCHAN];	/* allowed pchans */
310	unsigned int rate[SIO_NRATE];	/* allowed rates */
311	unsigned int nconf;		/* num. of confs[] */
312	struct sio_conf {
313		unsigned int enc;	/* bitmask of enc[] indexes */
314		unsigned int rchan;	/* bitmask of rchan[] indexes */
315		unsigned int pchan;	/* bitmask of pchan[] indexes */
316		unsigned int rate;	/* bitmask of rate[] indexes */
317	} confs[SIO_NCONF];
318};
319.Ed
320.Pp
321The parameters are as follows:
322.Bl -tag -width "rchan[SIO_NCHAN]"
323.It Va enc Ns Bq Dv SIO_NENC
324Array of supported encodings.
325The tuple of
326.Va bits ,
327.Va bps ,
328.Va sig ,
329.Va le ,
330and
331.Va msb
332parameters are usable in the corresponding parameters
333of the
334.Vt sio_par
335structure.
336.It Va rchan Ns Bq Dv SIO_NCHAN
337Array of supported channel numbers for recording usable
338in the
339.Vt sio_par
340structure.
341.It Va pchan Ns Bq Dv SIO_NCHAN
342Array of supported channel numbers for playback usable
343in the
344.Vt sio_par
345structure.
346.It Va rate Ns Bq Dv SIO_NRATE
347Array of supported sample rates usable
348in the
349.Vt sio_par
350structure.
351.It Va nconf
352Number of different configurations available, i.e. number
353of filled elements of the
354.Va confs[]
355array.
356.It Va confs Ns Bq Dv SIO_NCONF
357Array of available configurations.
358Each configuration contains bitmasks indicating which
359elements of the above parameter arrays are valid for the
360given configuration.
361For instance, if the second bit of
362.Va rate
363is set, in the
364.Vt sio_conf
365structure, then the second element of the
366.Va rate Ns Bq Dv SIO_NRATE
367array of the
368.Vt sio_cap
369structure is valid for this configuration.
370.El
371.Ss Starting and stopping the device
372The
373.Fn sio_start
374function puts the device in a waiting state:
375the device will wait for playback data to be provided
376(using the
377.Fn sio_write
378function).
379Once enough data is queued to ensure that play buffers
380will not underrun, actual playback is started automatically.
381If record mode only is selected, then recording starts
382immediately.
383In full-duplex mode, playback and recording will start
384synchronously as soon as enough data to play is available.
385.Pp
386The
387.Fn sio_stop
388function puts the audio subsystem
389in the same state as before
390.Fn sio_start
391is called.
392It stops recording, drains the play buffer and then stops playback.
393If samples to play are queued but playback hasn't started yet
394then playback is forced immediately; playback will actually stop
395once the buffer is drained.
396In no case are samples in the play buffer discarded.
397.Ss Playing and recording
398When record mode is selected, the
399.Fn sio_read
400function must be called to retrieve recorded data; it must be called
401often enough to ensure that internal buffers will not overrun.
402It will store at most
403.Fa nbytes
404bytes at the
405.Fa addr
406location and return the number of bytes stored.
407Unless the
408.Fa nbio_flag
409flag is set, it will block until data becomes available and
410will return zero only on error.
411.Pp
412Similarly, when play mode is selected, the
413.Fn sio_write
414function must be called to provide data to play.
415Unless the
416.Fa nbio_flag
417is set,
418.Fn sio_write
419will block until the requested amount of data is written.
420.Ss Non-blocking mode operation
421If the
422.Fa nbio_flag
423is set on
424.Fn sio_open ,
425then the
426.Fn sio_read
427and
428.Fn sio_write
429functions will never block; if no data is available, they will
430return zero immediately.
431.Pp
432The
433.Xr poll 2
434system call can be used to check if data can be
435read from or written to the device.
436The
437.Fn sio_pollfd
438function fills the array
439.Fa pfd
440of
441.Vt pollfd
442structures, used by
443.Xr poll 2 ,
444with
445.Fa events ;
446the latter is a bit-mask of
447.Dv POLLIN
448and
449.Dv POLLOUT
450constants; refer to
451.Xr poll 2
452for more details.
453.Fn sio_pollfd
454returns the number of
455.Vt pollfd
456structures filled.
457The
458.Fn sio_revents
459function returns the bit-mask set by
460.Xr poll 2
461in the
462.Fa pfd
463array of
464.Vt pollfd
465structures.
466If
467.Dv POLLIN
468is set, recorded samples are available in the device buffer
469and can be read with
470.Fn sio_read .
471If
472.Dv POLLOUT
473is set, space is available in the device buffer and new samples
474to play can be submitted with
475.Fn sio_write .
476.Dv POLLHUP
477may be set if an error occurs, even if
478it is not selected with
479.Fn sio_pollfd .
480.Pp
481The
482.Fn sio_nfds
483function returns the number of
484.Vt pollfd
485structures the caller must preallocate in order to be sure
486that
487.Fn sio_pollfd
488will never overrun.
489.Ss Synchronizing non-audio events to the audio stream in real-time
490In order to perform actions at precise positions of the audio stream,
491such as displaying video in sync with the audio stream,
492the application must be notified in real-time of the exact
493position in the stream the hardware is processing.
494.Pp
495The
496.Fn sio_onmove
497function can be used to register the
498.Fn cb
499callback function called at regular time intervals.
500The
501.Fa delta
502argument contains the number of frames the hardware played and/or recorded
503since the last call of
504.Fn cb .
505It is called by
506.Fn sio_read ,
507.Fn sio_write ,
508and
509.Fn sio_revents .
510When the first sample is played and/or recorded, right after the device starts,
511the callback is invoked with a zero
512.Fa delta
513argument.
514The value of the
515.Fa arg
516pointer is passed to the callback and can contain anything.
517.Pp
518If desired, the application can maintain the current position by
519starting from zero (when
520.Fn sio_start
521is called) and adding to the current position
522.Fa delta
523every time
524.Fn cb
525is called.
526.Ss Measuring the latency and buffers usage
527The playback latency is the delay it will take for the
528frame just written to become audible, expressed in number of frames.
529The exact playback
530latency can be obtained by subtracting the current position
531from the number of frames written.
532Once playback is actually started (first sample audible)
533the latency will never exceed the
534.Va bufsz
535parameter (see the sections above).
536There's a phase during which
537.Fn sio_write
538only queues data;
539once there's enough data, actual playback starts.
540During this phase talking about latency is meaningless.
541.Pp
542In any cases, at most
543.Va bufsz
544frames are buffered.
545This value takes into account all buffers.
546The number of frames stored is equal to the number of frames
547written minus the current position.
548.Pp
549The recording latency is obtained similarly, by subtracting
550the number of frames read from the current position.
551.Pp
552Note that
553.Fn sio_write
554might block even if there is buffer space left;
555using the buffer usage to guess if
556.Fn sio_write
557would block is false and leads to unreliable programs \(en consider using
558.Xr poll 2
559for this.
560.Ss Handling buffer overruns and underruns
561When the application cannot accept recorded data fast enough,
562the record buffer (of size
563.Va appbufsz )
564might overrun; in this case recorded data is lost.
565Similarly if the application cannot provide data to play
566fast enough, the play buffer underruns and silence is played
567instead.
568Depending on the
569.Va xrun
570parameter of the
571.Vt sio_par
572structure, the audio subsystem will behave as follows:
573.Bl -tag -width "SIO_IGNORE"
574.It Dv SIO_IGNORE
575The devices pauses during overruns and underruns,
576thus the current position (obtained through
577.Fn sio_onmove )
578stops being incremented.
579Once the overrun and/or underrun condition is gone, the device resumes;
580play and record are always kept in sync.
581With this mode, the application cannot notice
582underruns and/or overruns and shouldn't care about them.
583.Pp
584This mode is the default.
585It's suitable for applications,
586like audio players and telephony, where time
587is not important and overruns or underruns are not short.
588.It Dv SIO_SYNC
589If the play buffer underruns, then silence is played,
590but in order to reach the right position in time,
591the same amount of written samples will be
592discarded once the application is unblocked.
593Similarly, if the record buffer overruns, then
594samples are discarded, but the same amount of silence will be
595returned later.
596The current position (obtained through
597.Fn sio_onmove )
598is still incremented.
599When the play buffer underruns the play latency might become negative;
600when the record buffer overruns, the record latency might become
601larger than
602.Va bufsz .
603.Pp
604This mode is suitable for applications, like music production,
605where time is important and where underruns or overruns are
606short and rare.
607.It Dv SIO_ERROR
608With this mode, on the first play buffer underrun or
609record buffer overrun, playback and/or recording is terminated and
610no other function than
611.Fn sio_close
612will succeed.
613.Pp
614This mode is mostly useful for testing.
615.El
616.Ss Controlling the volume
617The
618.Fn sio_setvol
619function can be used to set playback attenuation.
620The
621.Fa vol
622parameter takes a value between 0 (maximum attenuation)
623and
624.Dv SIO_MAXVOL
625(no attenuation).
626It specifies the weight the audio subsystem will
627give to this stream.
628It is not meant to control hardware parameters like
629speaker gain; the
630.Xr mixerctl 1
631interface should be used for that purpose instead.
632.Pp
633An application can use the
634.Fn sio_onvol
635function to register a callback function that
636will be called each time the volume is changed,
637including when
638.Fn sio_setvol
639is used.
640The callback is always invoked when
641.Fn sio_onvol
642is called in order to provide the initial volume.
643An application can safely assume that once
644.Fn sio_onvol
645has returned a non-zero value,
646the callback has been invoked and thus
647the current volume is available.
648If there's no volume setting available,
649.Fn sio_onvol
650returns 0 and the callback is never invoked and calls to
651.Fn sio_setvol
652are ignored.
653.Pp
654The
655.Fn sio_onvol
656function can be called with a NULL argument to check whether
657a volume knob is available.
658.Ss Error handling
659Errors related to the audio subsystem
660(like hardware errors, dropped connections) and
661programming errors (e.g. call to
662.Fn sio_read
663on a play-only stream) are considered fatal.
664Once an error occurs, all functions taking a
665.Fa sio_hdl
666argument, except
667.Fn sio_close
668and
669.Fn sio_eof ,
670stop working (i.e. always return 0).
671.Pp
672The
673.Fn sio_eof
674function can be used at any stage;
675it returns 0 if there's no pending error, and a non-zero
676value if there's an error.
677.Ss Use with Xr pledge 2
678If the
679.Nm sndio
680library is used in combination with
681.Xr pledge 2 ,
682then the
683.Fn sio_open
684function needs the
685.Va stdio ,
686.Va rpath ,
687.Va wpath ,
688.Va cpath ,
689.Va inet ,
690.Va unix ,
691.Va dns ,
692and
693.Va audio
694.Xr pledge 2
695promises.
696.Bl -bullet
697.It
698.Va rpath ,
699.Va wpath ,
700and
701.Va cpath
702are needed to read, write or create the authentication cookie
703.Pa ~/.aucat_cookie .
704.It
705.Va rpath ,
706.Va wpath ,
707and
708.Va audio
709are needed when the device is a local raw device.
710.It
711.Va unix
712is needed when the device is a local
713.Xr sndiod 8
714sub-device.
715.It
716.Va inet
717and
718.Va dns
719are needed when the device is a remote
720.Xr sndiod 8
721sub-device.
722.El
723.Pp
724Once no further calls to
725.Fn sio_open
726will be made, all these
727.Xr pledge 2
728promises may be dropped, except for the
729.Va audio
730promise.
731.Sh RETURN VALUES
732The
733.Fn sio_open
734function returns the newly created handle on success or NULL
735on failure.
736The
737.Fn sio_setpar ,
738.Fn sio_getpar ,
739.Fn sio_getcap ,
740.Fn sio_start ,
741.Fn sio_stop ,
742.Fn sio_pollfd ,
743and
744.Fn sio_setvol
745functions return 1 on success and 0 on failure.
746The
747.Fn sio_read
748and
749.Fn sio_write
750functions return the number of bytes transferred.
751.Sh ENVIRONMENT
752.Bl -tag -width "SNDIO_DEBUGXXX" -compact
753.It Ev AUDIODEVICE
754Device to use if
755.Fn sio_open
756is called with
757.Dv SIO_DEVANY
758as the
759.Fa name
760argument.
761.It Ev SNDIO_DEBUG
762The debug level:
763may be a value between 0 and 2.
764.El
765.Sh SEE ALSO
766.Xr pledge 2 ,
767.Xr audio 4 ,
768.Xr sndio 7 ,
769.Xr sndiod 8 ,
770.Xr audio 9
771.Sh BUGS
772The
773.Xr audio 4
774driver doesn't drain playback buffers, thus if sndio
775is used to directly access an
776.Xr audio 4
777device,
778the
779.Fn sio_stop
780function will stop playback immediately.
781.Pp
782If the application doesn't consume recorded data fast enough then
783.Dq "control messages"
784from the
785.Xr sndiod 8
786server are delayed and consequently
787.Fn sio_onmove
788callback or volume changes may be delayed.
789.Pp
790The
791.Fn sio_open ,
792.Fn sio_setpar ,
793.Fn sio_getpar ,
794.Fn sio_getcap ,
795.Fn sio_start ,
796and
797.Fn sio_stop
798functions may block for a very short period of time, thus they should
799be avoided in code sections where blocking is not desirable.
800