getPlayhead and the Optional Template variables

I’m looking at reading information from the DAW host for the first time in my plugin, and I have not encountered this Optional class of variable before.

What I gather from the documentation and from consulting the docs also for std::optional is that this is for values that may or may not be there?

So are you supposed to be testing each value something like this?

(This is just some preliminary code I put in my processBlock() to store the info in member variables and printout out when it has changed.)

Member variables (in PluginProcessor class):
    Optional<double> tempoBPM;
    Optional<double> ppqPosition;
    Optional<int64_t> barCount;


void PluginProcessor::processBlock (AudioBuffer<float>& buffer, MidiBuffer& midiBufferHost)
{
    if (auto playHead = getPlayHead())
    {
        auto posInfo = playHead->getPosition();
        if (posInfo)
        {
            if (posInfo->getBpm())
            {
                if (!approximatelyEqual(tempoBPM, posInfo->getBpm()))
                    DBG(String::formatted("       Tempo %f", *posInfo->getBpm()));
                
                tempoBPM = posInfo->getBpm();
             }
            
            if (posInfo->getPpqPosition())
            {
                if (!approximatelyEqual(ppqPosition, posInfo->getPpqPosition()))
                    DBG(String::formatted("       ppqPosition %f", *posInfo->getPpqPosition()));
                
                ppqPosition = posInfo->getPpqPosition();
            }
            
            if (posInfo->getBarCount())
            {
                if (barCount != posInfo->getBarCount())
                    DBG(String::formatted("       ppqPosition %d", *posInfo->getBarCount()));
                
                barCount = posInfo->getBarCount();
            }
        }
    }

For example, in Reaper, posInfo->getBarCount() does not return a value, so this seems to work to ignore it…

I’m just not sure how to use this PositionInfo class - it seems that various bits of it are not available on various hosts, but not consistently…

You will just have to deal with that. In some hosts you might not get any useful info from the play head. (That should be rare, though, and would probably only happen in special hosts like audio editors or modular environments.)

Right. OK. I was more interested in if I was using this Optional value type correctly, I’ve not encountered it before, or if there is some better way.

Depending on how you want your code organized, you might find it useful to use the orFallback method of the optionals to get either the optional value or a fallback value, instead of doing the if checks.

1 Like

I see - Thank you!