summaryrefslogtreecommitdiffstats
path: root/src/plugins/windowsaudio/qwindowsaudiooutput.cpp
blob: f39e1694bfd4b8ff67cfb9117e786d09d6309669 (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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of other Qt classes.  This header file may change from version to
// version without notice, or even be removed.
//
// INTERNAL USE ONLY: Do NOT use for any other purpose.
//

#include "qwindowsaudiooutput.h"
#include "qwindowsaudiodeviceinfo.h"
#include "qwindowsaudioutils.h"
#include <QtEndian>
#include <QtCore/QDataStream>
#include <private/qaudiohelpers_p.h>

//#define DEBUG_AUDIO 1

QT_BEGIN_NAMESPACE

QWindowsAudioOutput::QWindowsAudioOutput(const QByteArray &device)
{
    bytesAvailable = 0;
    buffer_size = 0;
    period_size = 0;
    m_device = device;
    totalTimeValue = 0;
    intervalTime = 1000;
    audioBuffer = 0;
    errorState = QAudio::NoError;
    deviceState = QAudio::StoppedState;
    audioSource = 0;
    pullMode = true;
    finished = false;
    volumeCache = qreal(1.0);
    blocks_count = 5;
}

QWindowsAudioOutput::~QWindowsAudioOutput()
{
    mutex.lock();
    finished = true;
    mutex.unlock();

    close();
}

void CALLBACK QWindowsAudioOutput::waveOutProc( HWAVEOUT hWaveOut, UINT uMsg,
        DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2 )
{
    Q_UNUSED(dwParam1)
    Q_UNUSED(dwParam2)
    Q_UNUSED(hWaveOut)

    QWindowsAudioOutput* qAudio;
    qAudio = (QWindowsAudioOutput*)(dwInstance);
    if(!qAudio)
        return;

    QMutexLocker locker(&qAudio->mutex);

    switch(uMsg) {
        case WOM_OPEN:
            qAudio->feedback();
            break;
        case WOM_CLOSE:
            return;
        case WOM_DONE:
            if(qAudio->finished || qAudio->buffer_size == 0 || qAudio->period_size == 0) {
                return;
            }
            qAudio->waveFreeBlockCount++;
            if (qAudio->waveFreeBlockCount >= qAudio->blocks_count)
                qAudio->waveFreeBlockCount = qAudio->blocks_count;

            qAudio->feedback();
            break;
        default:
            return;
    }
}

WAVEHDR* QWindowsAudioOutput::allocateBlocks(int size, int count)
{
    int i;
    unsigned char* buffer;
    WAVEHDR* blocks;
    DWORD totalBufferSize = (size + sizeof(WAVEHDR))*count;

    if((buffer=(unsigned char*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
                    totalBufferSize)) == 0) {
        qWarning("QAudioOutput: Memory allocation error");
        return 0;
    }
    blocks = (WAVEHDR*)buffer;
    buffer += sizeof(WAVEHDR)*count;
    for(i = 0; i < count; i++) {
        blocks[i].dwBufferLength = size;
        blocks[i].lpData = (LPSTR)buffer;
        buffer += size;
    }
    return blocks;
}

void QWindowsAudioOutput::freeBlocks(WAVEHDR* blockArray)
{
    WAVEHDR* blocks = blockArray;
    for (int i = 0; i < blocks_count; ++i) {
        waveOutUnprepareHeader(hWaveOut,blocks, sizeof(WAVEHDR));
        blocks++;
    }
    HeapFree(GetProcessHeap(), 0, blockArray);
}

QAudioFormat QWindowsAudioOutput::format() const
{
    return settings;
}

void QWindowsAudioOutput::setFormat(const QAudioFormat& fmt)
{
    if (deviceState == QAudio::StoppedState)
        settings = fmt;
}

void QWindowsAudioOutput::start(QIODevice* device)
{
    if(deviceState != QAudio::StoppedState)
        close();

    if(!pullMode && audioSource)
        delete audioSource;

    pullMode = true;
    audioSource = device;

    deviceState = QAudio::ActiveState;

    if(!open())
        return;

    emit stateChanged(deviceState);
}

QIODevice* QWindowsAudioOutput::start()
{
    if(deviceState != QAudio::StoppedState)
        close();

    if(!pullMode && audioSource)
        delete audioSource;

    pullMode = false;
    audioSource = new OutputPrivate(this);
    audioSource->open(QIODevice::WriteOnly|QIODevice::Unbuffered);

    deviceState = QAudio::IdleState;

    if(!open())
        return 0;

    emit stateChanged(deviceState);

    return audioSource;
}

void QWindowsAudioOutput::stop()
{
    if(deviceState == QAudio::StoppedState)
        return;
    close();
    if(!pullMode && audioSource) {
        delete audioSource;
        audioSource = 0;
    }
    emit stateChanged(deviceState);
}

bool QWindowsAudioOutput::open()
{
#ifdef DEBUG_AUDIO
    QTime now(QTime::currentTime());
    qDebug()<<now.second()<<"s "<<now.msec()<<"ms :open()";
#endif

    period_size = 0;

    if (!qt_convertFormat(settings, &wfx)) {
        qWarning("QAudioOutput: open error, invalid format.");
    } else if (buffer_size == 0) {
        // Default buffer size, 200ms, default period size is 40ms
        buffer_size
                = (settings.sampleRate()
                * settings.channelCount()
                * settings.sampleSize()
                + 39) / 40;
        period_size = buffer_size / 5;
    } else {
        period_size = buffer_size / 5;
    }

    // Make even size of wave block to prevent crackling
    // due to waveOutWrite() does not like odd buffer length
    period_size &= ~1;

    if (period_size == 0) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit stateChanged(deviceState);
        return false;
    }

    const int periods = buffer_size / period_size;
    bool ok = false;
    static int wave_buffers = qEnvironmentVariableIntValue("QT_WAVE_BUFFERS", &ok);
    if (wave_buffers < periods) {
        if (ok)
            qWarning("Number of WAVE buffers (QT_WAVE_BUFFERS=%d) cannot be less than %d.", wave_buffers, periods);
        wave_buffers = periods;
    }

    blocks_count = wave_buffers;
    waveBlocks = allocateBlocks(period_size, blocks_count);

    mutex.lock();
    waveFreeBlockCount = blocks_count;
    mutex.unlock();

    waveCurrentBlock = 0;

    if(audioBuffer == 0)
        audioBuffer = new char[blocks_count * period_size];

    timeStamp.restart();
    elapsedTimeOffset = 0;

    QDataStream ds(&m_device, QIODevice::ReadOnly);
    quint32 deviceId;
    ds >> deviceId;

    if (waveOutOpen(&hWaveOut, UINT_PTR(deviceId), &wfx.Format,
                    (DWORD_PTR)&waveOutProc,
                    (DWORD_PTR) this,
                    CALLBACK_FUNCTION) != MMSYSERR_NOERROR) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit stateChanged(deviceState);
        qWarning("QAudioOutput: open error");
        return false;
    }

    totalTimeValue = 0;
    timeStampOpened.restart();
    elapsedTimeOffset = 0;

    errorState = QAudio::NoError;
    if(pullMode) {
        deviceState = QAudio::ActiveState;
        QTimer::singleShot(10, this, SLOT(feedback()));
    } else
        deviceState = QAudio::IdleState;

    return true;
}

void QWindowsAudioOutput::pauseAndSleep()
{
    waveOutPause(hWaveOut);
    int bitrate = settings.sampleRate() * settings.channelCount() * settings.sampleSize() / 8;
    // Time of written data.
    int delay = (buffer_size - bytesFree()) * 1000 / bitrate;
    Sleep(delay + 10);
}

void QWindowsAudioOutput::close()
{
    if(deviceState == QAudio::StoppedState)
        return;

    // Pause playback before reset to avoid uneeded crackling at the end.
    pauseAndSleep();
    deviceState = QAudio::StoppedState;
    errorState = QAudio::NoError;
    waveOutReset(hWaveOut);

    freeBlocks(waveBlocks);
    waveOutClose(hWaveOut);
    delete [] audioBuffer;
    audioBuffer = 0;
    buffer_size = 0;
}

int QWindowsAudioOutput::bytesFree() const
{
    int buf;
    buf = waveFreeBlockCount*period_size;

    return buf;
}

int QWindowsAudioOutput::periodSize() const
{
    return period_size;
}

void QWindowsAudioOutput::setBufferSize(int value)
{
    if(deviceState == QAudio::StoppedState)
        buffer_size = value;
}

int QWindowsAudioOutput::bufferSize() const
{
    return buffer_size;
}

void QWindowsAudioOutput::setNotifyInterval(int ms)
{
    intervalTime = qMax(0, ms);
}

int QWindowsAudioOutput::notifyInterval() const
{
    return intervalTime;
}

qint64 QWindowsAudioOutput::processedUSecs() const
{
    if (deviceState == QAudio::StoppedState)
        return 0;
    qint64 result = qint64(1000000) * totalTimeValue /
        (settings.channelCount()*(settings.sampleSize()/8)) /
        settings.sampleRate();

    return result;
}

qint64 QWindowsAudioOutput::write( const char *data, qint64 len )
{
    // Write out some audio data
    if (deviceState != QAudio::ActiveState && deviceState != QAudio::IdleState)
        return 0;

    char* p = (char*)data;
    int l = (int)len;

    QByteArray reverse;
    if (settings.byteOrder() == QAudioFormat::BigEndian) {

        switch (settings.sampleSize()) {
            case 8:
                // No need to convert
                break;

            case 16:
                reverse.resize(l);
                for (qint64 i = 0; i < (l >> 1); i++)
                    *((qint16*)reverse.data() + i) = qFromBigEndian(*((qint16*)data + i));
                p = reverse.data();
                break;

            case 32:
                reverse.resize(l);
                for (qint64 i = 0; i < (l >> 2); i++)
                    *((qint32*)reverse.data() + i) = qFromBigEndian(*((qint32*)data + i));
                p = reverse.data();
                break;
        }
    }

    WAVEHDR* current;
    int remain;
    current = &waveBlocks[waveCurrentBlock];
    while(l > 0) {
        mutex.lock();
        if(waveFreeBlockCount==0) {
            mutex.unlock();
            break;
        }
        mutex.unlock();

        if(current->dwFlags & WHDR_PREPARED)
            waveOutUnprepareHeader(hWaveOut, current, sizeof(WAVEHDR));

        if(l < period_size)
            remain = l;
        else
            remain = period_size;

        if (volumeCache < qreal(1.0))
            QAudioHelperInternal::qMultiplySamples(volumeCache, settings, p, current->lpData, remain);
        else
            memcpy(current->lpData, p, remain);

        l -= remain;
        p += remain;
        current->dwBufferLength = remain;
        waveOutPrepareHeader(hWaveOut, current, sizeof(WAVEHDR));
        waveOutWrite(hWaveOut, current, sizeof(WAVEHDR));

        mutex.lock();
        waveFreeBlockCount--;
#ifdef DEBUG_AUDIO
        qDebug("write out l=%d, waveFreeBlockCount=%d",
                current->dwBufferLength,waveFreeBlockCount);
#endif
        mutex.unlock();

        totalTimeValue += current->dwBufferLength;
        waveCurrentBlock++;
        waveCurrentBlock %= blocks_count;
        current = &waveBlocks[waveCurrentBlock];
        current->dwUser = 0;
        errorState = QAudio::NoError;
        if (deviceState != QAudio::ActiveState) {
            deviceState = QAudio::ActiveState;
            emit stateChanged(deviceState);
        }
    }
    return (len-l);
}

void QWindowsAudioOutput::resume()
{
    if(deviceState == QAudio::SuspendedState) {
        deviceState = pullMode ? QAudio::ActiveState : QAudio::IdleState;
        errorState = QAudio::NoError;
        waveOutRestart(hWaveOut);
        QTimer::singleShot(10, this, SLOT(feedback()));
        emit stateChanged(deviceState);
    }
}

void QWindowsAudioOutput::suspend()
{
    if(deviceState == QAudio::ActiveState || deviceState == QAudio::IdleState) {
        pauseAndSleep();
        deviceState = QAudio::SuspendedState;
        errorState = QAudio::NoError;
        emit stateChanged(deviceState);
    }
}

void QWindowsAudioOutput::feedback()
{
#ifdef DEBUG_AUDIO
    QTime now(QTime::currentTime());
    qDebug()<<now.second()<<"s "<<now.msec()<<"ms :feedback()";
#endif
    bytesAvailable = bytesFree();

    if(!(deviceState==QAudio::StoppedState||deviceState==QAudio::SuspendedState)) {
        if(bytesAvailable >= period_size)
            QMetaObject::invokeMethod(this, "deviceReady", Qt::QueuedConnection);
    }
}

bool QWindowsAudioOutput::deviceReady()
{
    if(deviceState == QAudio::StoppedState || deviceState == QAudio::SuspendedState)
        return false;

    if(pullMode) {
        int chunks = bytesAvailable/period_size;
#ifdef DEBUG_AUDIO
        qDebug()<<"deviceReady() avail="<<bytesAvailable<<" bytes, period size="<<period_size<<" bytes";
        qDebug()<<"deviceReady() no. of chunks that can fit ="<<chunks<<", chunks in bytes ="<<chunks*period_size;
#endif
        bool startup = false;
        if(totalTimeValue == 0)
            startup = true;

        bool full=false;

        mutex.lock();
        if (waveFreeBlockCount==0) full = true;
        mutex.unlock();

        if (full) {
#ifdef DEBUG_AUDIO
            qDebug() << "Skipping data as unable to write";
#endif
            if ((timeStamp.elapsed() + elapsedTimeOffset) > intervalTime) {
                emit notify();
                elapsedTimeOffset = timeStamp.elapsed() + elapsedTimeOffset - intervalTime;
                timeStamp.restart();
            }
            return true;
        }

        if(startup)
            waveOutPause(hWaveOut);
        int input = period_size*chunks;
        int l = audioSource->read(audioBuffer,input);
        if(l > 0) {
            int out= write(audioBuffer,l);
            if(out > 0) {
                if (deviceState != QAudio::ActiveState) {
                    deviceState = QAudio::ActiveState;
                    emit stateChanged(deviceState);
                }
            }
            if ( out < l) {
                // Didn't write all data
                audioSource->seek(audioSource->pos()-(l-out));
            }
            if (startup)
                waveOutRestart(hWaveOut);
        } else if(l == 0) {
            bytesAvailable = bytesFree();

            int check = 0;

            mutex.lock();
            check = waveFreeBlockCount;
            mutex.unlock();

            if (check == blocks_count) {
                if (deviceState != QAudio::IdleState) {
                    errorState = QAudio::UnderrunError;
                    deviceState = QAudio::IdleState;
                    emit stateChanged(deviceState);
                }
            }

        } else if(l < 0) {
            bytesAvailable = bytesFree();
            if (errorState != QAudio::IOError)
                errorState = QAudio::IOError;
        }
    } else {
        int buffered;

        mutex.lock();
        buffered = waveFreeBlockCount;
        mutex.unlock();

        if (buffered >= blocks_count && deviceState == QAudio::ActiveState) {
            if (deviceState != QAudio::IdleState) {
                errorState = QAudio::UnderrunError;
                deviceState = QAudio::IdleState;
                emit stateChanged(deviceState);
            }
        }
    }
    if(deviceState != QAudio::ActiveState && deviceState != QAudio::IdleState)
        return true;

    if(intervalTime && (timeStamp.elapsed() + elapsedTimeOffset) > intervalTime) {
        emit notify();
        elapsedTimeOffset = timeStamp.elapsed() + elapsedTimeOffset - intervalTime;
        timeStamp.restart();
    }

    return true;
}

qint64 QWindowsAudioOutput::elapsedUSecs() const
{
    if (deviceState == QAudio::StoppedState)
        return 0;

    return timeStampOpened.elapsed() * qint64(1000);
}

QAudio::Error QWindowsAudioOutput::error() const
{
    return errorState;
}

QAudio::State QWindowsAudioOutput::state() const
{
    return deviceState;
}

void QWindowsAudioOutput::setVolume(qreal v)
{
    if (qFuzzyCompare(volumeCache, v))
        return;

    volumeCache = qBound(qreal(0), v, qreal(1));
}

qreal QWindowsAudioOutput::volume() const
{
    return volumeCache;
}

void QWindowsAudioOutput::reset()
{
    close();
}

OutputPrivate::OutputPrivate(QWindowsAudioOutput* audio)
{
    audioDevice = qobject_cast<QWindowsAudioOutput*>(audio);
}

OutputPrivate::~OutputPrivate() {}

qint64 OutputPrivate::readData( char* data, qint64 len)
{
    Q_UNUSED(data)
    Q_UNUSED(len)

    return 0;
}

qint64 OutputPrivate::writeData(const char* data, qint64 len)
{
    int retry = 0;
    qint64 written = 0;

    if((audioDevice->deviceState == QAudio::ActiveState)
            ||(audioDevice->deviceState == QAudio::IdleState)) {
        qint64 l = len;
        while(written < l) {
            int chunk = audioDevice->write(data+written,(l-written));
            if(chunk <= 0)
                retry++;
            else
                written+=chunk;

            if(retry > 10)
                return written;
        }
        audioDevice->deviceState = QAudio::ActiveState;
    }
    return written;
}

QT_END_NAMESPACE

#include "moc_qwindowsaudiooutput.cpp"