Creating QIODevice with infinite data
-
I'm making a simple DAW and my aim is to make a readonly audio buffer, containing a pregenerated sine wave, that can be read infinitely. So, if all the bytes of internal audioBuffer were read, it start reading it from the beginning. My current implementation is as follows:
AudioSynthBuffer.h:
#include <QAudio> #include <QBuffer> const qint32 SAMPLING_FREQUENCY = 44100; class AudioSynthBuffer : public QIODevice{ private: const qint32 bufferSize = SAMPLING_FREQUENCY * 2; char* audioData; public: AudioSynthBuffer(QObject* parent = nullptr); ~AudioSynthBuffer(); virtual qint64 readData(char *data, qint64 maxSize) override; virtual bool open(QIODevice::OpenMode om = ReadOnly) override; qint64 bytesAvailable() const override; };
AudioSynthBuffer.cpp:
#include "AudioSynthBuffer.h" AudioSynthBuffer::AudioSynthBuffer(QObject *parent) : QIODevice(parent) { audioData = new char[bufferSize]; /* initializing audioBuffer somehow... */ } bool AudioSynthBuffer::open(OpenMode om) { if(om != ReadOnly){ setOpenMode(NotOpen); return false; } return QIODevice::open(om); } qint64 AudioSynthBuffer::readData(char *targetData, qint64 maxRead) { qint64 bytesRead = 0; qint64 remainingBytes = maxRead; char* currentDataPtr; while(bytesRead < maxRead){ currentDataPtr = std::copy(audioData, audioData + remainingBytes, targetData); bytesRead = currentDataPtr - targetData; remainingBytes = (maxRead - bytesRead >= bufferSize) ? bufferSize : maxRead - bytesRead; } return bytesRead; } AudioSynthBuffer::~AudioSynthBuffer() { delete[] audioData; } qint64 AudioSynthBuffer::bytesAvailable() const { return ULLONG_MAX; }
It seems like it doesn't work in appropriate way. I'd like to know if you can see some problems with this implementation, and what should I change, just opinion of experienced programmers. Maybe I should not even create subclass of QIODevice and use a different concept?
-
Hi and welcome to devnet,
How are you using it ?
What exact error are you getting ? -
@artemious3 said in Creating QIODevice with infinite data:
I'd like to know if you can see some problems with this implementation,
On a cursory inspection...
Let's say your audioData buffer size is 1024 bytes, for example, and the user requests a read of 2048 bytes (because your bytesAvailable says that is available). This line:currentDataPtr = std::copy(audioData, audioData + remainingBytes, targetData);
will try to copy 2048 bytes out of a 1024 byte buffer.
You should also look at the QIODevice::bytesAvailable() docs regarding what this should return.