Implementing an Audio Mixer, Part 2

Implementing an Audio Mixer, Part 2

Recap

In Part 1, we coated PCM audio and superimposing waveforms, and developed an algorithm to mix an arbitrary variety of audio streams into one.

Now we have to use these concepts to complete a full implementation utilizing Qt Multimedia.

Using Qt Multimedia for Audio Device Access

So what do we want? Well, we need to use a single QAudioOutput, which we move an audio machine and a supported audio format.

We can get these like this:

const QAudioDeviceInfo &machine = QAudioDeviceInfo::defaultOutputDevice();
const QAudioFormat &format = machine.most well-likedFormat();

Let’s assemble our QAudioOutput object utilizing the machine and format:

static QAudioOutput audioOutput(machine, format);

Now, to make use of it to write down information, we’ve got to name begin on the audio output, passing in a QIODevice *.

Normally we’d use the QIODevice subclass QBuffer for a single audio buffer. But on this case, we would like our personal subclass of QIODevice, so we will mix a number of buffers into one IO machine.

We’ll name our subclass MixerStream. This is the place we are going to do our bufferCombine, and hold our member record of streams mStreams.

We may also want one other stream kind for mStreams. For now let’s simply name it DecoderStream, ahead declare it, and fear about its implementation later.

One factor that’s good to know at this level is DecoderStream objects will get the info buffers we want by decoding audio information from a file. Because of this, we’ll must hold our audio format from above to as a knowledge member mFormat. Then we will move it to decoders once they want it.

Implementing MixerStream

Since we’re subclassing QIODevice, we have to present reimplementations for these two protected digital features:

digital qint64 QIODevice::learnData(char *information, qint64 maxSize);
digital qint64 QIODevice::writeData(const char *information, qint64 maxSize);

We additionally need to present a method to open new streams that we’ll add to mStreams, given a filename. We’ll name this perform openStream. We may also enable looping a stream a number of occasions, so let’s add a parameter for that and provides it a default worth of 1.

Additionally, we’ll want a user-defined destructor to delete any pointers within the record that may stay if the MixerStream is abruptly destructed.

// mixerstream.h
#pragma as soon as
#embody <QAudioFormat>
#embody <QAudioOutput>
#embody <QIODevice>
class DecodeStream;
class MixerStream : public QIODevice
{
Q_OBJECT
public:
specific MixerStream(const QAudioFormat &format);
~MixerStream();
void openStream(const QString &fileName, int loops = 1);
protected:
qint64 learnData(char *information, qint64 maxSize) override;
qint64 writeData(const char *information, qint64 maxSize) override;
personal:
QAudioFormat mFormat;
QList<DecodeStream *> mStreams;
};

Notice that combineSamples isn’t within the header. It’s a fairly fundamental perform that doesn’t require any members, so we will simply implement it as a free perform.

Let’s put it in a header mixer.h and wrap it in a namespace:

// mixer.h
#pragma as soon as
#embody <QtWorld>
#embody <limits>
namespace Mixer
{
inline qint16 combineSamples(qint32 samp1, qint32 samp2)
{
const auto sum = samp1 + samp2;
if (std::numeric_limits<qint16>::max() < sum)
return std::numeric_limits<qint16>::max();
if (std::numeric_limits<qint16>::min() > sum)
return std::numeric_limits<qint16>::min();
return sum;
}
} // namespace Mixer

There are some very basic items we will get out of the best way shortly within the MixerStream cpp file. Recall that we should implement these member features:

specific MixerStream(const QAudioFormat &format);
~MixerStream();
void openStream(const QString &fileName, int loops = 1);
qint64 learnData(char *information, qint64 maxSize) override;
qint64 writeData(const char *information, qint64 maxSize) override;

The constructor may be very easy:

MixerStream::MixerStream(const QAudioFormat &format)
: mFormat(format)
{
setOpenMode(QIODevice::LearnOnly);
}

Here we use setOpenMode to mechanically open our machine in read-only mode, so we don’t should name open() instantly from outdoors the category.

Also, because it’s going to be read-only, our reimplementation of QIODevice::writeData will do nothing:

qint64 MixerStream::writeData([[maybe_unused]] const char *information,
[[maybe_unused]] qint64 maxSize)
{
Q_ASSERT_X(false, "writeData", "not applied");
return 0;
}

The customized destructor we want can also be fairly easy:

MixerStream::~MixerStream()
{
whereas (!mStreams.empty())
delete mStreams.takeLast();
}

learnData can be nearly precisely the identical because the implementation we did earlier, however returning qint64. The return worth is supposed to be the quantity of information written, which in our case is simply the maxSize argument given to it, as we write fixed-size buffers.

Additionally, we must always name qAsConst (or std::as_const) on mStreams within the range-for to keep away from detaching the Qt container. For extra on qAsConst and range-based for loops, see Jesper Pederson’s weblog publish on the subject.

qint64 MixerStream::learnData(char *information, qint64 maxSize)
{
memset(information, 0, maxSize);
constexpr qint16 bitDepth = sizeof(qint16);
const qint16 numSamples = maxSize / bitDepth;
for (auto *stream : qAsConst(mStreams))
{
auto *cursor = reinterpret_cast<qint16 *>(information);
qint16 pattern;
for (int i = 0; i < numSamples; ++i, ++cursor)
if (stream->learn(reinterpret_cast<char *>(&pattern), bitDepth))
*cursor = Mixer::combineSamples(pattern, *cursor);
}
return maxSize;
}

That solely leaves us with openStream. This one would require us to debate DecodeStream and its interface.

The perform ought to assemble a brand new DecodeStream on the heap, which is able to want a file identify and format. DecodeStream, as implied by its identify, must decode audio information to PCM information. We’ll use a QAudioDecoder inside DecodeStream to perform this, and for that, we have to move mFormat to the constructor. We additionally must move loops to the constructor, as every stream can have a distinct variety of loops.

Now our constructor name will appear to be this:

DecodeStream(fileName, mFormat, loops);

We can then use operator<< so as to add it to mStreams.

Finally, we have to take away it from the record when it’s achieved. We’ll give it a Qt sign, completed, and join it to a lambda expression that can take away the stream from the record and delete the pointer.

Our accomplished openStream perform now seems to be like this:

void MixerStream::openStream(const QString &fileName, int loops)
{
auto *decodeStream = new DecodeStream(fileName, mFormat, loops);
mStreams << decodeStream;
join(decodeStream, &DecodeStream::completed, this, [this, decodeStream]() {
mStreams.removeAll(decodeStream);
decodeStream->deleteLater();
});
}

Recall from earlier that we name learn on a stream, which takes a char * to which the learn information can be copied and a qint64 representing the scale of the info.

This is a QIODevice perform, which is able to internally name learnData. Thus, DecoderStream additionally must be a QIODevice.

Getting PCM Data for DecodeStream

In DecodeStream, we want learnData to spit out PCM information, so we have to decode our audio file to get its contents in PCM format. In Qt Multimedia, we use a QAudioDecoder for this. We move it an audio format to decode to, and a supply machine, on this case a QFile file deal with for our audio file.

When a QAudioDecoder‘s begin technique known as, it’s going to start decoding the supply file in a non-blocking method, emitting a sign bufferReady when a full buffer of decoded PCM information is offered.

On that sign, we will name the decoder’s learn technique, which provides us a QAudioBuffer. To retailer in a knowledge member in DecodeStream, we use a QByteArray, which we will work together with utilizing QBuffers to get a QIODevice interface for studying and writing. This is the best method to work with buffers of bytes to learn or write in Qt.

We’ll make two QBuffers: one for writing information to the QByteArray (we’ll name it mInputBuffer), and one for studying from the QByteArray (we’ll name it mOutputBuffer). The motive for utilizing two buffers moderately than one learn/write buffer is so the learn and write positions may be unbiased. Otherwise, we are going to encounter extra stuttering.

So once we get the bufferReady sign, we’ll need to do one thing like this:

const QAudioBuffer buffer = mDecoder.learn();
mInputBuf.write(buffer.information<char>(), buffer.byteCount());

We’ll additionally must have some type of state enum. The motive for that is that once we are completed with the stream and emit completed(), we take away and delete the stream from a related lambda expression, however learn may nonetheless be referred to as earlier than that has accomplished. Thus, we need to solely learn from the buffer when the state is Playing.

Let’s replace mixer.h to place the enum in namespace Mixer:

#pragma as soon as
#embody <QtWorld>
#embody <limits>
namespace Mixer
{
enum State
{
Playing,
Stopped
};
inline qint16 combineSamples(qint32 samp1, qint32 samp2)
{
const auto sum = samp1 + samp2;
if (std::numeric_limits<qint16>::max() < sum)
return std::numeric_limits<qint16>::max();
if (std::numeric_limits<qint16>::min() > sum)
return std::numeric_limits<qint16>::min();
return sum;
}
} // namespace Mixer

Implementing DecodeStream

Now that we perceive all the info members we have to use, let’s see what our header for DecodeStream seems to be like:

// decodestream.h
#pragma as soon as
#embody "mixer.h"
#embody <QAudioDecoder>
#embody <QBuffer>
#embody <QFile>
class DecodeStream : public QIODevice
{
Q_OBJECT
public:
specific DecodeStream(const QString &fileName, const QAudioFormat &format, int loops);
protected:
qint64 learnData(char *information, qint64 maxSize) override;
qint64 writeData(const char *information, qint64 maxSize) override;
indicators:
void completed();
personal:
QFile mSourceFile;
QByteArray mData;
QBuffer mInputBuf;
QBuffer mOutputBuf;
QAudioDecoder mDecoder;
QAudioFormat mFormat;
Mixer::State mState;
int mLoopsLeft;
};

In the constructor, we’ll initialize our personal members, open the DecodeStream in read-only (like we did earlier), be certain we open the QFile and QBuffers efficiently, and at last arrange our QAudioDecoder.

DecodeStream::DecodeStream(const QString &fileName, const QAudioFormat &format, int loops)
: mSourceFile(fileName)
, mInputBuf(&mData)
, mOutputBuf(&mData)
, mFormat(format)
, mState(Mixer::Playing)
, mLoopsLeft(loops)
{
setOpenMode(QIODevice::LearnOnly);
const bool legitimate = mSourceFile.open(QIODevice::LearnOnly) &&
mOutputBuf.open(QIODevice::LearnOnly) &&
mInputBuf.open(QIODevice::WriteOnly);
Q_ASSERT(legitimate);
mDecoder.setAudioFormat(mFormat);
mDecoder.setSourceDevice(&mSourceFile);
mDecoder.begin();
join(&mDecoder, &QAudioDecoder::bufferReady, this, [this]() {
const QAudioBuffer buffer = mDecoder.learn();
mInputBuf.write(buffer.information<char>(), buffer.byteCount());
});
}

Once once more, our QIODevice subclass is read-only, so our writeData technique seems to be like this:

qint64 DecodeStream::writeData([[maybe_unused]] const char *information,
[[maybe_unused]] qint64 maxSize)
{
Q_ASSERT_X(false, "writeData", "not applied");
return 0;
}

Which leaves us with the final a part of the implementation, DecodeStream‘s learnData perform.

We zero out the char * with memset to keep away from any noise if there are areas that aren’t overwritten. Then we merely learn from the QByteArray into the char * if mState is Mixer::Playing.

We verify to see if we completed studying the file with QBuffer::atEnd(), and if we’re, we decrement the loops remaining. If it’s zero now, that was the final (or solely) loop, so we set mState to stopped, and emit completed(). Either approach we search again to place 0. Now if there are loops left, it begins studying from the start once more.

qint64 DecodeStream::learnData(char *information, qint64 maxSize)
{
memset(information, 0, maxSize);
if (mState == Mixer::Playing)
{
mOutputBuf.learn(information, maxSize);
if (mOutputBuf.dimension() && mOutputBuf.atEnd())
{
if (--mLoopsLeft == 0)
{
mState = Mixer::Stopped;
emit completed();
}
mOutputBuf.search(0);
}
}
return maxSize;
}

Now that we’ve applied DecodeStream, we will truly use MixerStream to play two audio information on the similar time!

Using MixerStream

Here’s an instance snippet that exhibits how MixerStream can be utilized to route two simultaneous audio streams into one system mixer channel:

const auto &machine = QAudioDeviceInfo::defaultOutputDevice();
const auto &format = machine.most well-likedFormat();
auto mixerStream = std::make_unique<MixerStream>(format);
auto *audioOutput = new QAudioOutput(machine, format);
audioOutput->setVolume(0.5);
audioOutput->begin(mixerStream.get());
mixerStream->openStream(QStringLiteral("/path/to/some/sound.wav"));
mixerStream->openStream(QStringLiteral("/path/to/one thing/else.mp3"), 3);

Final Remarks

The code on this sequence of posts is essentially a reimplementation of Lova Widmark’s mission QtMixer. Huge because of her for an incredible and light-weight implementation. Check the mission out if you wish to use one thing like this for a GPL-compliant mission (and don’t thoughts that it makes use of qmake).

About KDAB

If you want this text and need to learn comparable materials, take into account subscribing by way of our RSS feed.

Subscribe to KDAB TV for comparable informative quick video content material.

KDAB supplies market main software program consulting and improvement providers and coaching in Qt, C++ and 3D/OpenGL. Contact us.

The publish Implementing an Audio Mixer, Part 2 appeared first on KDAB.

HI-FI News

by way of Planet KDE | English https://planet.kde.org/

September 19, 2024 at 10:39AM