summaryrefslogtreecommitdiffstats
path: root/src/imports/audioengine/qaudioengine_openal_p.cpp
blob: 3200e21e002b96ee56737d0a7b55d2961ba71428 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:COMM$
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** $QT_END_LICENSE$
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
****************************************************************************/

#include "qaudioengine_openal_p.h"

#include <QtCore/QMutex>
#include <QtCore/QThread>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkAccessManager>

#include "qsamplecache_p.h"

#include "qdebug.h"

#define DEBUG_AUDIOENGINE

QT_USE_NAMESPACE

QSoundBufferPrivateAL::QSoundBufferPrivateAL(QObject *parent)
    : QSoundBuffer(parent)
{
}


StaticSoundBufferAL::StaticSoundBufferAL(QObject *parent, const QUrl &url, QSampleCache *sampleLoader)
    : QSoundBufferPrivateAL(parent),
      m_ref(1),
      m_url(url),
      m_alBuffer(0),
      m_state(Creating),
      m_sample(0),
      m_sampleLoader(sampleLoader)
{
#ifdef DEBUG_AUDIOENGINE
    qDebug() << "creating new StaticSoundBufferOpenAL";
#endif
}

StaticSoundBufferAL::~StaticSoundBufferAL()
{
    if (m_sample)
        m_sample->release();

    if (m_alBuffer != 0) {
        alGetError(); // clear error
        alDeleteBuffers(1, &m_alBuffer);
        QAudioEnginePrivate::checkNoError("delete buffer");
    }
}

QSoundBuffer::State StaticSoundBufferAL::state() const
{
    return m_state;
}

void StaticSoundBufferAL::load()
{
    if (m_state == Loading || m_state == Ready)
        return;

    m_state = Loading;
    emit stateChanged(m_state);

    m_sample = m_sampleLoader->requestSample(m_url);
    connect(m_sample, SIGNAL(error()), this, SLOT(decoderError()));
    connect(m_sample, SIGNAL(ready()), this, SLOT(sampleReady()));
    switch (m_sample->state()) {
    case QSample::Ready:
        sampleReady();
        break;
    case QSample::Error:
        decoderError();
        break;
    default:
        break;
    }
}

void StaticSoundBufferAL::bindToSource(ALuint alSource)
{
    Q_ASSERT(m_alBuffer != 0);
    alSourcei(alSource, AL_BUFFER, m_alBuffer);
}

void StaticSoundBufferAL::unbindFromSource(ALuint alSource)
{
    alSourcei(alSource, AL_BUFFER, 0);
}

void StaticSoundBufferAL::sampleReady()
{
#ifdef DEBUG_AUDIOENGINE
    qDebug() << "StaticSoundBufferOpenAL:sample[" << m_url << "] loaded";
#endif

    disconnect(m_sample, SIGNAL(error()), this, SLOT(decoderError()));
    disconnect(m_sample, SIGNAL(ready()), this, SLOT(sampleReady()));

    if (m_sample->data().size() > 1024 * 1024 * 4) {
        qWarning() << "source [" << m_url << "] size too large!";
        decoderError();
        return;
    }

    if (m_sample->format().channelCount() > 2) {
        qWarning() << "source [" << m_url << "] channel > 2!";
        decoderError();
        return;
    }

    ALenum alFormat = 0;
    if (m_sample->format().sampleSize() == 8) {
        alFormat = m_sample->format().channelCount() == 1 ? AL_FORMAT_MONO8 : AL_FORMAT_STEREO8;
    } else if (m_sample->format().sampleSize() == 16) {
        alFormat = m_sample->format().channelCount() == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
    } else {
        qWarning() << "source [" << m_url << "] invalid sample size:"
                   << m_sample->format().sampleSize() << "(should be 8 or 16)";
        decoderError();
        return;
    }

    alGenBuffers(1, &m_alBuffer);
    if (!QAudioEnginePrivate::checkNoError("create buffer")) {
        decoderError();
        return;
    }
    alBufferData(m_alBuffer, alFormat, m_sample->data().data(),
                 m_sample->data().size(), m_sample->format().sampleRate());
    if (!QAudioEnginePrivate::checkNoError("fill buffer")) {
        decoderError();
        return;
    }

    m_sample->release();
    m_sample = 0;

    m_state = Ready;
    emit stateChanged(m_state);
    emit ready();
}

void StaticSoundBufferAL::decoderError()
{
    qWarning() << "loading [" << m_url << "] failed";

    disconnect(m_sample, SIGNAL(error()), this, SLOT(decoderError()));
    disconnect(m_sample, SIGNAL(ready()), this, SLOT(sampleReady()));

    m_sample->release();
    m_sample = 0;

    m_state = Error;
    emit stateChanged(m_state);
    emit error();
}


/////////////////////////////////////////////////////////////////
QAudioEnginePrivate::QAudioEnginePrivate(QObject *parent)
    : QObject(parent)
{
    m_updateTimer.setInterval(200);
    connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(updateSoundSources()));

    m_sampleLoader = new QSampleCache(this);
    m_sampleLoader->setCapacity(0);
    connect(m_sampleLoader, SIGNAL(isLoadingChanged()), this, SIGNAL(isLoadingChanged()));

#ifdef DEBUG_AUDIOENGINE
    qDebug() << "default openal device = " << alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);

    const ALCchar* devNames = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
    int cc = 0;
    qDebug() << "device list:";
    while (true) {
        qDebug() << "    " << devNames + cc;
        while (devNames[cc] != 0)
            ++cc;
        ++cc;
        if (devNames[cc] == 0)
            break;
    }
#endif

    ALCdevice *device = alcOpenDevice(0);
    if (!device) {
        qWarning() << "Can not create openal device!";
        return;
    }

    ALCcontext* context = alcCreateContext(device, 0);
    if (!context) {
        qWarning() << "Can not create openal context!";
        return;
    }
    alcMakeContextCurrent(context);
    alDistanceModel(AL_NONE);
    alDopplerFactor(0);
}

QAudioEnginePrivate::~QAudioEnginePrivate()
{
#ifdef DEBUG_AUDIOENGINE
    qDebug() << "QAudioEnginePrivate::dtor";
#endif
    const QObjectList children = this->children();
    for (QObject *child : children) {
        QSoundSourcePrivate* s = qobject_cast<QSoundSourcePrivate*>(child);
        if (!s)
            continue;
        s->release();
    }

    for (QSoundBufferPrivateAL *buffer : qAsConst(m_staticBufferPool)) {
        delete buffer;
    }
    m_staticBufferPool.clear();

    delete m_sampleLoader;

    ALCcontext* context = alcGetCurrentContext();
    ALCdevice *device = alcGetContextsDevice(context);
    alcDestroyContext(context);
    alcCloseDevice(device);
#ifdef DEBUG_AUDIOENGINE
    qDebug() << "QAudioEnginePrivate::dtor: all done";
#endif
}

bool QAudioEnginePrivate::isLoading() const
{
    return m_sampleLoader->isLoading();
}

QSoundSource* QAudioEnginePrivate::createSoundSource()
{
#ifdef DEBUG_AUDIOENGINE
    qDebug() << "QAudioEnginePrivate::createSoundSource()";
#endif
    QSoundSourcePrivate *instance = NULL;
    if (m_instancePool.count() == 0) {
        instance = new QSoundSourcePrivate(this);
    } else {
        instance = m_instancePool.front();
        m_instancePool.pop_front();
    }
    connect(instance, SIGNAL(activate(QObject*)), this, SLOT(soundSourceActivate(QObject*)));
    return instance;
}

void QAudioEnginePrivate::releaseSoundSource(QSoundSource *soundInstance)
{
    QSoundSourcePrivate *privInstance = static_cast<QSoundSourcePrivate*>(soundInstance);
#ifdef DEBUG_AUDIOENGINE
    qDebug() << "recycle soundInstance" << privInstance;
#endif
    privInstance->unbindBuffer();
    m_instancePool.push_front(privInstance);
    m_activeInstances.removeOne(privInstance);
}

QSoundBuffer* QAudioEnginePrivate::getStaticSoundBuffer(const QUrl& url)
{
    StaticSoundBufferAL *staticBuffer = NULL;
    QMap<QUrl, QSoundBufferPrivateAL*>::iterator it = m_staticBufferPool.find(url);
    if (it == m_staticBufferPool.end()) {
        staticBuffer = new StaticSoundBufferAL(this, url, m_sampleLoader);
        m_staticBufferPool.insert(url, staticBuffer);
    } else {
        staticBuffer = static_cast<StaticSoundBufferAL*>(*it);
        staticBuffer->addRef();
    }
    return staticBuffer;
}

void QAudioEnginePrivate::releaseSoundBuffer(QSoundBuffer *buffer)
{
#ifdef DEBUG_AUDIOENGINE
    qDebug() << "QAudioEnginePrivate: recycle sound buffer";
#endif
    if (StaticSoundBufferAL *staticBuffer = qobject_cast<StaticSoundBufferAL *>(buffer)) {
        //decrement the reference count, still kept in memory for reuse
        staticBuffer->release();
        //TODO implement some resource recycle strategy
    } else {
        //TODO
        Q_ASSERT(0);
        qWarning() << "Unknown soundbuffer type for recycle" << buffer;
    }
}

bool QAudioEnginePrivate::checkNoError(const char *msg)
{
    ALenum error = alGetError();
    if (error != AL_NO_ERROR) {
        qWarning() << "Failed on" << msg << "[OpenAL error code =" << error << "]";
        return false;
    }
    return true;
}

QVector3D QAudioEnginePrivate::listenerPosition() const
{
    ALfloat x, y, z;
    alGetListener3f(AL_POSITION, &x, &y, &z);
    checkNoError("get listener position");
    return QVector3D(x, y, z);
}

QVector3D QAudioEnginePrivate::listenerVelocity() const
{
    ALfloat x, y, z;
    alGetListener3f(AL_VELOCITY, &x, &y, &z);
    checkNoError("get listener velocity");
    return QVector3D(x, y, z);
}

qreal QAudioEnginePrivate::listenerGain() const
{
    ALfloat gain;
    alGetListenerf(AL_GAIN, &gain);
    checkNoError("get listener gain");
    return gain;
}

void QAudioEnginePrivate::setListenerPosition(const QVector3D& position)
{
    alListener3f(AL_POSITION, position.x(), position.y(), position.z());
    checkNoError("set listener position");
}

void QAudioEnginePrivate::setListenerOrientation(const QVector3D& direction, const QVector3D& up)
{
    ALfloat orientation[6];
    orientation[0] = direction.x();
    orientation[1] = direction.y();
    orientation[2] = direction.z();
    orientation[3] = up.x();
    orientation[4] = up.y();
    orientation[5] = up.z();
    alListenerfv(AL_ORIENTATION, orientation);
    checkNoError("set listener orientation");
}

void QAudioEnginePrivate::setListenerVelocity(const QVector3D& velocity)
{
    alListener3f(AL_VELOCITY, velocity.x(), velocity.y(), velocity.z());
    checkNoError("set listener velocity");
}

void QAudioEnginePrivate::setListenerGain(qreal gain)
{
    alListenerf(AL_GAIN, gain);
    checkNoError("set listener gain");
}

void QAudioEnginePrivate::setDopplerFactor(qreal dopplerFactor)
{
    alDopplerFactor(dopplerFactor);
}

void QAudioEnginePrivate::setSpeedOfSound(qreal speedOfSound)
{
    alSpeedOfSound(speedOfSound);
}

void QAudioEnginePrivate::soundSourceActivate(QObject *soundSource)
{
    QSoundSourcePrivate *ss = qobject_cast<QSoundSourcePrivate*>(soundSource);
    ss->checkState();
    if (ss->isLooping())
        return;
    if (!m_activeInstances.contains(ss))
        m_activeInstances.push_back(ss);
    if (!m_updateTimer.isActive())
        m_updateTimer.start();
}

void QAudioEnginePrivate::updateSoundSources()
{
    for (QList<QSoundSourcePrivate*>::Iterator it = m_activeInstances.begin();
         it != m_activeInstances.end();) {
        QSoundSourcePrivate *instance = *it;
        instance->checkState();
        if (instance->state() == QSoundSource::StoppedState) {
            it = m_activeInstances.erase(it);
        } else {
            ++it;
        }
    }

    if (m_activeInstances.count() == 0) {
        m_updateTimer.stop();
    }
}