summaryrefslogtreecommitdiffstats
path: root/src/multimedia/windows/qwindowsaudiosource.cpp
blob: 85fc454add954ad674015acb158988c613613b80 (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

//
//  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 "qwindowsaudiosource_p.h"
#include "qwindowsmultimediautils_p.h"
#include "qcomtaskresource_p.h"

#include <QtCore/QDataStream>
#include <QtCore/qtimer.h>

#include <private/qaudiohelpers_p.h>

#include <qloggingcategory.h>
#include <qdebug.h>
#include <audioclient.h>
#include <mmdeviceapi.h>

QT_BEGIN_NAMESPACE

static Q_LOGGING_CATEGORY(qLcAudioSource, "qt.multimedia.audiosource")

using namespace QWindowsMultimediaUtils;

class OurSink : public QIODevice
{
public:
    OurSink(QWindowsAudioSource& source) : QIODevice(&source), m_audioSource(source) {}

    qint64 bytesAvailable() const override { return m_audioSource.bytesReady(); }
    qint64 readData(char* data, qint64 len) override { return m_audioSource.read(data, len); }
    qint64 writeData(const char*, qint64) override { return 0; }

private:
    QWindowsAudioSource &m_audioSource;
};

QWindowsAudioSource::QWindowsAudioSource(ComPtr<IMMDevice> device, QObject *parent)
    : QPlatformAudioSource(parent),
      m_timer(new QTimer(this)),
      m_device(std::move(device)),
      m_ourSink(new OurSink(*this))
{
    m_ourSink->open(QIODevice::ReadOnly|QIODevice::Unbuffered);
    m_timer->setTimerType(Qt::PreciseTimer);
    m_timer->setSingleShot(true);
    m_timer->callOnTimeout(this, &QWindowsAudioSource::pullCaptureClient);
}

void QWindowsAudioSource::setVolume(qreal volume)
{
    m_volume = qBound(qreal(0), volume, qreal(1));
}

qreal QWindowsAudioSource::volume() const
{
    return m_volume;
}

QWindowsAudioSource::~QWindowsAudioSource()
{
    stop();
}

QAudio::Error QWindowsAudioSource::error() const
{
    return m_errorState;
}

QAudio::State QWindowsAudioSource::state() const
{
    return m_deviceState;
}

void QWindowsAudioSource::setFormat(const QAudioFormat& fmt)
{
    if (m_deviceState == QAudio::StoppedState) {
        m_format = fmt;
    } else {
        if (m_format != fmt) {
            qWarning() << "Cannot set a new audio format, in the current state ("
                       << m_deviceState << ")";
        }
    }
}

QAudioFormat QWindowsAudioSource::format() const
{
    return m_format;
}

void QWindowsAudioSource::deviceStateChange(QAudio::State state, QAudio::Error error)
{
    if (state != m_deviceState) {
        bool wasActive = m_deviceState == QAudio::ActiveState || m_deviceState == QAudio::IdleState;
        bool isActive = state == QAudio::ActiveState || state == QAudio::IdleState;

        if (isActive && !wasActive) {
            m_audioClient->Start();
            qCDebug(qLcAudioSource) << "Audio client started";

        } else if (wasActive && !isActive) {
            m_timer->stop();
            m_audioClient->Stop();
            qCDebug(qLcAudioSource) << "Audio client stopped";
        }

        m_deviceState = state;
        emit stateChanged(m_deviceState);
    }

    if (error != m_errorState) {
        m_errorState = error;
        emit errorChanged(error);
    }
}

QByteArray QWindowsAudioSource::readCaptureClientBuffer()
{
    UINT32 actualFrames = 0;
    BYTE *data = nullptr;
    DWORD flags = 0;
    HRESULT hr = m_captureClient->GetBuffer(&data, &actualFrames, &flags, nullptr, nullptr);
    if (FAILED(hr)) {
        qWarning() << "IAudioCaptureClient::GetBuffer failed" << errorString(hr);
        deviceStateChange(QAudio::IdleState, QAudio::IOError);
        return {};
    }

    if (actualFrames == 0)
        return {};

    QByteArray out;
    if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
        out.resize(m_resampler.outputFormat().bytesForDuration(
                           m_resampler.inputFormat().framesForDuration(actualFrames)),
                   0);
    } else {
        out = m_resampler.resample(
                { data, m_resampler.inputFormat().bytesForFrames(actualFrames) });
        QAudioHelperInternal::qMultiplySamples(m_volume, m_resampler.outputFormat(), out.data(), out.data(), out.size());
    }

    hr = m_captureClient->ReleaseBuffer(actualFrames);
    if (FAILED(hr)) {
        qWarning() << "IAudioCaptureClient::ReleaseBuffer failed" << errorString(hr);
        deviceStateChange(QAudio::IdleState, QAudio::IOError);
        return {};
    }

    return out;
}

void QWindowsAudioSource::schedulePull()
{
    auto allocated = QWindowsAudioUtils::audioClientFramesAllocated(m_audioClient.Get());
    auto inUse = QWindowsAudioUtils::audioClientFramesInUse(m_audioClient.Get());

    if (!allocated || !inUse) {
        deviceStateChange(QAudio::IdleState, QAudio::IOError);
    } else {
        // Schedule the next audio pull immediately if the audio buffer is more
        // than half-full or wait until the audio source fills at least half of it.
        if (*inUse > *allocated / 2) {
            m_timer->start(0);
        } else {
            auto timeToHalfBuffer = m_resampler.inputFormat().durationForFrames(*allocated / 2 - *inUse);
            m_timer->start(timeToHalfBuffer / 1000);
        }
    }
}

void QWindowsAudioSource::pullCaptureClient()
{
    qCDebug(qLcAudioSource) << "Pull captureClient";
    while (true) {
        auto out = readCaptureClientBuffer();
        if (out.isEmpty())
            break;

        if (m_clientSink) {
            qint64 written = m_clientSink->write(out.data(), out.size());
            if (written != out.size())
                qCDebug(qLcAudioSource) << "Did not write all data to the output";

        } else {
            m_clientBufferResidue += out;
            emit m_ourSink->readyRead();
        }
    }

    schedulePull();
}

void QWindowsAudioSource::start(QIODevice* device)
{
    qCDebug(qLcAudioSource) << "start(ioDevice)";
    if (m_deviceState != QAudio::StoppedState)
        close();

    if (device == nullptr)
        return;

    if (!open()) {
        m_errorState = QAudio::OpenError;
        emit errorChanged(QAudio::OpenError);
        return;
    }

    m_clientSink = device;
    schedulePull();
    deviceStateChange(QAudio::ActiveState, QAudio::NoError);
}

QIODevice* QWindowsAudioSource::start()
{
    qCDebug(qLcAudioSource) << "start()";
    if (m_deviceState != QAudio::StoppedState)
        close();

    if (!open()) {
        m_errorState = QAudio::OpenError;
        emit errorChanged(QAudio::OpenError);
        return nullptr;
    }

    schedulePull();
    deviceStateChange(QAudio::IdleState, QAudio::NoError);
    return m_ourSink;
}

void QWindowsAudioSource::stop()
{
    if (m_deviceState == QAudio::StoppedState)
        return;

    close();
}

bool QWindowsAudioSource::open()
{
    HRESULT hr = m_device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER,
                                    nullptr, (void**)m_audioClient.GetAddressOf());
    if (FAILED(hr)) {
        qCWarning(qLcAudioSource) << "Failed to activate audio device" << errorString(hr);
        return false;
    }

    QComTaskResource<WAVEFORMATEX> pwfx;
    hr = m_audioClient->GetMixFormat(pwfx.address());
    if (FAILED(hr)) {
        qCWarning(qLcAudioSource) << "Format unsupported" << errorString(hr);
        return false;
    }

    if (!m_resampler.setup(QWindowsAudioUtils::waveFormatExToFormat(*pwfx), m_format)) {
        qCWarning(qLcAudioSource) << "Failed to set up resampler";
        return false;
    }

    if (m_bufferSize == 0)
        m_bufferSize = m_format.sampleRate() * m_format.bytesPerFrame() / 5; // 200ms

    REFERENCE_TIME requestedDuration = m_format.durationForBytes(m_bufferSize);

    hr = m_audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, requestedDuration, 0, pwfx.get(),
                                   nullptr);

    if (FAILED(hr)) {
        qCWarning(qLcAudioSource) << "Failed to initialize audio client" << errorString(hr);
        return false;
    }

    auto framesAllocated = QWindowsAudioUtils::audioClientFramesAllocated(m_audioClient.Get());
    if (!framesAllocated) {
        qCWarning(qLcAudioSource) << "Failed to get audio client buffer size";
        return false;
    }

    m_bufferSize = m_format.bytesForDuration(
            m_resampler.inputFormat().durationForFrames(*framesAllocated));

    hr = m_audioClient->GetService(__uuidof(IAudioCaptureClient), (void**)m_captureClient.GetAddressOf());
    if (FAILED(hr)) {
        qCWarning(qLcAudioSource) << "Failed to obtain audio client rendering service" << errorString(hr);
        return false;
    }

    return true;
}

void QWindowsAudioSource::close()
{
    qCDebug(qLcAudioSource) << "close()";
    if (m_deviceState == QAudio::StoppedState)
        return;

    deviceStateChange(QAudio::StoppedState, QAudio::NoError);

    m_clientBufferResidue.clear();
    m_captureClient.Reset();
    m_audioClient.Reset();
    m_clientSink = nullptr;
}

qsizetype QWindowsAudioSource::bytesReady() const
{
    if (m_deviceState == QAudio::StoppedState || m_deviceState == QAudio::SuspendedState)
        return 0;

    auto frames = QWindowsAudioUtils::audioClientFramesInUse(m_audioClient.Get());
    if (frames) {
        auto clientBufferSize = m_resampler.outputFormat().bytesForDuration(
                m_resampler.inputFormat().durationForFrames(*frames));

        return clientBufferSize + m_clientBufferResidue.size();

    } else {
        return 0;
    }
}

qint64 QWindowsAudioSource::read(char* data, qint64 len)
{
    deviceStateChange(QAudio::ActiveState, QAudio::NoError);
    schedulePull();

    if (data == nullptr || len < 0)
        return -1;

    auto offset = 0;
    if (!m_clientBufferResidue.isEmpty()) {
        auto copyLen = qMin(m_clientBufferResidue.size(), len);
        memcpy(data, m_clientBufferResidue.data(), copyLen);
        len -= copyLen;
        offset += copyLen;
    }

    m_clientBufferResidue = QByteArray{ m_clientBufferResidue.data() + offset,
                                        m_clientBufferResidue.size() - offset };

    if (len > 0) {
        auto out = readCaptureClientBuffer();
        if (!out.isEmpty()) {
            qsizetype copyLen = qMin(out.size(), len);
            memcpy(data + offset, out.data(), copyLen);
            offset += copyLen;

            m_clientBufferResidue = QByteArray{ out.data() + copyLen, out.size() - copyLen };
        }
    }

    return offset;
}

void QWindowsAudioSource::resume()
{
    qCDebug(qLcAudioSource) << "resume()";
    if (m_deviceState == QAudio::SuspendedState) {
        deviceStateChange(QAudio::ActiveState, QAudio::NoError);
        pullCaptureClient();
    }
}

void QWindowsAudioSource::setBufferSize(qsizetype value)
{
    m_bufferSize = value;
}

qsizetype QWindowsAudioSource::bufferSize() const
{
    return m_bufferSize;
}

qint64 QWindowsAudioSource::processedUSecs() const
{
    if (m_deviceState == QAudio::StoppedState)
        return 0;

    return m_resampler.outputFormat().durationForBytes(m_resampler.totalOutputBytes());
}

void QWindowsAudioSource::suspend()
{
    qCDebug(qLcAudioSource) << "suspend";
    if (m_deviceState == QAudio::ActiveState || m_deviceState == QAudio::IdleState)
        deviceStateChange(QAudio::SuspendedState, QAudio::NoError);
}

void QWindowsAudioSource::reset()
{
    stop();
}

QT_END_NAMESPACE