Search code examples
c++qtqthread

Is there any memory leak with the QAudioOutput code?


I am playing an audio stream in a QThread like this:

// Setup
QAudioFormat format;
format.setFrequency(44100);
format.setChannels(2);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
format = info.nearestFormat(format);
this->m_AudioOutput = new QAudioOutput(format, this);
DECLARE_ALIGNED(16,uint8_t,audio_buffer)[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2];

// Playback
QIODevice *iodevice = this->m_AudioOutput->start();
for(;;) {
    // Routine that fetches audio data from network
    // data_size is length of the buffer
    fetch_packet(&audio_buffer, data_size);

    qint64 dataRemaining = data_size;
    const char *b2 = (const char *)audio_buffer;
    while (dataRemaining) {
    qint64 bytesWritten = iodevice->write((const char *)b2, dataRemaining);
        dataRemaining -= bytesWritten;
        b2 = b2 + bytesWritten ;
    }

    msleep(10);
}

The audio plays just fine but the app's memory consumption seems to increase over time (around 2MB per minute). I was wondering if I have done something wrong. I suppose QAudioOutput should be responsible for deleting the QIODevice's buffer after it has been read and used for playback?


Solution

  • I don't think so, the docs says:

    Starting to play an audio stream is simply a matter of calling start() with a QIODevice. QAudioOutput will then fetch the data it needs from the io device.

    It it just reading data. The QIODevice should manage the buffer. To be sure, you can check the size of your buffer using QIODevice::size() and see if it is growing.