1.\" $OpenBSD: sio_open.3,v 1.46 2017/01/03 20:29:28 natano 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: January 3 2017 $ 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. 453The 454.Fn sio_revents 455function returns the bit-mask set by 456.Xr poll 2 457in the 458.Fa pfd 459array of 460.Vt pollfd 461structures. 462If 463.Dv POLLIN 464is set, recorded samples are available in the device buffer 465and can be read with 466.Fn sio_read . 467If 468.Dv POLLOUT 469is set, space is available in the device buffer and new samples 470to play can be submitted with 471.Fn sio_write . 472.Dv POLLHUP 473may be set if an error occurs, even if 474it is not selected with 475.Fn sio_pollfd . 476.Pp 477The size of the 478.Ar pfd 479array, which the caller must pre-allocate, is provided by the 480.Fn sio_nfds 481function. 482.Ss Synchronizing non-audio events to the audio stream in real-time 483In order to perform actions at precise positions of the audio stream, 484such as displaying video in sync with the audio stream, 485the application must be notified in real-time of the exact 486position in the stream the hardware is processing. 487.Pp 488The 489.Fn sio_onmove 490function can be used to register the 491.Fn cb 492callback function called at regular time intervals. 493The 494.Fa delta 495argument contains the number of frames the hardware played and/or recorded 496since the last call of 497.Fn cb . 498It is called by 499.Fn sio_read , 500.Fn sio_write , 501and 502.Fn sio_revents . 503When the first sample is played and/or recorded, right after the device starts, 504the callback is invoked with a zero 505.Fa delta 506argument. 507The value of the 508.Fa arg 509pointer is passed to the callback and can contain anything. 510.Pp 511If desired, the application can maintain the current position by 512starting from zero (when 513.Fn sio_start 514is called) and adding to the current position 515.Fa delta 516every time 517.Fn cb 518is called. 519.Ss Measuring the latency and buffers usage 520The playback latency is the delay it will take for the 521frame just written to become audible, expressed in number of frames. 522The exact playback 523latency can be obtained by subtracting the current position 524from the number of frames written. 525Once playback is actually started (first sample audible) 526the latency will never exceed the 527.Va bufsz 528parameter (see the sections above). 529There's a phase during which 530.Fn sio_write 531only queues data; 532once there's enough data, actual playback starts. 533During this phase talking about latency is meaningless. 534.Pp 535In any cases, at most 536.Va bufsz 537frames are buffered. 538This value takes into account all buffers. 539The number of frames stored is equal to the number of frames 540written minus the current position. 541.Pp 542The recording latency is obtained similarly, by subtracting 543the number of frames read from the current position. 544.Pp 545Note that 546.Fn sio_write 547might block even if there is buffer space left; 548using the buffer usage to guess if 549.Fn sio_write 550would block is false and leads to unreliable programs \(en consider using 551.Xr poll 2 552for this. 553.Ss Handling buffer overruns and underruns 554When the application cannot accept recorded data fast enough, 555the record buffer (of size 556.Va appbufsz ) 557might overrun; in this case recorded data is lost. 558Similarly if the application cannot provide data to play 559fast enough, the play buffer underruns and silence is played 560instead. 561Depending on the 562.Va xrun 563parameter of the 564.Vt sio_par 565structure, the audio subsystem will behave as follows: 566.Bl -tag -width "SIO_IGNORE" 567.It Dv SIO_IGNORE 568The devices pauses during overruns and underruns, 569thus the current position (obtained through 570.Fn sio_onmove ) 571stops being incremented. 572Once the overrun and/or underrun condition is gone, the device resumes; 573play and record are always kept in sync. 574With this mode, the application cannot notice 575underruns and/or overruns and shouldn't care about them. 576.Pp 577This mode is the default. 578It's suitable for applications, 579like audio players and telephony, where time 580is not important and overruns or underruns are not short. 581.It Dv SIO_SYNC 582If the play buffer underruns, then silence is played, 583but in order to reach the right position in time, 584the same amount of written samples will be 585discarded once the application is unblocked. 586Similarly, if the record buffer overruns, then 587samples are discarded, but the same amount of silence will be 588returned later. 589The current position (obtained through 590.Fn sio_onmove ) 591is still incremented. 592When the play buffer underruns the play latency might become negative; 593when the record buffer overruns, the record latency might become 594larger than 595.Va bufsz . 596.Pp 597This mode is suitable for applications, like music production, 598where time is important and where underruns or overruns are 599short and rare. 600.It Dv SIO_ERROR 601With this mode, on the first play buffer underrun or 602record buffer overrun, playback and/or recording is terminated and 603no other function than 604.Fn sio_close 605will succeed. 606.Pp 607This mode is mostly useful for testing. 608.El 609.Ss Controlling the volume 610The 611.Fn sio_setvol 612function can be used to set playback attenuation. 613The 614.Fa vol 615parameter takes a value between 0 (maximum attenuation) 616and 617.Dv SIO_MAXVOL 618(no attenuation). 619It specifies the weight the audio subsystem will 620give to this stream. 621It is not meant to control hardware parameters like 622speaker gain; the 623.Xr mixerctl 1 624interface should be used for that purpose instead. 625.Pp 626An application can use the 627.Fn sio_onvol 628function to register a callback function that 629will be called each time the volume is changed, 630including when 631.Fn sio_setvol 632is used. 633The callback is always invoked when 634.Fn sio_onvol 635is called in order to provide the initial volume. 636An application can safely assume that once 637.Fn sio_onvol 638has returned a non-zero value, 639the callback has been invoked and thus 640the current volume is available. 641If there's no volume setting available, 642.Fn sio_onvol 643returns 0 and the callback is never invoked and calls to 644.Fn sio_setvol 645are ignored. 646.Pp 647The 648.Fn sio_onvol 649function can be called with a NULL argument to check whether 650a volume knob is available. 651.Ss Error handling 652Errors related to the audio subsystem 653(like hardware errors, dropped connections) and 654programming errors (e.g. call to 655.Fn sio_read 656on a play-only stream) are considered fatal. 657Once an error occurs, all functions taking a 658.Fa sio_hdl 659argument, except 660.Fn sio_close 661and 662.Fn sio_eof , 663stop working (i.e. always return 0). 664The 665.Fn sio_eof 666function can be used at any stage. 667.Ss Use with Xr pledge 2 668If the 669.Nm sndio 670library is used in combination with 671.Xr pledge 2 , 672then the 673.Fn sio_open 674function needs the 675.Va stdio , 676.Va rpath , 677.Va wpath , 678.Va cpath , 679.Va inet , 680.Va unix , 681.Va dns , 682and 683.Va audio 684.Xr pledge 2 685promises. 686.Bl -bullet 687.It 688.Va rpath , 689.Va wpath , 690and 691.Va cpath 692are needed to read, write or create the authentication cookie 693.Pa ~/.aucat_cookie . 694.It 695.Va rpath , 696.Va wpath , 697and 698.Va audio 699are needed when the device is a local raw device. 700.It 701.Va unix 702is needed when the device is a local 703.Xr sndiod 8 704sub-device. 705.It 706.Va inet 707and 708.Va dns 709are needed when the device is a remote 710.Xr sndiod 8 711sub-device. 712.El 713.Pp 714Once no further calls to 715.Fn sio_open 716will be made, all these 717.Xr pledge 2 718promises may be dropped, except for the 719.Va audio 720promise. 721.Sh RETURN VALUES 722The 723.Fn sio_open 724function returns the newly created handle on success or NULL 725on failure. 726.Pp 727The 728.Fn sio_setpar , 729.Fn sio_getpar , 730.Fn sio_getcap , 731.Fn sio_start , 732.Fn sio_stop , 733and 734.Fn sio_setvol 735functions return 1 on success and 0 on failure. 736.Pp 737The 738.Fn sio_pollfd 739function returns the number of 740.Va pollfd 741structures filled. 742The 743.Fn sio_nfds 744function returns the number of 745.Va pollfd 746structures the caller must preallocate in order to be sure 747that 748.Fn sio_pollfd 749will never overrun. 750.Pp 751The 752.Fn sio_read 753and 754.Fn sio_write 755functions return the number of bytes transferred. 756.Pp 757The 758.Fn sio_eof 759function returns 0 if there's no pending error, and a non-zero 760value if there's an error. 761.Sh ENVIRONMENT 762.Bl -tag -width "SNDIO_DEBUGXXX" -compact 763.It Ev AUDIODEVICE 764Device to use if 765.Fn sio_open 766is called with 767.Dv SIO_DEVANY 768as the 769.Fa name 770argument. 771.It Ev SNDIO_DEBUG 772The debug level: 773may be a value between 0 and 2. 774.El 775.Sh SEE ALSO 776.Xr pledge 2 , 777.Xr audio 4 , 778.Xr sndio 7 , 779.Xr sndiod 8 , 780.Xr audio 9 781.Sh BUGS 782The 783.Xr audio 4 784driver doesn't drain playback buffers, thus if sndio 785is used to directly access an 786.Xr audio 4 787device, 788the 789.Fn sio_stop 790function will stop playback immediately. 791.Pp 792If the application doesn't consume recorded data fast enough then 793.Dq "control messages" 794from the 795.Xr sndiod 8 796server are delayed and consequently 797.Fn sio_onmove 798callback or volume changes may be delayed. 799.Pp 800The 801.Fn sio_open , 802.Fn sio_setpar , 803.Fn sio_getpar , 804.Fn sio_getcap , 805.Fn sio_start , 806and 807.Fn sio_stop 808functions may block for a very short period of time, thus they should 809be avoided in code sections where blocking is not desirable. 810