1.\" $OpenBSD: sio_open.3,v 1.48 2019/01/18 08:43:49 ratchov 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 18 2019 $ 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. 287However, for most new applications it's generally 288not recommended to use 289.Fn sio_getcap . 290Instead, follow the recommendations for negotiating 291device parameters (see above). 292.Pp 293The 294.Vt sio_cap 295structure contains the list of parameter configurations. 296Each configuration contains multiple parameter sets. 297The application must examine all configurations, and 298choose its parameter set from 299.Em one 300of the configurations. 301Parameters of different configurations 302.Em are not 303usable together. 304.Bd -literal 305struct sio_cap { 306 struct sio_enc { /* allowed encodings */ 307 unsigned int bits; 308 unsigned int bps; 309 unsigned int sig; 310 unsigned int le; 311 unsigned int msb; 312 } enc[SIO_NENC]; 313 unsigned int rchan[SIO_NCHAN]; /* allowed rchans */ 314 unsigned int pchan[SIO_NCHAN]; /* allowed pchans */ 315 unsigned int rate[SIO_NRATE]; /* allowed rates */ 316 unsigned int nconf; /* num. of confs[] */ 317 struct sio_conf { 318 unsigned int enc; /* bitmask of enc[] indexes */ 319 unsigned int rchan; /* bitmask of rchan[] indexes */ 320 unsigned int pchan; /* bitmask of pchan[] indexes */ 321 unsigned int rate; /* bitmask of rate[] indexes */ 322 } confs[SIO_NCONF]; 323}; 324.Ed 325.Pp 326The parameters are as follows: 327.Bl -tag -width "rchan[SIO_NCHAN]" 328.It Va enc Ns Bq Dv SIO_NENC 329Array of supported encodings. 330The tuple of 331.Va bits , 332.Va bps , 333.Va sig , 334.Va le , 335and 336.Va msb 337parameters are usable in the corresponding parameters 338of the 339.Vt sio_par 340structure. 341.It Va rchan Ns Bq Dv SIO_NCHAN 342Array of supported channel numbers for recording usable 343in the 344.Vt sio_par 345structure. 346.It Va pchan Ns Bq Dv SIO_NCHAN 347Array of supported channel numbers for playback usable 348in the 349.Vt sio_par 350structure. 351.It Va rate Ns Bq Dv SIO_NRATE 352Array of supported sample rates usable 353in the 354.Vt sio_par 355structure. 356.It Va nconf 357Number of different configurations available, i.e. number 358of filled elements of the 359.Va confs[] 360array. 361.It Va confs Ns Bq Dv SIO_NCONF 362Array of available configurations. 363Each configuration contains bitmasks indicating which 364elements of the above parameter arrays are valid for the 365given configuration. 366For instance, if the second bit of 367.Va rate 368is set, in the 369.Vt sio_conf 370structure, then the second element of the 371.Va rate Ns Bq Dv SIO_NRATE 372array of the 373.Vt sio_cap 374structure is valid for this configuration. 375As such, when reading the array elements in the 376.Vt sio_cap 377structure, the corresponding 378.Vt sio_conf 379bitmasks should always be used. 380.El 381.Ss Starting and stopping the device 382The 383.Fn sio_start 384function puts the device in a waiting state: 385the device will wait for playback data to be provided 386(using the 387.Fn sio_write 388function). 389Once enough data is queued to ensure that play buffers 390will not underrun, actual playback is started automatically. 391If record mode only is selected, then recording starts 392immediately. 393In full-duplex mode, playback and recording will start 394synchronously as soon as enough data to play is available. 395.Pp 396The 397.Fn sio_stop 398function puts the audio subsystem 399in the same state as before 400.Fn sio_start 401is called. 402It stops recording, drains the play buffer and then stops playback. 403If samples to play are queued but playback hasn't started yet 404then playback is forced immediately; playback will actually stop 405once the buffer is drained. 406In no case are samples in the play buffer discarded. 407.Ss Playing and recording 408When record mode is selected, the 409.Fn sio_read 410function must be called to retrieve recorded data; it must be called 411often enough to ensure that internal buffers will not overrun. 412It will store at most 413.Fa nbytes 414bytes at the 415.Fa addr 416location and return the number of bytes stored. 417Unless the 418.Fa nbio_flag 419flag is set, it will block until data becomes available and 420will return zero only on error. 421.Pp 422Similarly, when play mode is selected, the 423.Fn sio_write 424function must be called to provide data to play. 425Unless the 426.Fa nbio_flag 427is set, 428.Fn sio_write 429will block until the requested amount of data is written. 430.Ss Non-blocking mode operation 431If the 432.Fa nbio_flag 433is set on 434.Fn sio_open , 435then the 436.Fn sio_read 437and 438.Fn sio_write 439functions will never block; if no data is available, they will 440return zero immediately. 441.Pp 442The 443.Xr poll 2 444system call can be used to check if data can be 445read from or written to the device. 446The 447.Fn sio_pollfd 448function fills the array 449.Fa pfd 450of 451.Vt pollfd 452structures, used by 453.Xr poll 2 , 454with 455.Fa events ; 456the latter is a bit-mask of 457.Dv POLLIN 458and 459.Dv POLLOUT 460constants; refer to 461.Xr poll 2 462for more details. 463The 464.Fn sio_revents 465function returns the bit-mask set by 466.Xr poll 2 467in the 468.Fa pfd 469array of 470.Vt pollfd 471structures. 472If 473.Dv POLLIN 474is set, recorded samples are available in the device buffer 475and can be read with 476.Fn sio_read . 477If 478.Dv POLLOUT 479is set, space is available in the device buffer and new samples 480to play can be submitted with 481.Fn sio_write . 482.Dv POLLHUP 483may be set if an error occurs, even if 484it is not selected with 485.Fn sio_pollfd . 486.Pp 487The size of the 488.Ar pfd 489array, which the caller must pre-allocate, is provided by the 490.Fn sio_nfds 491function. 492.Ss Synchronizing non-audio events to the audio stream in real-time 493In order to perform actions at precise positions of the audio stream, 494such as displaying video in sync with the audio stream, 495the application must be notified in real-time of the exact 496position in the stream the hardware is processing. 497.Pp 498The 499.Fn sio_onmove 500function can be used to register the 501.Fn cb 502callback function called at regular time intervals. 503The 504.Fa delta 505argument contains the number of frames the hardware played and/or recorded 506since the last call of 507.Fn cb . 508It is called by 509.Fn sio_read , 510.Fn sio_write , 511and 512.Fn sio_revents . 513When the first sample is played and/or recorded, right after the device starts, 514the callback is invoked with a zero 515.Fa delta 516argument. 517The value of the 518.Fa arg 519pointer is passed to the callback and can contain anything. 520.Pp 521If desired, the application can maintain the current position by 522starting from zero (when 523.Fn sio_start 524is called) and adding to the current position 525.Fa delta 526every time 527.Fn cb 528is called. 529.Ss Measuring the latency and buffers usage 530The playback latency is the delay it will take for the 531frame just written to become audible, expressed in number of frames. 532The exact playback 533latency can be obtained by subtracting the current position 534from the number of frames written. 535Once playback is actually started (first sample audible) 536the latency will never exceed the 537.Va bufsz 538parameter (see the sections above). 539There's a phase during which 540.Fn sio_write 541only queues data; 542once there's enough data, actual playback starts. 543During this phase talking about latency is meaningless. 544.Pp 545In any cases, at most 546.Va bufsz 547frames are buffered. 548This value takes into account all buffers. 549The number of frames stored is equal to the number of frames 550written minus the current position. 551.Pp 552The recording latency is obtained similarly, by subtracting 553the number of frames read from the current position. 554.Pp 555Note that 556.Fn sio_write 557might block even if there is buffer space left; 558using the buffer usage to guess if 559.Fn sio_write 560would block is false and leads to unreliable programs \(en consider using 561.Xr poll 2 562for this. 563.Ss Handling buffer overruns and underruns 564When the application cannot accept recorded data fast enough, 565the record buffer (of size 566.Va appbufsz ) 567might overrun; in this case recorded data is lost. 568Similarly if the application cannot provide data to play 569fast enough, the play buffer underruns and silence is played 570instead. 571Depending on the 572.Va xrun 573parameter of the 574.Vt sio_par 575structure, the audio subsystem will behave as follows: 576.Bl -tag -width "SIO_IGNORE" 577.It Dv SIO_IGNORE 578The devices pauses during overruns and underruns, 579thus the current position (obtained through 580.Fn sio_onmove ) 581stops being incremented. 582Once the overrun and/or underrun condition is gone, the device resumes; 583play and record are always kept in sync. 584With this mode, the application cannot notice 585underruns and/or overruns and shouldn't care about them. 586.Pp 587This mode is the default. 588It's suitable for applications, 589like audio players and telephony, where time 590is not important and overruns or underruns are not short. 591.It Dv SIO_SYNC 592If the play buffer underruns, then silence is played, 593but in order to reach the right position in time, 594the same amount of written samples will be 595discarded once the application is unblocked. 596Similarly, if the record buffer overruns, then 597samples are discarded, but the same amount of silence will be 598returned later. 599The current position (obtained through 600.Fn sio_onmove ) 601is still incremented. 602When the play buffer underruns the play latency might become negative; 603when the record buffer overruns, the record latency might become 604larger than 605.Va bufsz . 606.Pp 607This mode is suitable for applications, like music production, 608where time is important and where underruns or overruns are 609short and rare. 610.It Dv SIO_ERROR 611With this mode, on the first play buffer underrun or 612record buffer overrun, playback and/or recording is terminated and 613no other function than 614.Fn sio_close 615will succeed. 616.Pp 617This mode is mostly useful for testing. 618.El 619.Ss Controlling the volume 620The 621.Fn sio_setvol 622function can be used to set playback attenuation. 623The 624.Fa vol 625parameter takes a value between 0 (maximum attenuation) 626and 627.Dv SIO_MAXVOL 628(no attenuation). 629It specifies the weight the audio subsystem will 630give to this stream. 631It is not meant to control hardware parameters like 632speaker gain; the 633.Xr mixerctl 1 634interface should be used for that purpose instead. 635.Pp 636An application can use the 637.Fn sio_onvol 638function to register a callback function that 639will be called each time the volume is changed, 640including when 641.Fn sio_setvol 642is used. 643The callback is always invoked when 644.Fn sio_onvol 645is called in order to provide the initial volume. 646An application can safely assume that once 647.Fn sio_onvol 648has returned a non-zero value, 649the callback has been invoked and thus 650the current volume is available. 651If there's no volume setting available, 652.Fn sio_onvol 653returns 0 and the callback is never invoked and calls to 654.Fn sio_setvol 655are ignored. 656.Pp 657The 658.Fn sio_onvol 659function can be called with a NULL argument to check whether 660a volume knob is available. 661.Ss Error handling 662Errors related to the audio subsystem 663(like hardware errors, dropped connections) and 664programming errors (e.g. call to 665.Fn sio_read 666on a play-only stream) are considered fatal. 667Once an error occurs, all functions taking a 668.Fa sio_hdl 669argument, except 670.Fn sio_close 671and 672.Fn sio_eof , 673stop working (i.e. always return 0). 674The 675.Fn sio_eof 676function can be used at any stage. 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 ~/.sndio/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. 736.Pp 737The 738.Fn sio_setpar , 739.Fn sio_getpar , 740.Fn sio_getcap , 741.Fn sio_start , 742.Fn sio_stop , 743and 744.Fn sio_setvol 745functions return 1 on success and 0 on failure. 746.Pp 747The 748.Fn sio_pollfd 749function returns the number of 750.Va pollfd 751structures filled. 752The 753.Fn sio_nfds 754function returns the number of 755.Va pollfd 756structures the caller must preallocate in order to be sure 757that 758.Fn sio_pollfd 759will never overrun. 760.Pp 761The 762.Fn sio_read 763and 764.Fn sio_write 765functions return the number of bytes transferred. 766.Pp 767The 768.Fn sio_eof 769function returns 0 if there's no pending error, and a non-zero 770value if there's an error. 771.Sh ENVIRONMENT 772.Bl -tag -width "SNDIO_DEBUGXXX" -compact 773.It Ev AUDIODEVICE 774Device to use if 775.Fn sio_open 776is called with 777.Dv SIO_DEVANY 778as the 779.Fa name 780argument. 781.It Ev SNDIO_DEBUG 782The debug level: 783may be a value between 0 and 2. 784.El 785.Sh SEE ALSO 786.Xr pledge 2 , 787.Xr audio 4 , 788.Xr sndio 7 , 789.Xr sndiod 8 , 790.Xr audio 9 791.Sh BUGS 792The 793.Xr audio 4 794driver doesn't drain playback buffers, thus if sndio 795is used to directly access an 796.Xr audio 4 797device, 798the 799.Fn sio_stop 800function will stop playback immediately. 801.Pp 802If the application doesn't consume recorded data fast enough then 803.Dq "control messages" 804from the 805.Xr sndiod 8 806server are delayed and consequently 807.Fn sio_onmove 808callback or volume changes may be delayed. 809.Pp 810The 811.Fn sio_open , 812.Fn sio_setpar , 813.Fn sio_getpar , 814.Fn sio_getcap , 815.Fn sio_start , 816and 817.Fn sio_stop 818functions may block for a very short period of time, thus they should 819be avoided in code sections where blocking is not desirable. 820