Detect CPU overload and stop audio

I am using Juce AudioPluginHost.
I would like to know if there is a way to detect CPU overload and stop the audio at this point (much like Logic or ProTools does).
I am experiencing stuttering audio and crashes of CoreAudio when using some audio interfaces and getting to a point that the CPU load is 100%.
I know this kind of thing is not deterministic and can variate between systems, but I am looking for some starting point that will cover most of the cases.

I am using this to get the CPU reading:

    auto cpu = deviceManager.getCpuUsage() * 100;
    cpuUsageText->setButtonText (juce::String (cpu, 6) + " % Audio engine CPU");


Check out AudioIODevice::getXRunCount()

You could monitor this for changes and react accordingly.

Thanks for this answer, looks like I have something working.
Now I have managed to implement an underruns counter.
The strange thing is that I see underruns much before I actually can hear any problem in sound,
I’m probably doing something wrong… but when I monitor a 400khz sine wave, when the channel is at input monitoring (in > to > out) - I see underruns in my counter running pretty fast but the audio has no drops at all.
Any suggestion?


If I’ve got this the right way around, underruns are when the input buffer runs empty so your audio processor has no data to pick up and process. So if you happen to be synthesising a sine wave, then you don’t care that there is no input data and you keep happily synthesising an output (unless there’s a buffer overrun of course!).

If you’re monitoring an input sine wave, then you should hear glitches when there is an underrun - unless the block sizes are very small perhaps.