summaryrefslogtreecommitdiffstats
path: root/src/multimedia/darwin/qdarwinmediadevices.mm
blob: 46a91a850948d69b4f5fdde8b20e2357e356c6a1 (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
// Copyright (C) 2021 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

#include "qdarwinmediadevices_p.h"
#include "qmediadevices.h"
#include "private/qaudiodevice_p.h"
#include "qdarwinaudiodevice_p.h"
#include "qdarwinaudiosource_p.h"
#include "qdarwinaudiosink_p.h"

#include <qloggingcategory.h>

#include <qdebug.h>

#if defined(Q_OS_IOS)
#include "qcoreaudiosessionmanager_p.h"
#import <AVFoundation/AVFoundation.h>
#endif

Q_LOGGING_CATEGORY(qLcDarwinMediaDevices, "qt.multimedia.darwin.mediaDevices")

QT_BEGIN_NAMESPACE

template<typename... Args>
QAudioDevice createAudioDevice(bool isDefault, Args &&...args)
{
    auto *dev = new QCoreAudioDeviceInfo(std::forward<Args>(args)...);
    dev->isDefault = isDefault;
    return dev->create();
}

#if defined(Q_OS_MACOS)

static AudioDeviceID defaultAudioDevice(QAudioDevice::Mode mode)
{
    AudioDeviceID audioDevice;
    UInt32 size = sizeof(audioDevice);
    const AudioObjectPropertySelector selector = (mode == QAudioDevice::Output) ? kAudioHardwarePropertyDefaultOutputDevice
                                                                               : kAudioHardwarePropertyDefaultInputDevice;
    const AudioObjectPropertyAddress defaultDevicePropertyAddress = {
        selector, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster
    };

    if (AudioObjectGetPropertyData(kAudioObjectSystemObject,
                                   &defaultDevicePropertyAddress,
                                   0, NULL, &size, &audioDevice) != noErr) {
        qWarning("QAudioDevice: Unable to find default %s device",  (mode == QAudioDevice::Output) ? "output" : "input");
        return 0;
    }

    return audioDevice;
}

static QByteArray uniqueId(AudioDeviceID device, QAudioDevice::Mode mode)
{
    CFStringRef name;
    UInt32 size = sizeof(CFStringRef);

    const AudioObjectPropertyScope audioPropertyScope = mode == QAudioDevice::Input
            ? kAudioDevicePropertyScopeInput
            : kAudioDevicePropertyScopeOutput;

    const AudioObjectPropertyAddress audioDeviceNamePropertyAddress = {
        kAudioDevicePropertyDeviceUID, audioPropertyScope, kAudioObjectPropertyElementMaster
    };

    if (AudioObjectGetPropertyData(device, &audioDeviceNamePropertyAddress, 0, NULL, &size, &name) != noErr) {
        qWarning() << "QAudioDevice: Unable to get device UID";
        return QByteArray();
    }

    QString s = QString::fromCFString(name);
    CFRelease(name);
    return s.toUtf8();
}

static QList<QAudioDevice> availableAudioDevices(QAudioDevice::Mode mode)
{
    QList<QAudioDevice> devices;

    AudioDeviceID defaultDevice = defaultAudioDevice(mode);
    if (defaultDevice != 0)
        devices << createAudioDevice(true, defaultDevice, uniqueId(defaultDevice, mode), mode);

    UInt32 propSize = 0;
    const AudioObjectPropertyAddress audioDevicesPropertyAddress = {
        kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal,
        kAudioObjectPropertyElementMaster
    };

    if (AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesPropertyAddress, 0,
                                       nullptr, &propSize)
        == noErr) {

        std::vector<AudioDeviceID> audioDevices(propSize / sizeof(AudioDeviceID));

        if (!audioDevices.empty()
            && AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesPropertyAddress, 0,
                                          nullptr, &propSize, audioDevices.data())
                    == noErr) {

            const auto propertyScope = mode == QAudioDevice::Input
                    ? kAudioDevicePropertyScopeInput
                    : kAudioDevicePropertyScopeOutput;

            for (const auto &device : audioDevices) {
                if (device == defaultDevice)
                    continue;

                AudioStreamBasicDescription sf = {};
                UInt32 size = sizeof(AudioStreamBasicDescription);
                const AudioObjectPropertyAddress audioDeviceStreamFormatPropertyAddress = {
                    kAudioDevicePropertyStreamFormat, propertyScope,
                    kAudioObjectPropertyElementMaster
                };

                if (AudioObjectGetPropertyData(device, &audioDeviceStreamFormatPropertyAddress, 0,
                                               nullptr, &size, &sf)
                    == noErr)
                    devices << createAudioDevice(false, device, uniqueId(device, mode), mode);
            }
        }
    }

    return devices;
}

static OSStatus audioDeviceChangeListener(AudioObjectID id, UInt32,
                                          const AudioObjectPropertyAddress *address, void *ptr)
{
    Q_ASSERT(address);
    Q_ASSERT(ptr);

    QDarwinMediaDevices *instance = static_cast<QDarwinMediaDevices *>(ptr);

    qCDebug(qLcDarwinMediaDevices)
            << "audioDeviceChangeListener: id:" << id << "address: " << address->mSelector
            << address->mScope << address->mElement;

    switch (address->mSelector) {
    case kAudioHardwarePropertyDefaultInputDevice:
        instance->onInputsUpdated();
        break;
    case kAudioHardwarePropertyDefaultOutputDevice:
        instance->onOutputsUpdated();
        break;
    default:
        instance->onInputsUpdated();
        instance->onOutputsUpdated();
        break;
    }

    return 0;
}

static constexpr AudioObjectPropertyAddress listenerAddresses[] = {
    { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster },
    { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster },
    { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster }
};

static void setAudioListeners(QDarwinMediaDevices &instance)
{
    for (const auto &address : listenerAddresses) {
        const auto err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &address,
                                                        audioDeviceChangeListener, &instance);

        if (err)
            qWarning() << "Fail to add listener. mSelector:" << address.mSelector
                       << "mScope:" << address.mScope << "mElement:" << address.mElement
                       << "err:" << err;
    }
}

static void removeAudioListeners(QDarwinMediaDevices &instance)
{
    for (const auto &address : listenerAddresses) {
        const auto err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &address,
                                                           audioDeviceChangeListener, &instance);

        if (err)
            qWarning() << "Fail to remove listener. mSelector:" << address.mSelector
                       << "mScope:" << address.mScope << "mElement:" << address.mElement
                       << "err:" << err;
    }
}

#elif defined(Q_OS_IOS)

static QList<QAudioDevice> availableAudioDevices(QAudioDevice::Mode mode)
{
    QList<QAudioDevice> devices;

    if (mode == QAudioDevice::Output) {
        devices.append(createAudioDevice(true, "default", QAudioDevice::Output));
    } else {
        AVCaptureDevice *defaultDevice =
                [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];

        // TODO: Support Bluetooth and USB devices
        AVCaptureDeviceDiscoverySession *captureDeviceDiscoverySession =
                [AVCaptureDeviceDiscoverySession
                        discoverySessionWithDeviceTypes:@[ AVCaptureDeviceTypeBuiltInMicrophone ]
                                              mediaType:AVMediaTypeAudio
                                               position:AVCaptureDevicePositionUnspecified];

        NSArray *captureDevices = [captureDeviceDiscoverySession devices];
        for (AVCaptureDevice *device in captureDevices) {
            const bool isDefault =
                    defaultDevice && [defaultDevice.uniqueID isEqualToString:device.uniqueID];
            devices.append(createAudioDevice(isDefault,
                                             QString::fromNSString(device.uniqueID).toUtf8(),
                                             QAudioDevice::Input));
        }
    }

    return devices;
}

static void setAudioListeners(QDarwinMediaDevices &)
{
    // ### This should use the audio session manager
}

static void removeAudioListeners(QDarwinMediaDevices &)
{
    // ### This should use the audio session manager
}

#endif


QDarwinMediaDevices::QDarwinMediaDevices()
    : QPlatformMediaDevices()
{
#ifdef Q_OS_MACOS // TODO: implement setAudioListeners, removeAudioListeners for Q_OS_IOS, after
                  // that - remove or modify the define
    m_cachedAudioInputs = availableAudioDevices(QAudioDevice::Input);
    m_cachedAudioOutputs = availableAudioDevices(QAudioDevice::Output);
#endif

    setAudioListeners(*this);
}


QDarwinMediaDevices::~QDarwinMediaDevices()
{
    removeAudioListeners(*this);
}

QList<QAudioDevice> QDarwinMediaDevices::audioInputs() const
{
    return availableAudioDevices(QAudioDevice::Input);
}

QList<QAudioDevice> QDarwinMediaDevices::audioOutputs() const
{
    return availableAudioDevices(QAudioDevice::Output);
}

void QDarwinMediaDevices::onInputsUpdated()
{
    auto inputs = availableAudioDevices(QAudioDevice::Input);
    if (m_cachedAudioInputs != inputs) {
        m_cachedAudioInputs = inputs;
        audioInputsChanged();
    }
}

void QDarwinMediaDevices::onOutputsUpdated()
{
    auto outputs = availableAudioDevices(QAudioDevice::Output);
    if (m_cachedAudioOutputs != outputs) {
        m_cachedAudioOutputs = outputs;
        audioOutputsChanged();
    }
}

QPlatformAudioSource *QDarwinMediaDevices::createAudioSource(const QAudioDevice &info,
                                                             QObject *parent)
{
    return new QDarwinAudioSource(info, parent);
}

QPlatformAudioSink *QDarwinMediaDevices::createAudioSink(const QAudioDevice &info,
                                                         QObject *parent)
{
    return new QDarwinAudioSink(info, parent);
}

QT_END_NAMESPACE