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