summaryrefslogtreecommitdiffstats
path: root/src/plugins/coreaudio/coreaudiodeviceinfo.mm
blob: 277cbb4dd3d259412250b1873846453ec13d1af3 (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
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd and/or its subsidiary(-ies).
** Contact: https://www.qt.io/licensing/
**
** This file is part 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 "coreaudiodeviceinfo.h"
#include "coreaudioutils.h"
#if defined(Q_OS_IOS) || defined(Q_OS_TVOS)
# include "coreaudiosessionmanager.h"
#endif

#include <QtCore/QDataStream>
#include <QtCore/QDebug>
#include <QtCore/QSet>

QT_BEGIN_NAMESPACE

CoreAudioDeviceInfo::CoreAudioDeviceInfo(const QByteArray &device, QAudio::Mode mode)
    : m_mode(mode)
{
#if defined(Q_OS_OSX)
    quint32 deviceID;

    QDataStream dataStream(device);
    dataStream >> deviceID >> m_device;
    m_deviceId = AudioDeviceID(deviceID);
#else //iOS
    m_device = device;
#endif
}


QAudioFormat CoreAudioDeviceInfo::preferredFormat() const
{
    QAudioFormat format;

#if defined(Q_OS_OSX)
    UInt32  propSize = 0;
    AudioObjectPropertyScope audioDevicePropertyScope = m_mode == QAudio::AudioInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
    AudioObjectPropertyAddress audioDevicePropertyStreamsAddress = { kAudioDevicePropertyStreams,
                                                                     audioDevicePropertyScope,
                                                                     kAudioObjectPropertyElementMaster };

    if (AudioObjectGetPropertyDataSize(m_deviceId, &audioDevicePropertyStreamsAddress, 0, NULL, &propSize) == noErr) {

        const int sc = propSize / sizeof(AudioStreamID);

        if (sc > 0) {
            AudioStreamID*  streams = new AudioStreamID[sc];

            if (AudioObjectGetPropertyData(m_deviceId, &audioDevicePropertyStreamsAddress, 0, NULL, &propSize, streams) == noErr) {

                AudioObjectPropertyAddress audioDevicePhysicalFormatPropertyAddress = { kAudioStreamPropertyPhysicalFormat,
                                                                                        kAudioObjectPropertyScopeGlobal,
                                                                                        kAudioObjectPropertyElementMaster };

                for (int i = 0; i < sc; ++i) {
                    if (AudioObjectGetPropertyDataSize(streams[i], &audioDevicePhysicalFormatPropertyAddress, 0, NULL, &propSize) == noErr) {
                        AudioStreamBasicDescription sf;

                        if (AudioObjectGetPropertyData(streams[i], &audioDevicePhysicalFormatPropertyAddress, 0, NULL, &propSize, &sf) == noErr) {
                            format = CoreAudioUtils::toQAudioFormat(sf);
                            break;
                        } else {
                            qWarning() << "QAudioDeviceInfo: Unable to find perferedFormat for stream";
                        }
                    } else {
                        qWarning() << "QAudioDeviceInfo: Unable to find size of perferedFormat for stream";
                    }
                }
            }

            delete[] streams;
        }
    }
#else //iOS
    format.setSampleSize(16);
    if (m_mode == QAudio::AudioInput) {
        format.setChannelCount(1);
        format.setSampleRate(8000);
    } else {
        format.setChannelCount(2);
        format.setSampleRate(44100);
    }
    format.setCodec(QString::fromLatin1("audio/pcm"));
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);
#endif

    return format;
}


bool CoreAudioDeviceInfo::isFormatSupported(const QAudioFormat &format) const
{
    CoreAudioDeviceInfo *self = const_cast<CoreAudioDeviceInfo*>(this);

    //Sample rates are more of a suggestion with CoreAudio so as long as we get a
    //sane value then we can likely use it.
    return format.isValid()
            && format.codec() == QString::fromLatin1("audio/pcm")
            && format.sampleRate() > 0
            && self->supportedChannelCounts().contains(format.channelCount())
            && self->supportedSampleSizes().contains(format.sampleSize());
}


QString CoreAudioDeviceInfo::deviceName() const
{
    return m_device;
}


QStringList CoreAudioDeviceInfo::supportedCodecs()
{
    return QStringList() << QString::fromLatin1("audio/pcm");
}


QList<int> CoreAudioDeviceInfo::supportedSampleRates()
{
    QSet<int> sampleRates;

#if defined(Q_OS_OSX)
    UInt32  propSize = 0;
    AudioObjectPropertyScope scope = m_mode == QAudio::AudioInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
    AudioObjectPropertyAddress availableNominalSampleRatesAddress = { kAudioDevicePropertyAvailableNominalSampleRates,
                                                                      scope,
                                                                      kAudioObjectPropertyElementMaster };

    if (AudioObjectGetPropertyDataSize(m_deviceId, &availableNominalSampleRatesAddress, 0, NULL, &propSize) == noErr) {
        const int pc = propSize / sizeof(AudioValueRange);

        if (pc > 0) {
            AudioValueRange* vr = new AudioValueRange[pc];

            if (AudioObjectGetPropertyData(m_deviceId, &availableNominalSampleRatesAddress, 0, NULL, &propSize, vr) == noErr) {
                for (int i = 0; i < pc; ++i) {
                    sampleRates << vr[i].mMinimum << vr[i].mMaximum;
                }
            }

            delete[] vr;
        }
    }
#else //iOS
    //iOS doesn't have a way to query available sample rates
    //instead we provide reasonable targets
    //It may be necessary have CoreAudioSessionManger test combinations
    //with available hardware
    sampleRates << 8000 << 11025 << 22050 << 44100 << 48000;
#endif
    return sampleRates.toList();
}


QList<int> CoreAudioDeviceInfo::supportedChannelCounts()
{
    static QList<int> supportedChannels;

    if (supportedChannels.isEmpty()) {
        // If the number of channels is not supported by an audio device, Core Audio will
        // automatically convert the audio data.
        for (int i = 1; i <= 16; ++i)
            supportedChannels.append(i);
    }

    return supportedChannels;
}


QList<int> CoreAudioDeviceInfo::supportedSampleSizes()
{
    return QList<int>() << 8 << 16 << 24 << 32 << 64;
}


QList<QAudioFormat::Endian> CoreAudioDeviceInfo::supportedByteOrders()
{
    return QList<QAudioFormat::Endian>() << QAudioFormat::LittleEndian << QAudioFormat::BigEndian;
}


QList<QAudioFormat::SampleType> CoreAudioDeviceInfo::supportedSampleTypes()
{
    return QList<QAudioFormat::SampleType>() << QAudioFormat::SignedInt << QAudioFormat::UnSignedInt << QAudioFormat::Float;
}

#if defined(Q_OS_OSX)
// XXX: remove at some future date
static inline QString cfStringToQString(CFStringRef str)
{
    CFIndex length = CFStringGetLength(str);
    const UniChar *chars = CFStringGetCharactersPtr(str);
    if (chars)
        return QString(reinterpret_cast<const QChar *>(chars), length);

    UniChar buffer[length];
    CFStringGetCharacters(str, CFRangeMake(0, length), buffer);
    return QString(reinterpret_cast<const QChar *>(buffer), length);
}

static QByteArray get_device_info(AudioDeviceID audioDevice, QAudio::Mode mode)
{
    UInt32      size;
    QByteArray  device;
    QDataStream ds(&device, QIODevice::WriteOnly);
    AudioStreamBasicDescription     sf;
    CFStringRef name;
    Boolean     isInput = mode == QAudio::AudioInput;
    AudioObjectPropertyScope audioPropertyScope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;

    // Id
    ds << quint32(audioDevice);

    // Mode //TODO: Why don't we use the Stream Format we ask for?
    size = sizeof(AudioStreamBasicDescription);
    AudioObjectPropertyAddress audioDeviceStreamFormatPropertyAddress = { kAudioDevicePropertyStreamFormat,
                                                                    audioPropertyScope,
                                                                    kAudioObjectPropertyElementMaster };

    if (AudioObjectGetPropertyData(audioDevice, &audioDeviceStreamFormatPropertyAddress, 0, NULL, &size, &sf) != noErr) {
        return QByteArray();
    }

    // Name
    size = sizeof(CFStringRef);
    AudioObjectPropertyAddress audioDeviceNamePropertyAddress = { kAudioObjectPropertyName,
                                                                  audioPropertyScope,
                                                                  kAudioObjectPropertyElementMaster };

    if (AudioObjectGetPropertyData(audioDevice, &audioDeviceNamePropertyAddress, 0, NULL, &size, &name) != noErr) {
        qWarning() << "QAudioDeviceInfo: Unable to find device name";
        return QByteArray();
    }
    ds << cfStringToQString(name);

    CFRelease(name);

    return device;
}
#endif

QByteArray CoreAudioDeviceInfo::defaultDevice(QAudio::Mode mode)
{
#if defined(Q_OS_OSX)
    AudioDeviceID audioDevice;
    UInt32 size = sizeof(audioDevice);
    const AudioObjectPropertySelector selector = (mode == QAudio::AudioOutput) ? kAudioHardwarePropertyDefaultOutputDevice
                                                                               : kAudioHardwarePropertyDefaultInputDevice;
    AudioObjectPropertyAddress defaultDevicePropertyAddress = { selector,
                                                                kAudioObjectPropertyScopeGlobal,
                                                                kAudioObjectPropertyElementMaster };

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

    return get_device_info(audioDevice, mode);
#else //iOS
    const auto &devices = (mode == QAudio::AudioOutput) ? CoreAudioSessionManager::instance().outputDevices()
                                                        : CoreAudioSessionManager::instance().inputDevices();
    return !devices.isEmpty() ? devices.first() : QByteArray();
#endif
}

QList<QByteArray> CoreAudioDeviceInfo::availableDevices(QAudio::Mode mode)
{
    QList<QByteArray> devices;
#if defined(Q_OS_OSX)
    UInt32  propSize = 0;
    AudioObjectPropertyAddress audioDevicesPropertyAddress = { kAudioHardwarePropertyDevices,
                                                               kAudioObjectPropertyScopeGlobal,
                                                               kAudioObjectPropertyElementMaster };

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

        const int dc = propSize / sizeof(AudioDeviceID);

        if (dc > 0) {
            AudioDeviceID*  audioDevices = new AudioDeviceID[dc];

            if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesPropertyAddress, 0, NULL, &propSize, audioDevices) == noErr) {
                for (int i = 0; i < dc; ++i) {
                    const QByteArray &info = get_device_info(audioDevices[i], mode);
                    if (!info.isNull())
                        devices << info;
                }
            }

            delete[] audioDevices;
        }
    }
#else //iOS
    if (mode == QAudio::AudioOutput)
        return CoreAudioSessionManager::instance().outputDevices();
    if (mode == QAudio::AudioInput)
        return CoreAudioSessionManager::instance().inputDevices();
#endif

    return devices;
}

QT_END_NAMESPACE

#include "moc_coreaudiodeviceinfo.cpp"