andrewrk / libsoundio

C library for cross-platform real-time audio input and output
http://libsound.io/
MIT License
1.94k stars 228 forks source link

Restrictions on soundio_{in,out}stream_get_latency() #118

Open iskunk opened 7 years ago

iskunk commented 7 years ago

The documentation for the two soundio_{in,out}stream_get_latency() functions specifies that they must only be called from the read or write callbacks, respectively. (Presumably due to the fact that they access non-thread-safe variables maintained by the capture/playback thread.)

I think this is prone to misuse---many developers will no doubt call this function from their application thread, and when told that this is incorrect, respond with "Hey, it works fine... it's never given me a problem."

I'd like to suggest the possibility of adding a double *out_latency parameter to the read/write begin or end functions. The user can pass in a variable pointer if they want to know the latency, or NULL otherwise. Because the means of obtaining this information is one and the same with the begin/end functions, there is no separate function to misuse.

Also: The documentation for soundio_outstream_get_latency() indicates that it is normally called right after soundio_outstream_end_write(), suggesting that this function should be the one to gain the out_latency parameter. But perhaps it may be more useful if the latency can be obtained from _begin_write(), because then the write callback would be able to conditionally write one set of samples or another depending on the specific value of that latency.

iskunk commented 7 years ago

Oh, one additional thing I wanted to mention.

I'd like to suggest returning the latency not as the (fractional) number of seconds between "now" and the moment that the last sample currently in the buffer is played, but as the absolute time (e.g. CLOCK_MONOTONIC) when this is expected to occur, in the future.

The problem with returning the latency as a small time delta is that this information obviously has a very short shelf life. If you get back that the latency is e.g. 0.2 seconds, and then you do some computation that takes some number of milliseconds, you're not still going to have 0.2 seconds when that's done. IMHO, it would be more useful to give an absolute timestamp, because that datum will remain valid for as long as the buffer is not modified (and playback is not interrupted).

andrewrk commented 7 years ago

I think these are all good suggestions, scheduled for v2.