# BufferingAudioSource prepareToPlay blocks MessageThread

**URL:** <https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215>\
**Category:** General JUCE discussion\
**Created:** [September 22, 2016, 5:54pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215 "2016-09-22T17:54:56Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [September 22, 2016, 5:54pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/1 "2016-09-22T17:54:56Z")

</div>

I use BufferingAudioSources to buffer in the background. But they have a nice kickstart, which is to buffer already the first block in prepareToPlay, see:

> <https://github.com/WeAreROLI/JUCE/blob/develop/modules/juce_audio_basics/sources/juce_BufferingAudioSource.cpp>

My problem is, unfortunately I have an AudioReaderSource connected which doesn’t produce samples (probably a defective ogg file, I’m checking). But this means, I get in an infinite loop in the MessageThread, which invoked prepareToPlay.  
Normal behaviour for BufferingAudioSource, when the buffer is not valid is to produce silence. Does it make sense to block prepareToPlay until one block is read?  
IMHO there should be either a timeout or the while loop could be removed, because it will start in the background anyway… Or simply change the while into if, so it get’s started, but the rest is left for the background…

---

<div class="post-metadata">

**Author:** ![fr810](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/fr810/32/841_2.png) [@fr810](https://forum.juce.com/u/fr810)\
**Post date:** [September 23, 2016, 8:43am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/2 "2016-09-23T08:43:25Z")

</div>

Makes sense! See my latest commit on develop.

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [September 23, 2016, 9:57am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/3 "2016-09-23T09:57:13Z")

</div>

Great, thanks 🙂  
Would it be possible to add this other method regarding blocking and non-blocking from a while ago,  
a semaphore for non-realtime use of BufferingAudioThread, very handy to use multi threads for reading…

> [@BufferingAudioSource and non-realtime: waitForNextAudioBlock (with code)](https://forum.juce.com/t/bufferingaudiosource-and-non-realtime-waitfornextaudioblock-with-code/18118/2):
>
> I implemented this and it works for me: /\*\* Wait for buffer ready. This will block until the buffer is prepared. DO NOT USE IN REALTIME! \*/ bool BufferingAudioSource::waitForNextAudioBlockReady (const AudioSourceChannelInfo& info, const uint32 sleepMiliSecs, const uint32 timeout) { if (nextPlayPos + info.numSamples \< 0 || (! isLooping() && nextPlayPos \> getTotalLength())) { return true; } const uint32 endTime = Time::getMillisecondCounter () + timeout; int valid…

(a pity that this block quote always spoils the markup of the quoted post…)

---

<div class="post-metadata">

**Author:** ![fr810](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/fr810/32/841_2.png) [@fr810](https://forum.juce.com/u/fr810)\
**Post date:** [September 26, 2016, 8:00am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/4 "2016-09-26T08:00:58Z")

</div>

Hi daniel, I’m not quite sure I understand this one. If you processor is in offline mode, why don’t you just use the BufferingAudioSource’s underlying AudioSource directly?

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [September 26, 2016, 9:50am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/5 "2016-09-26T09:50:28Z")

</div>

Hi Fabian,  
because then all reading is done from one rendering thread.

I have a AudioProcessor, that mixes ~30 audiosources according to a special algorithm. If the getNextAudioBlock of the IO callback drives the whole chain from reading from disk to mixing, everything runs in one thread, i.e. on one CPU core.  
So I have the BufferingAudioSource to prepare the buffers. This uses TimeSliceThreads to distribute the load of reading (I use 4 threads, runs perfectly).

a) Situation live: everything is perfect, because the calls from the audio device are coming at a fixed interval, leaving enough time to read  
b) Situation rendering: the writer calls the mixing as fast as possible. So the background threads have not enough time to fetch the next audio block.

With the `bool waitForNextAudioBlockReady (const AudioSourceChannelInfo &, const int sleepMiliSecs=10, const uint32 timeout=500)` the reading is happening on several threads, but mixing is easy when using on the audioSource:

```
BufferingAudioSource source;
AudioSourceChannelInfo info (&buffer, 0, bufferSize);
if (isNonRealtime ())
    source.waitForNextAudioBlockReady (info);
source.getNextAudioBlock (info);

```

This way you can easily synchronize the threads.

Does this make sense?  
Thanks for your time

_Correction for the wait method: don’t block if source cannot produce any samples:_

```
/** Wait for buffer ready. This will block until the buffer is prepared. DO NOT USE IN REALTIME! */
bool BufferingAudioSource::waitForNextAudioBlockReady (const AudioSourceChannelInfo& info, const int sleepMilliSecs, const uint32 timeout)
{
    if (!source || source->getTotalLength() <= 0)
        return false;

    if (nextPlayPos + info.numSamples < 0 ||
        (! isLooping() && nextPlayPos > getTotalLength())) {
        return true;
    }

    const uint32 endTime = Time::getMillisecondCounter () + timeout;
    int validStart;
    int validEnd;
    while (Time::getMillisecondCounter() < endTime) {
        {
            const ScopedLock sl (bufferStartPosLock);
            validStart = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos);
            validEnd = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos);
        }
        if (validStart <= 0 &&
            validStart < validEnd &&
            validEnd >= info.numSamples) {
            return true;
        }
        Thread::sleep (sleepMilliSecs);
    }

    return false;
}
```

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [September 26, 2016, 2:47pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/6 "2016-09-26T14:47:43Z")

</div>

Btw. if there is a better method for synchronising threads using BufferingAudioSources, I’m open for suggestions…

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [September 28, 2016, 8:07am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/7 "2016-09-28T08:07:20Z")

</div>

@Fabian: A function `int BufferingAudioSource::getNumReady()` similar to AbstractFIFO would be an alternative, even though I find the solution above easier to read, as I don’t have to write a loop everytime I want to wait for the buffering/decoding thread.

---

<div class="post-metadata">

**Author:** ![fr810](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/fr810/32/841_2.png) [@fr810](https://forum.juce.com/u/fr810)\
**Post date:** [September 28, 2016, 11:44am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/8 "2016-09-28T11:44:02Z")

</div>

No I like your original suggestion better. I’m working on it…

---

<div class="post-metadata">

**Author:** ![fr810](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/fr810/32/841_2.png) [@fr810](https://forum.juce.com/u/fr810)\
**Post date:** [September 30, 2016, 2:52pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/9 "2016-09-30T14:52:27Z")

</div>

OK I’ve implemented something on my on private repo. Can you head over there and check if this works for you?

[https://github.com/hogliux/JUCE/tree/feature/BlockingBufferingAudioSource](https://github.com/hogliux/JUCE/tree/feature/BlockingBufferingAudioSource)

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [September 30, 2016, 3:28pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/10 "2016-09-30T15:28:35Z")

</div>

Thanks, looks good. I didn’t know the WaitableEvent, that’s an interesting concept.  
But I’m afraid, it won’t work here. I don’t see, that the backgroundThread would signal the waiting thread.  
In this case the thread will wait the full timeout:

```
if (! bufferReadyEvent.wait (endTime - now))

```

So it actually will slow things down instead of speeding up.  
The alternative I proposed was to suspend the waiting thread for 5 ms and poll again. What’s your opinion on this?

Cheers

---

<div class="post-metadata">

**Author:** ![fr810](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/fr810/32/841_2.png) [@fr810](https://forum.juce.com/u/fr810)\
**Post date:** [September 30, 2016, 3:31pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/11 "2016-09-30T15:31:32Z")

</div>

No, the given time is the maximum time to wait. The corresponding signal is in the read thread ([here](https://github.com/hogliux/JUCE/blob/434393620f1ba9afd32a7933f5ecef04e5f4590b/modules/juce_audio_basics/sources/juce_BufferingAudioSource.cpp#L282)). The version with the WaitableEvent will normally be faster then any version with sleep as the thread will immediately be waken up when there is data to read - unless I have a bug in there somewhere 🙂

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [September 30, 2016, 3:37pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/12 "2016-09-30T15:37:12Z")

</div>

Nice, I thought I missed something. I forgot, that the working thread calls a method of BufferingAudioSource as well. And I overlooked that line in your commit.  
I will pull and try it out, but I am pretty sure it will work…

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [September 30, 2016, 5:33pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/13 "2016-09-30T17:33:43Z")

</div>

Unfortunately something is wrong…  
Initially it didn’t wait, so I got scrambled audio in my rendered file.  
But if I remove the static keyword, it works as expected (or use const as I did):

> <https://github.com/hogliux/JUCE/blob/434393620f1ba9afd32a7933f5ecef04e5f4590b/modules/juce_audio_basics/sources/juce_BufferingAudioSource.cpp#L173>

And the waitableEvent gives also a noticable speedup 🙂

---

<div class="post-metadata">

**Author:** ![fr810](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/fr810/32/841_2.png) [@fr810](https://forum.juce.com/u/fr810)\
**Post date:** [October 1, 2016, 9:35am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/14 "2016-10-01T09:35:14Z")

</div>

Wow I must have been completely beside myself yesterday: I wanted to write `const` not `static`?!? I’ve fixed it and merged it into develop.

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [October 1, 2016, 10:41am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/15 "2016-10-01T10:41:49Z")

</div>

…and I thought another trick using static that I don’t know of 😉  
Thanks for taking the time

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [October 4, 2016, 9:10am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/16 "2016-10-04T09:10:17Z")

</div>

Works perfect, thanks for adding (and for improving it)

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [November 18, 2016, 5:21pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/17 "2016-11-18T17:21:50Z")

</div>

Hi @Fabian,  
I use this function now in both, realtime and non-realtime like this:

```
    if (currentSource) {
        if (owningTheme->isNonRealtime()) {
            currentSource->waitForNextAudioBlockReady (bufferToFill, 500);
        }
        else {
            if (! currentSource->waitForNextAudioBlockReady (bufferToFill, 0)) {
                // we don't wait for wimps
                bufferDropout += 1;
            }
        }
        buffersPlayed += 1;
        currentSource->getNextAudioBlock(bufferToFill);
    }

```

But for this to work, the comparism on line 168 in BufferingAudioSource needs to be changed into less or equal:

```
uint32 now = Time::getMillisecondCounter();
const uint32 endTime = now + timeout;

while (now <= endTime)
//[...]

```

EDIT: and that change as well to make it not wait:

```
if ((endTime > now) && (! bufferReadyEvent.wait (static_cast<int> (endTime - now))))
        return false;

```

Do you think we could change that?

Thanks and have a nice weekend…

---

<div class="post-metadata">

**Author:** ![fr810](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/fr810/32/841_2.png) [@fr810](https://forum.juce.com/u/fr810)\
**Post date:** [November 21, 2016, 9:09am UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/18 "2016-11-21T09:09:07Z")

</div>

Yup makes sense. It’s on develop now.

---

<div class="post-metadata">

**Author:** ![chkn](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/chkn/32/3862_2.png) [@chkn](https://forum.juce.com/u/chkn)\
**Post date:** [November 21, 2016, 12:39pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/19 "2016-11-21T12:39:18Z")

</div>

Should the wrap around of the uint32 Time::getMillisecondCounter() should also be considered?

---

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/daniel/32/790_2.png) [@daniel](https://forum.juce.com/u/daniel)\
**Post date:** [November 21, 2016, 6:16pm UTC](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215/20 "2016-11-21T18:16:34Z")

</div>

Thanks @Fabian!

@chkn indeed, looking at the docs [Time::getMillisecondCounter()](https://www.juce.com/doc/classTime#a8aa2b95bb1fc2fd7a2df29736bad3a37) it is noted there. If it is really zero at startup, the problem will arise after 49 days. Still, it can happen…

[Next page](https://forum.juce.com/t/bufferingaudiosource-preparetoplay-blocks-messagethread/19215.md?page=2)
