Potential integer overflow with MemoryAudioSource's position

Hi there,

is there any reason why the MemoryAudioSource’s int position variable isn’t wrapped around while looping?

Within the getNextAudioBlock (see JUCE/juce_MemoryAudioSource.cpp at fbe95b0b073ccb589e28255cb0cd56e1382dc2c9 · juce-framework/JUCE · GitHub) the value of position is always increasing. It might overflow sooner or later (probably later).

The temporary copy of it int i = position; actually gets modulo`d within the process loop, however, once wrapped around this might yield a negative value, and from there I expect things to go south. (Haven’t actually waited for the overflow).

Even though the statements within the loop might catch that (haven’t had a deeper look into it, yet), it makes it quite inconvenient to compute the current progress as I expected it to be:

auto progress = static_cast<float> (getNextReadPosition()) / getTotalLength();

which will get bigger and bigger unless I perform the modulo myself:

auto progress = static_cast<float> (getNextReadPosition() % getTotalLength()) / getTotalLength();

Which I wouldn’t have expected having it to perform myself.

This might be related to my post here?

Indeed! Your proposal would definitely fix the progress behavior.

Still wondering why getNextReadPosition returns the total number of read samples since playback, which inevitably will overflow some time.

Here’s a PIP producing the overflow. I set the source’s samplerate very high so the position variable advances fast, also set the initial start to a quite high value.


void MemoryAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)

I added DBG (std::numeric_limits< **int** >::max() - position); so the Debugger shows a countdown when it will happen (a couple of seconds @44.1kHz).

Once the overflow occurs, an assertion in AudioBuffer.copyFrom() is triggered.

WARNING: turn down the volume when you try it. Without the debugger attached I assume garbage is played back.

IndexOverflowPIP.h (2.6 KB)

1 Like