Thread Safe Buffer Filling/Draining
Members - Reputation: 565
Posted 21 August 2012 - 02:20 PM
This is the basic scenario, I have 2 threads, one of these threads handles audio "streaming". Basically the audio to be played is put into a ByteBuffer array from the main thread, the audio thread is responsible with pushing said data to the line device.
Now the thing is I can see alot of things going wrong and I can't seem to find a good example on the internet, hopefully someone here might be able to point me in the right direction. So these are my basic needs.
Say we have a ByteBuffer with capacity K, the ByteBuffer is continually filled with audio data and is draining equally as fast in order to now have a Buffer Overflow Exception. Now because of the nature of byte buffer its a little tricky because of its positioning, I need it to act basically like a Queue in First in First out order, I want the new data to be automatically be appended to the end of the tail while reading from the head. I'm able to do said things in a kind of patch work type manner right now, but I feel it is open to data corruption (i.e it accidently writes the newested data a bit before the tail because the markers I keep were updated properly.
Should i try to tackle this in another way without using ByteBuffer? or is there a psuecode type manner to implement this with the ByteBuffer. Thank you for your time.
Members - Reputation: 638
Posted 22 August 2012 - 12:29 AM
On the other hand, it might make more sense and be easier to manage to just use a queue of audio chunks instead of a single byte array. Then you can just use a basic thread-safe queue for pushing/popping chunks on and off the queue. If you use a pool of pre-allocated chunks it will probably be more efficient too.
Edited by krippy2k8, 22 August 2012 - 12:30 AM.