1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40//
41// W A R N I N G
42// -------------
43//
44// This file is not part of the Qt API. It exists purely as an
45// implementation detail. This header file may change from version to
46// version without notice, or even be removed.
47//
48// INTERNAL USE ONLY: Do NOT use for any other purpose.
49//
50
51#include "qsoundeffect_qaudio_p.h"
52
53#include <QtCore/qcoreapplication.h>
54#include <QtCore/qiodevice.h>
55
56//#include <QDebug>
57//#define QT_QAUDIO_DEBUG 1
58
59QT_BEGIN_NAMESPACE
60
61Q_GLOBAL_STATIC(QSampleCache, sampleCache)
62
63QSoundEffectPrivate::QSoundEffectPrivate(QObject *parent):
64 QObject(parent),
65 d(new PrivateSoundSource(this))
66{
67}
68
69QSoundEffectPrivate::QSoundEffectPrivate(const QAudioDeviceInfo &audioDevice, QObject *parent)
70 : QObject(parent)
71 , d(new PrivateSoundSource(this, audioDevice))
72{
73}
74
75QSoundEffectPrivate::~QSoundEffectPrivate()
76{
77}
78
79void QSoundEffectPrivate::release()
80{
81 stop();
82 if (d->m_audioOutput) {
83 d->m_audioOutput->stop();
84 d->m_audioOutput->deleteLater();
85 d->m_sample->release();
86 }
87 delete d;
88 this->deleteLater();
89}
90
91QStringList QSoundEffectPrivate::supportedMimeTypes()
92{
93 // Only return supported mime types if we have a audio device available
94 const QList<QAudioDeviceInfo> devices = QAudioDeviceInfo::availableDevices(mode: QAudio::AudioOutput);
95 if (devices.size() <= 0)
96 return QStringList();
97
98 return QStringList() << QLatin1String("audio/x-wav")
99 << QLatin1String("audio/wav")
100 << QLatin1String("audio/wave")
101 << QLatin1String("audio/x-pn-wav");
102}
103
104QUrl QSoundEffectPrivate::source() const
105{
106 return d->m_url;
107}
108
109void QSoundEffectPrivate::setSource(const QUrl &url)
110{
111#ifdef QT_QAUDIO_DEBUG
112 qDebug() << this << "setSource current=" << d->m_url << ", to=" << url;
113#endif
114 Q_ASSERT(d->m_url != url);
115
116 stop();
117
118 d->m_url = url;
119
120 d->m_sampleReady = false;
121
122 if (url.isEmpty()) {
123 setStatus(QSoundEffect::Null);
124 return;
125 }
126
127 if (!url.isValid()) {
128 setStatus(QSoundEffect::Error);
129 return;
130 }
131
132 if (d->m_sample) {
133 if (!d->m_sampleReady) {
134 disconnect(sender: d->m_sample, signal: &QSample::error, receiver: d, slot: &PrivateSoundSource::decoderError);
135 disconnect(sender: d->m_sample, signal: &QSample::ready, receiver: d, slot: &PrivateSoundSource::sampleReady);
136 }
137 d->m_sample->release();
138 d->m_sample = nullptr;
139 }
140
141 if (d->m_audioOutput) {
142 disconnect(sender: d->m_audioOutput, signal: &QAudioOutput::stateChanged, receiver: d, slot: &PrivateSoundSource::stateChanged);
143 d->m_audioOutput->stop();
144 d->m_audioOutput->deleteLater();
145 d->m_audioOutput = nullptr;
146 }
147
148 setStatus(QSoundEffect::Loading);
149 d->m_sample = sampleCache()->requestSample(url);
150 connect(sender: d->m_sample, signal: &QSample::error, receiver: d, slot: &PrivateSoundSource::decoderError);
151 connect(sender: d->m_sample, signal: &QSample::ready, receiver: d, slot: &PrivateSoundSource::sampleReady);
152
153 switch (d->m_sample->state()) {
154 case QSample::Ready:
155 d->sampleReady();
156 break;
157 case QSample::Error:
158 d->decoderError();
159 break;
160 default:
161 break;
162 }
163}
164
165int QSoundEffectPrivate::loopCount() const
166{
167 return d->m_loopCount;
168}
169
170int QSoundEffectPrivate::loopsRemaining() const
171{
172 return d->m_runningCount;
173}
174
175void QSoundEffectPrivate::setLoopCount(int loopCount)
176{
177#ifdef QT_QAUDIO_DEBUG
178 qDebug() << "setLoopCount " << loopCount;
179#endif
180 if (loopCount == 0)
181 loopCount = 1;
182 d->m_loopCount = loopCount;
183 if (d->m_playing)
184 setLoopsRemaining(loopCount);
185}
186
187qreal QSoundEffectPrivate::volume() const
188{
189 if (d->m_audioOutput && !d->m_muted)
190 return d->m_audioOutput->volume();
191
192 return d->m_volume;
193}
194
195void QSoundEffectPrivate::setVolume(qreal volume)
196{
197 d->m_volume = volume;
198
199 if (d->m_audioOutput && !d->m_muted)
200 d->m_audioOutput->setVolume(volume);
201
202 emit volumeChanged();
203}
204
205bool QSoundEffectPrivate::isMuted() const
206{
207 return d->m_muted;
208}
209
210void QSoundEffectPrivate::setMuted(bool muted)
211{
212 if (muted && d->m_audioOutput)
213 d->m_audioOutput->setVolume(0);
214 else if (!muted && d->m_audioOutput && d->m_muted)
215 d->m_audioOutput->setVolume(d->m_volume);
216
217 d->m_muted = muted;
218 emit mutedChanged();
219}
220
221bool QSoundEffectPrivate::isLoaded() const
222{
223 return d->m_status == QSoundEffect::Ready;
224}
225
226
227bool QSoundEffectPrivate::isPlaying() const
228{
229 return d->m_playing;
230}
231
232QSoundEffect::Status QSoundEffectPrivate::status() const
233{
234 return d->m_status;
235}
236
237void QSoundEffectPrivate::play()
238{
239 d->m_offset = 0;
240 setLoopsRemaining(d->m_loopCount);
241#ifdef QT_QAUDIO_DEBUG
242 qDebug() << this << "play";
243#endif
244 if (d->m_status == QSoundEffect::Null || d->m_status == QSoundEffect::Error) {
245 setStatus(QSoundEffect::Null);
246 return;
247 }
248 setPlaying(true);
249 if (d->m_audioOutput && d->m_audioOutput->state() == QAudio::StoppedState && d->m_sampleReady)
250 d->m_audioOutput->start(device: d);
251}
252
253void QSoundEffectPrivate::stop()
254{
255 if (!d->m_playing)
256 return;
257#ifdef QT_QAUDIO_DEBUG
258 qDebug() << "stop()";
259#endif
260 d->m_offset = 0;
261
262 setPlaying(false);
263
264 if (d->m_audioOutput)
265 d->m_audioOutput->stop();
266}
267
268void QSoundEffectPrivate::setStatus(QSoundEffect::Status status)
269{
270#ifdef QT_QAUDIO_DEBUG
271 qDebug() << this << "setStatus" << status;
272#endif
273 if (d->m_status == status)
274 return;
275 bool oldLoaded = isLoaded();
276 d->m_status = status;
277 emit statusChanged();
278 if (oldLoaded != isLoaded())
279 emit loadedChanged();
280}
281
282void QSoundEffectPrivate::setPlaying(bool playing)
283{
284#ifdef QT_QAUDIO_DEBUG
285 qDebug() << this << "setPlaying(" << playing << ")";
286#endif
287 if (d->m_playing == playing)
288 return;
289 d->m_playing = playing;
290 emit playingChanged();
291}
292
293void QSoundEffectPrivate::setLoopsRemaining(int loopsRemaining)
294{
295 if (d->m_runningCount == loopsRemaining)
296 return;
297#ifdef QT_QAUDIO_DEBUG
298 qDebug() << this << "setLoopsRemaining " << loopsRemaining;
299#endif
300 d->m_runningCount = loopsRemaining;
301 emit loopsRemainingChanged();
302}
303
304/* Categories are ignored */
305QString QSoundEffectPrivate::category() const
306{
307 return d->m_category;
308}
309
310void QSoundEffectPrivate::setCategory(const QString &category)
311{
312 if (d->m_category != category && !d->m_playing) {
313 d->m_category = category;
314 emit categoryChanged();
315 }
316}
317
318PrivateSoundSource::PrivateSoundSource(QSoundEffectPrivate *s, const QAudioDeviceInfo &audioDevice)
319 : QIODevice(s)
320 , m_audioDevice(audioDevice)
321{
322 soundeffect = s;
323 m_category = QLatin1String("game");
324 open(mode: QIODevice::ReadOnly);
325}
326
327void PrivateSoundSource::sampleReady()
328{
329 if (m_status == QSoundEffect::Error)
330 return;
331
332#ifdef QT_QAUDIO_DEBUG
333 qDebug() << this << "sampleReady "<<m_playing;
334#endif
335 disconnect(sender: m_sample, signal: &QSample::error, receiver: this, slot: &PrivateSoundSource::decoderError);
336 disconnect(sender: m_sample, signal: &QSample::ready, receiver: this, slot: &PrivateSoundSource::sampleReady);
337 if (!m_audioOutput) {
338 if (m_audioDevice.isNull())
339 m_audioOutput = new QAudioOutput(m_sample->format());
340 else
341 m_audioOutput = new QAudioOutput(m_audioDevice, m_sample->format());
342 connect(sender: m_audioOutput, signal: &QAudioOutput::stateChanged, receiver: this, slot: &PrivateSoundSource::stateChanged);
343 if (!m_muted)
344 m_audioOutput->setVolume(m_volume);
345 else
346 m_audioOutput->setVolume(0);
347 }
348 m_sampleReady = true;
349 soundeffect->setStatus(QSoundEffect::Ready);
350
351 if (m_playing && m_audioOutput->state() == QAudio::StoppedState)
352 m_audioOutput->start(device: this);
353}
354
355void PrivateSoundSource::decoderError()
356{
357 qWarning(msg: "QSoundEffect(qaudio): Error decoding source %ls", qUtf16Printable(m_url.toString()));
358 disconnect(sender: m_sample, signal: &QSample::ready, receiver: this, slot: &PrivateSoundSource::sampleReady);
359 disconnect(sender: m_sample, signal: &QSample::error, receiver: this, slot: &PrivateSoundSource::decoderError);
360 m_playing = false;
361 soundeffect->setStatus(QSoundEffect::Error);
362}
363
364void PrivateSoundSource::stateChanged(QAudio::State state)
365{
366#ifdef QT_QAUDIO_DEBUG
367 qDebug() << this << "stateChanged " << state;
368#endif
369 if ((state == QAudio::IdleState && m_runningCount == 0)
370 || (state == QAudio::StoppedState && m_audioOutput->error() != QAudio::NoError))
371 emit soundeffect->stop();
372}
373
374qint64 PrivateSoundSource::readData(char *data, qint64 len)
375{
376 if ((m_runningCount > 0 || m_runningCount == QSoundEffect::Infinite) && m_playing) {
377
378 if (m_sample->state() != QSample::Ready)
379 return 0;
380
381 qint64 bytesWritten = 0;
382
383 const int periodSize = m_audioOutput->periodSize();
384 const int sampleSize = m_sample->data().size();
385 const char* sampleData = m_sample->data().constData();
386
387 // Some systems can have large buffers we only need a max of three
388 int periodsFree = qMin(a: 3, b: (int)(m_audioOutput->bytesFree()/periodSize));
389 int dataOffset = 0;
390
391#ifdef QT_QAUDIO_DEBUG
392 qDebug() << "bytesFree=" << m_audioOutput->bytesFree() << ", can fit " << periodsFree << " periodSize() chunks";
393#endif
394
395 while ((periodsFree > 0) && (bytesWritten + periodSize <= len)) {
396
397 if (sampleSize - m_offset >= periodSize) {
398 // We can fit a whole period of data
399 memcpy(dest: data + dataOffset, src: sampleData + m_offset, n: periodSize);
400 m_offset += periodSize;
401 dataOffset += periodSize;
402 bytesWritten += periodSize;
403#ifdef QT_QAUDIO_DEBUG
404 qDebug() << "WHOLE PERIOD: bytesWritten=" << bytesWritten << ", offset=" << m_offset
405 << ", filesize=" << sampleSize;
406#endif
407 } else {
408 // We are at end of sound, first write what is left of current sound
409 memcpy(dest: data + dataOffset, src: sampleData + m_offset, n: sampleSize - m_offset);
410 bytesWritten += sampleSize - m_offset;
411 int wrapLen = periodSize - (sampleSize - m_offset);
412 if (wrapLen > sampleSize)
413 wrapLen = sampleSize;
414#ifdef QT_QAUDIO_DEBUG
415 qDebug() << "END OF SOUND: bytesWritten=" << bytesWritten << ", offset=" << m_offset
416 << ", part1=" << (sampleSize-m_offset);
417#endif
418 dataOffset += (sampleSize - m_offset);
419 m_offset = 0;
420
421 if (m_runningCount > 0 && m_runningCount != QSoundEffect::Infinite)
422 soundeffect->setLoopsRemaining(m_runningCount-1);
423
424 if (m_runningCount > 0 || m_runningCount == QSoundEffect::Infinite) {
425 // There are still more loops of this sound to play, append the start of sound to make up full period
426 memcpy(dest: data + dataOffset, src: sampleData + m_offset, n: wrapLen);
427 m_offset += wrapLen;
428 dataOffset += wrapLen;
429 bytesWritten += wrapLen;
430#ifdef QT_QAUDIO_DEBUG
431 qDebug() << "APPEND START FOR FULL PERIOD: bytesWritten=" << bytesWritten << ", offset=" << m_offset
432 << ", part2=" << wrapLen;
433 qDebug() << "part1 + part2 should be a period " << periodSize;
434#endif
435 }
436 }
437 if (m_runningCount == 0)
438 break;
439
440 periodsFree--;
441 }
442 return bytesWritten;
443 }
444
445 return 0;
446}
447
448qint64 PrivateSoundSource::writeData(const char *data, qint64 len)
449{
450 Q_UNUSED(data)
451 Q_UNUSED(len)
452 return 0;
453}
454
455QT_END_NAMESPACE
456
457#include "moc_qsoundeffect_qaudio_p.cpp"
458

source code of qtmultimedia/src/multimedia/audio/qsoundeffect_qaudio_p.cpp