enum-wasapi.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include "enum-wasapi.hpp"
  2. #include <util/base.h>
  3. #include <util/platform.h>
  4. #include <util/windows/HRError.hpp>
  5. #include <util/windows/ComPtr.hpp>
  6. #include <util/windows/CoTaskMemPtr.hpp>
  7. using namespace std;
  8. string GetDeviceName(IMMDevice *device)
  9. {
  10. string device_name;
  11. ComPtr<IPropertyStore> store;
  12. HRESULT res;
  13. if (SUCCEEDED(device->OpenPropertyStore(STGM_READ, store.Assign()))) {
  14. PROPVARIANT nameVar;
  15. PropVariantInit(&nameVar);
  16. res = store->GetValue(PKEY_Device_FriendlyName, &nameVar);
  17. if (SUCCEEDED(res) && nameVar.pwszVal && *nameVar.pwszVal) {
  18. size_t len = wcslen(nameVar.pwszVal);
  19. size_t size;
  20. size = os_wcs_to_utf8(nameVar.pwszVal, len, nullptr, 0) + 1;
  21. device_name.resize(size);
  22. os_wcs_to_utf8(nameVar.pwszVal, len, &device_name[0], size);
  23. PropVariantClear(&nameVar);
  24. }
  25. }
  26. return device_name;
  27. }
  28. static void GetWASAPIAudioDevices_(vector<AudioDeviceInfo> &devices, bool input)
  29. {
  30. ComPtr<IMMDeviceEnumerator> enumerator;
  31. ComPtr<IMMDeviceCollection> collection;
  32. UINT count;
  33. HRESULT res;
  34. res = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
  35. (void **)enumerator.Assign());
  36. if (FAILED(res))
  37. throw HRError("Failed to create enumerator", res);
  38. res = enumerator->EnumAudioEndpoints(input ? eCapture : eRender, DEVICE_STATE_ACTIVE, collection.Assign());
  39. if (FAILED(res))
  40. throw HRError("Failed to enumerate devices", res);
  41. res = collection->GetCount(&count);
  42. if (FAILED(res))
  43. throw HRError("Failed to get device count", res);
  44. for (UINT i = 0; i < count; i++) {
  45. ComPtr<IMMDevice> device;
  46. CoTaskMemPtr<WCHAR> w_id;
  47. AudioDeviceInfo info;
  48. size_t len, size;
  49. res = collection->Item(i, device.Assign());
  50. if (FAILED(res))
  51. continue;
  52. res = device->GetId(&w_id);
  53. if (FAILED(res) || !w_id || !*w_id)
  54. continue;
  55. info.name = GetDeviceName(device);
  56. len = wcslen(w_id);
  57. size = os_wcs_to_utf8(w_id, len, nullptr, 0) + 1;
  58. info.id.resize(size);
  59. os_wcs_to_utf8(w_id, len, &info.id[0], size);
  60. devices.push_back(info);
  61. }
  62. }
  63. void GetWASAPIAudioDevices(vector<AudioDeviceInfo> &devices, bool input)
  64. {
  65. devices.clear();
  66. try {
  67. GetWASAPIAudioDevices_(devices, input);
  68. } catch (HRError &error) {
  69. blog(LOG_WARNING, "[GetWASAPIAudioDevices] %s: %lX", error.str, error.hr);
  70. }
  71. }