[linux-audio-dev] lock-free ring buffer code

Steve Harris S.W.Harris at ecs.soton.ac.uk
Sat Apr 5 07:19:00 UTC 2003


There are many cases in audio software when you are only concerned with
reading single values at a time from the fifo and relative delays, then
its much simpler [from memory, syntax might be wrong]:

	unsigned int size = some_power_of_two
	unsigned int write_ptr = 0
	float buffer[size]

to write:
	buffer[write_ptr++ & (size - 1)] = written_val

to read:
	float read_val = buffer[(write_ptr - delay) & (size - 1)]

If you want catchup reads, thats:

	while (read_ptr != write_ptr)
		float read_val = buffer[read_ptr++ & (size - 1)]

The no braches and so on generally makes it worth going to the next power
of two for your buffer sizes, which is why you will see so many outboards
and plugins with 2.7 second maximum delays :)  48000 * 2.7 < 2^17

The % operator in C uses a branch (even when the operands are unsigned and
const 2^n AFAIK) and has implementation specific behaviour when you use
negative numbers :(

- Steve



More information about the Linux-audio-dev mailing list