Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwindowsaudiodevices.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
5
6#include <QtCore/qdebug.h>
7#include <QtCore/private/qcomobject_p.h>
8#include <QtCore/private/qsystemerror_p.h>
9
10#include <QtMultimedia/qmediadevices.h>
11#include <QtMultimedia/private/qcomtaskresource_p.h>
12#include <QtMultimedia/private/qwindowsaudiodevice_p.h>
13#include <QtMultimedia/private/qwindowsaudiosink_p.h>
14#include <QtMultimedia/private/qwindowsaudiosource_p.h>
15#include <QtMultimedia/private/qwindows_propertystore_p.h>
16
17#include <audioclient.h>
18#include <functiondiscoverykeys_devpkey.h>
19#include <mmdeviceapi.h>
20
21#include <map>
22
24
25// older mingw does not have PKEY_Device_ContainerId defined
26// https://github.com/mingw-w64/mingw-w64/commit/7e6eca69655c81976acfd7cd6a1ed25e7961e8c7
27// defining it here to avoid depending on the mingw version
28DEFINE_PROPERTYKEY(PKEY_Device_ContainerIdQt, 0x8c7ed206, 0x3f8a, 0x4827, 0xb3, 0xab, 0xae, 0x9e,
29 0x1f, 0xae, 0xfc, 0x6c, 2);
30
31namespace QtWASAPI {
32
33namespace {
34
35enum class DeviceState : uint8_t {
36 active,
37 disabled,
38 notPresent,
39 unplugged,
40};
41
42constexpr DeviceState asDeviceState(DWORD state)
43{
44 switch (state) {
45 case DEVICE_STATE_ACTIVE:
46 return DeviceState::active;
47 case DEVICE_STATE_DISABLED:
48 return DeviceState::disabled;
49 case DEVICE_STATE_NOTPRESENT:
50 return DeviceState::notPresent;
51 case DEVICE_STATE_UNPLUGGED:
52 return DeviceState::unplugged;
53 default:
54 Q_UNREACHABLE_RETURN(DeviceState::notPresent);
55 }
56}
57
58} // namespace
59
61{
62 Q_OBJECT
63
65 QWindowsAudioDevices *m_windowsMediaDevices;
66
67 struct DeviceRecord
68 {
69 ComPtr<IMMDevice> device;
70 DeviceState state;
71 };
72
73 std::map<QString, DeviceRecord> m_deviceMap;
74
75public:
77 ComPtr<IMMDeviceEnumerator> enumerator)
78 : m_enumerator(enumerator), m_windowsMediaDevices(windowsMediaDevices)
79 {
80 ComPtr<IMMDeviceCollection> devColl;
81 UINT count = 0;
82
83 if (SUCCEEDED(m_enumerator->EnumAudioEndpoints(EDataFlow::eAll, DEVICE_STATEMASK_ALL,
84 devColl.GetAddressOf()))
85 && SUCCEEDED(devColl->GetCount(&count))) {
86 for (UINT i = 0; i < count; i++) {
87 ComPtr<IMMDevice> device;
88 if (FAILED(devColl->Item(i, device.GetAddressOf())))
89 continue;
90
91 auto enumerateResult = enumerateDevice(device);
92 if (!enumerateResult)
93 continue;
94
95 auto idResult = deviceId(enumerateResult->device);
96 if (!idResult)
97 continue;
98
99 m_deviceMap.emplace(std::move(*idResult), std::move(*enumerateResult));
100 }
101 }
102
103 // Does not seem to be necessary, but also won't do any harm
104 qRegisterMetaType<ComPtr<IMMDevice>>();
105 }
106
107signals:
112
113private:
114 HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role,
116 {
117 ComPtr device = [&] {
119 if (it != std::end(m_deviceMap))
120 return it->second.device;
121
122 return ComPtr<IMMDevice>{};
123 }();
124
125 if (role == ERole::eMultimedia) {
126 switch (flow) {
127 case EDataFlow::eCapture:
129 break;
130 case EDataFlow::eRender:
132 break;
133 case EDataFlow::eAll:
134 // Not expected, but handle it anyway
137 break;
138 default:
140 }
141 }
142
143 return S_OK;
144 }
145
162
175
195
205
207 {
210 if (FAILED(deviceStatus))
211 return q23::unexpected{ deviceStatus };
212 return enumerateDevice(device);
213 }
214
216 {
217 DWORD state = 0;
218
220 if (FAILED(stateStatus))
221 return q23::unexpected{ stateStatus };
222 return DeviceRecord{
223 device,
225 };
226 }
228 {
230 auto idStatus = device->GetId(id.address());
231 if (FAILED(idStatus))
232 return q23::unexpected{ idStatus };
233 return QString::fromWCharArray(id.get());
234 }
235
236 // Destructor is not public. Caller should call Release.
238};
239
240} // namespace QtWASAPI
241
244{
245 using namespace QtWASAPI;
246
247 auto hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER,
248 IID_PPV_ARGS(&m_deviceEnumerator));
249
250 if (FAILED(hr)) {
251 qWarning("Failed to instantiate IMMDeviceEnumerator (%s)."
252 "Audio device change notification will be disabled",
253 qPrintable(QSystemError::windowsComString(hr)));
254 return;
255 }
256
257 m_notificationClient = makeComObject<QtWASAPI::CMMNotificationClient>(this, m_deviceEnumerator);
258 m_deviceEnumerator->RegisterEndpointNotificationCallback(m_notificationClient.Get());
259
260 connect(m_notificationClient.Get(), &QtWASAPI::CMMNotificationClient::audioDeviceAdded, this,
261 [this] {
262 onAudioInputsChanged();
263 onAudioOutputsChanged();
264 });
265 connect(m_notificationClient.Get(), &QtWASAPI::CMMNotificationClient::audioDeviceRemoved, this,
266 [this](ComPtr<IMMDevice> device) {
267 {
268 std::lock_guard lock(m_cacheMutex);
269 m_cachedDevices.erase(device);
270 }
271 onAudioInputsChanged();
272 onAudioOutputsChanged();
273 });
274 connect(m_notificationClient.Get(), &QtWASAPI::CMMNotificationClient::audioDeviceDefaultChanged,
275 this, [this](QAudioDevice::Mode mode, ComPtr<IMMDevice> device) {
276 {
277 std::lock_guard lock(m_cacheMutex);
278
279 for (auto &entry : m_cachedDevices) {
280 if (entry.second.mode() != mode)
281 continue;
282
283 auto handle = QAudioDevicePrivate::handle<QWindowsAudioDevice>(entry.second);
284 Q_PRESUME(handle);
285
286 std::unique_ptr<QAudioDevicePrivate> newPrivate = handle->clone();
287 newPrivate->isDefault = entry.first == device;
288
289 entry.second = QAudioDevicePrivate::createQAudioDevice(std::move(newPrivate));
290 }
291 }
292
293 switch (mode) {
294 case QAudioDevice::Input:
295 onAudioInputsChanged();
296 break;
297 case QAudioDevice::Output:
298 onAudioOutputsChanged();
299 break;
300 default:
301 break;
302 }
303 });
304 connect(m_notificationClient.Get(),
305 &QtWASAPI::CMMNotificationClient::audioDevicePropertyChanged, this,
306 [this](ComPtr<IMMDevice> device) {
307 {
308 std::lock_guard lock(m_cacheMutex);
309 m_cachedDevices.erase(device);
310 }
311
312 onAudioInputsChanged();
313 onAudioOutputsChanged();
314 });
315}
316
318{
319 if (m_deviceEnumerator) {
320 // Note: Calling UnregisterEndpointNotificationCallback after CoUninitialize
321 // will abruptly terminate application, preventing remaining destructors from
322 // being called (QTBUG-120198).
323 m_deviceEnumerator->UnregisterEndpointNotificationCallback(m_notificationClient.Get());
324 }
325
326 m_deviceEnumerator.Reset();
327 m_notificationClient.Reset();
328}
329
330static std::optional<QString> getDeviceId(const ComPtr<IMMDevice> &dev)
331{
332 Q_ASSERT(dev);
333 QComTaskResource<WCHAR> id;
334 HRESULT status = dev->GetId(id.address());
335 if (FAILED(status)) {
336 qWarning() << "IMMDevice::GetId failed" << QSystemError::windowsComString(status);
337 return {};
338 }
339 return QString::fromWCharArray(id.get());
340}
341
342static std::optional<QAudioDevice> asQAudioDevice(ComPtr<IMMDevice> device, QAudioDevice::Mode mode,
343 std::optional<QString> defaultAudioDeviceID)
344{
345 using QtMultimediaPrivate::PropertyStoreHelper;
346
347 std::optional<QString> deviceId = getDeviceId(device);
348 if (!deviceId)
349 return std::nullopt;
350
351 q23::expected<PropertyStoreHelper, QString> props = PropertyStoreHelper::open(device);
352 if (!props) {
353 qWarning() << "OpenPropertyStore failed" << props.error();
354 return std::nullopt;
355 }
356
357 std::optional<QString> friendlyName = props->getString(PKEY_Device_FriendlyName);
358 if (!friendlyName) {
359 qWarning() << "Cannot read property store";
360 return std::nullopt;
361 }
362
363 std::optional<QUuid> deviceContainerId = props->getGUID(PKEY_Device_ContainerIdQt);
364 if (!deviceContainerId) {
365 qWarning() << "Cannot read property store";
366 return std::nullopt;
367 }
368
369 std::optional<uint32_t> formFactor = props->getUInt32(PKEY_AudioEndpoint_FormFactor);
370 if (!formFactor) {
371 qWarning() << "Cannot infer form factor";
372 return std::nullopt;
373 }
374
375 auto dev = std::make_unique<QWindowsAudioDevice>(deviceId->toUtf8(), device, *friendlyName,
376 *deviceContainerId,
377 EndpointFormFactor(*formFactor), mode);
378 dev->isDefault = deviceId == defaultAudioDeviceID;
379 return QAudioDevicePrivate::createQAudioDevice(std::move(dev));
380}
381
382QList<QAudioDevice> QWindowsAudioDevices::availableDevices(QAudioDevice::Mode mode) const
383{
384 if (!m_deviceEnumerator)
385 return {};
386
387 const bool audioOut = mode == QAudioDevice::Output;
388 const auto dataFlow = audioOut ? EDataFlow::eRender : EDataFlow::eCapture;
389
390 const auto defaultAudioDeviceID = [&, this]() -> std::optional<QString> {
391 ComPtr<IMMDevice> dev;
392 if (SUCCEEDED(m_deviceEnumerator->GetDefaultAudioEndpoint(dataFlow, ERole::eMultimedia,
393 dev.GetAddressOf())))
394 return getDeviceId(dev);
395
396 return std::nullopt;
397 }();
398
399 QList<QAudioDevice> devices;
400
401 ComPtr<IMMDeviceCollection> allActiveDevices;
402 HRESULT result = m_deviceEnumerator->EnumAudioEndpoints(dataFlow, DEVICE_STATE_ACTIVE,
403 allActiveDevices.GetAddressOf());
404
405 if (FAILED(result)) {
406 qWarning() << "IMMDeviceEnumerator::EnumAudioEndpoints failed"
407 << QSystemError::windowsComString(result);
408 return devices;
409 }
410
411 UINT numberOfDevices;
412 result = allActiveDevices->GetCount(&numberOfDevices);
413 if (FAILED(result)) {
414 qWarning() << "IMMDeviceCollection::GetCount failed"
415 << QSystemError::windowsComString(result);
416 return devices;
417 }
418
419 for (UINT index = 0; index != numberOfDevices; ++index) {
420 ComPtr<IMMDevice> device;
421 result = allActiveDevices->Item(index, device.GetAddressOf());
422 if (FAILED(result)) {
423 qWarning() << "IMMDeviceCollection::Item" << QSystemError::windowsComString(result);
424 continue;
425 }
426
427 {
428 std::lock_guard lock(m_cacheMutex);
429 auto cachedDevice = m_cachedDevices.find(device);
430 if (cachedDevice != m_cachedDevices.end()) {
431 devices.append(cachedDevice->second);
432 continue;
433 }
434 }
435
436 std::optional<QAudioDevice> audioDevice =
437 asQAudioDevice(device, mode, defaultAudioDeviceID);
438
439 if (audioDevice) {
440 devices.append(*audioDevice);
441 std::lock_guard lock(m_cacheMutex);
442 m_cachedDevices.emplace(device, *audioDevice);
443 }
444 }
445
446 auto deviceOrder = [](const QAudioDevice &lhs, const QAudioDevice &rhs) {
447 auto lhsHandle = QAudioDevicePrivate::handle<QWindowsAudioDevice>(lhs);
448 auto rhsHandle = QAudioDevicePrivate::handle<QWindowsAudioDevice>(rhs);
449 auto lhsKey = std::tie(lhsHandle->m_device_ContainerId, lhsHandle->m_formFactor,
450 lhsHandle->description);
451 auto rhsKey = std::tie(rhsHandle->m_device_ContainerId, rhsHandle->m_formFactor,
452 rhsHandle->description);
453 return lhsKey < rhsKey;
454 };
455
456 std::sort(devices.begin(), devices.end(), deviceOrder);
457 return devices;
458}
459
461{
462 return availableDevices(QAudioDevice::Input);
463}
464
466{
467 return availableDevices(QAudioDevice::Output);
468}
469
471 const QAudioFormat &fmt,
472 QObject *parent)
473{
474 return new QtWASAPI::QWindowsAudioSource(device, fmt, parent);
475}
476
478 const QAudioFormat &fmt, QObject *parent)
479{
480 return new QtWASAPI::QWindowsAudioSink(device, fmt, parent);
481}
482
483QT_END_NAMESPACE
484
485#include "qwindowsaudiodevices.moc"
QList< QAudioDevice > findAudioInputs() const override
QPlatformAudioSource * createAudioSource(const QAudioDevice &, const QAudioFormat &, QObject *parent) override
QPlatformAudioSink * createAudioSink(const QAudioDevice &, const QAudioFormat &, QObject *parent) override
QList< QAudioDevice > findAudioOutputs() const override
void audioDeviceDefaultChanged(QAudioDevice::Mode, ComPtr< IMMDevice >)
void audioDeviceRemoved(ComPtr< IMMDevice >)
CMMNotificationClient(QWindowsAudioDevices *windowsMediaDevices, ComPtr< IMMDeviceEnumerator > enumerator)
void audioDevicePropertyChanged(ComPtr< IMMDevice >)
QT_BEGIN_NAMESPACE DEFINE_PROPERTYKEY(PKEY_Device_ContainerIdQt, 0x8c7ed206, 0x3f8a, 0x4827, 0xb3, 0xab, 0xae, 0x9e, 0x1f, 0xae, 0xfc, 0x6c, 2)
static std::optional< QString > getDeviceId(const ComPtr< IMMDevice > &dev)
static std::optional< QAudioDevice > asQAudioDevice(ComPtr< IMMDevice > device, QAudioDevice::Mode mode, std::optional< QString > defaultAudioDeviceID)