1
0

enum-wasapi.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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,
  21. 0) +
  22. 1;
  23. device_name.resize(size);
  24. os_wcs_to_utf8(nameVar.pwszVal, len, &device_name[0],
  25. size);
  26. PropVariantClear(&nameVar);
  27. }
  28. }
  29. return device_name;
  30. }
  31. static void GetWASAPIAudioDevices_(vector<AudioDeviceInfo> &devices, bool input)
  32. {
  33. ComPtr<IMMDeviceEnumerator> enumerator;
  34. ComPtr<IMMDeviceCollection> collection;
  35. UINT count;
  36. HRESULT res;
  37. res = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL,
  38. __uuidof(IMMDeviceEnumerator),
  39. (void **)enumerator.Assign());
  40. if (FAILED(res))
  41. throw HRError("Failed to create enumerator", res);
  42. res = enumerator->EnumAudioEndpoints(input ? eCapture : eRender,
  43. DEVICE_STATE_ACTIVE,
  44. collection.Assign());
  45. if (FAILED(res))
  46. throw HRError("Failed to enumerate devices", res);
  47. res = collection->GetCount(&count);
  48. if (FAILED(res))
  49. throw HRError("Failed to get device count", res);
  50. for (UINT i = 0; i < count; i++) {
  51. ComPtr<IMMDevice> device;
  52. CoTaskMemPtr<WCHAR> w_id;
  53. AudioDeviceInfo info;
  54. size_t len, size;
  55. res = collection->Item(i, device.Assign());
  56. if (FAILED(res))
  57. continue;
  58. res = device->GetId(&w_id);
  59. if (FAILED(res) || !w_id || !*w_id)
  60. continue;
  61. info.name = GetDeviceName(device);
  62. len = wcslen(w_id);
  63. size = os_wcs_to_utf8(w_id, len, nullptr, 0) + 1;
  64. info.id.resize(size);
  65. os_wcs_to_utf8(w_id, len, &info.id[0], size);
  66. devices.push_back(info);
  67. }
  68. }
  69. void GetWASAPIAudioDevices(vector<AudioDeviceInfo> &devices, bool input)
  70. {
  71. devices.clear();
  72. try {
  73. GetWASAPIAudioDevices_(devices, input);
  74. } catch (HRError &error) {
  75. blog(LOG_WARNING, "[GetWASAPIAudioDevices] %s: %lX", error.str,
  76. error.hr);
  77. }
  78. }