summaryrefslogtreecommitdiff
path: root/Source/Core/AudioCommon/CubebUtils.cpp
blob: 85fb44767e834504336bded1042459593f9afc62 (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
// Copyright 2017 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "AudioCommon/CubebUtils.h"

#include <cstdarg>
#include <cstring>
#include <string_view>

#include "Common/Logging/Log.h"
#include "Common/Logging/LogManager.h"
#include "Common/StringUtil.h"

#include <cubeb/cubeb.h>

#ifdef _WIN32
#include <Objbase.h>
#endif

static void LogCallback(const char* format, ...)
{
  auto* instance = Common::Log::LogManager::GetInstance();
  if (instance == nullptr)
    return;

  constexpr auto log_type = Common::Log::LogType::AUDIO;
  constexpr auto log_level = Common::Log::LogLevel::LINFO;
  if (!instance->IsEnabled(log_type, log_level))
    return;

  va_list args;
  va_start(args, format);
  const char* filename = va_arg(args, const char*);
  const auto last_slash = std::string_view(filename).find_last_of("/\\");
  if (last_slash != std::string_view::npos)
    filename = filename + last_slash + 1;
  const int lineno = va_arg(args, int);
  const std::string adapted_format(StripWhitespace(format + strlen("%s:%d:")));
  const std::string message = StringFromFormatV(adapted_format.c_str(), args);
  va_end(args);

  instance->LogWithFullPath(log_level, log_type, filename, lineno, message.c_str());
}

static void DestroyContext(cubeb* ctx)
{
  cubeb_destroy(ctx);
  if (cubeb_set_log_callback(CUBEB_LOG_DISABLED, nullptr) != CUBEB_OK)
  {
    ERROR_LOG_FMT(AUDIO, "Error removing cubeb log callback");
  }
}

namespace CubebUtils
{
std::shared_ptr<cubeb> GetContext()
{
  static std::weak_ptr<cubeb> weak;

  std::shared_ptr<cubeb> shared = weak.lock();
  // Already initialized
  if (shared)
    return shared;

  if (cubeb_set_log_callback(CUBEB_LOG_NORMAL, LogCallback) != CUBEB_OK)
  {
    ERROR_LOG_FMT(AUDIO, "Error setting cubeb log callback");
  }

  cubeb* ctx;
  if (cubeb_init(&ctx, "Dolphin Emulator", nullptr) != CUBEB_OK)
  {
    ERROR_LOG_FMT(AUDIO, "Error initializing cubeb library");
    return nullptr;
  }
  INFO_LOG_FMT(AUDIO, "Cubeb initialized using {} backend", cubeb_get_backend_id(ctx));

  weak = shared = {ctx, DestroyContext};
  return shared;
}

std::vector<std::pair<std::string, std::string>> ListInputDevices()
{
  std::vector<std::pair<std::string, std::string>> devices;

  cubeb_device_collection collection;
  auto cubeb_ctx = GetContext();
  const int r = cubeb_enumerate_devices(cubeb_ctx.get(), CUBEB_DEVICE_TYPE_INPUT, &collection);

  if (r != CUBEB_OK)
  {
    ERROR_LOG_FMT(AUDIO, "Error listing cubeb input devices");
    return devices;
  }

  INFO_LOG_FMT(AUDIO, "Listing cubeb input devices:");
  for (uint32_t i = 0; i < collection.count; i++)
  {
    const auto& info = collection.device[i];
    const auto device_state = info.state;
    const char* state_name = [device_state] {
      switch (device_state)
      {
      case CUBEB_DEVICE_STATE_DISABLED:
        return "disabled";
      case CUBEB_DEVICE_STATE_UNPLUGGED:
        return "unplugged";
      case CUBEB_DEVICE_STATE_ENABLED:
        return "enabled";
      default:
        return "unknown?";
      }
    }();

    // According to cubeb_device_info definition in cubeb.h:
    //  > "Optional vendor name, may be NULL."
    // In practice, it seems some other fields might be NULL as well.
    static constexpr auto fmt_str = [](const char* ptr) constexpr -> const char* {
      return (ptr == nullptr) ? "(null)" : ptr;
    };

    INFO_LOG_FMT(AUDIO,
                 "[{}] Device ID: {}\n"
                 "\tName: {}\n"
                 "\tGroup ID: {}\n"
                 "\tVendor: {}\n"
                 "\tState: {}",
                 i, fmt_str(info.device_id), fmt_str(info.friendly_name), fmt_str(info.group_id),
                 fmt_str(info.vendor_name), state_name);

    if (info.device_id == nullptr)
      continue;  // Shouldn't happen

    if (info.state == CUBEB_DEVICE_STATE_ENABLED)
    {
      devices.emplace_back(info.device_id, fmt_str(info.friendly_name));
    }
  }

  cubeb_device_collection_destroy(cubeb_ctx.get(), &collection);

  return devices;
}

cubeb_devid GetInputDeviceById(std::string_view id)
{
  if (id.empty())
    return nullptr;

  cubeb_device_collection collection;
  auto cubeb_ctx = CubebUtils::GetContext();
  const int r = cubeb_enumerate_devices(cubeb_ctx.get(), CUBEB_DEVICE_TYPE_INPUT, &collection);

  if (r != CUBEB_OK)
  {
    ERROR_LOG_FMT(AUDIO, "Error enumerating cubeb input devices");
    return nullptr;
  }

  cubeb_devid device_id = nullptr;
  for (uint32_t i = 0; i < collection.count; i++)
  {
    const auto& info = collection.device[i];
    if (id.compare(info.device_id) == 0)
    {
      device_id = info.devid;
      break;
    }
  }
  if (device_id == nullptr)
  {
    WARN_LOG_FMT(AUDIO, "Failed to find selected input device, defaulting to system preferences");
  }

  cubeb_device_collection_destroy(cubeb_ctx.get(), &collection);

  return device_id;
}

std::vector<std::pair<std::string, std::string>> ListOutputDevices()
{
  std::vector<std::pair<std::string, std::string>> devices;

  cubeb_device_collection collection;
  auto cubeb_ctx = GetContext();
  if (!cubeb_ctx)
    return devices;

  const int r = cubeb_enumerate_devices(cubeb_ctx.get(), CUBEB_DEVICE_TYPE_OUTPUT, &collection);
  if (r != CUBEB_OK)
  {
    ERROR_LOG_FMT(AUDIO, "Error listing cubeb output devices");
    return devices;
  }

  for (uint32_t i = 0; i < collection.count; i++)
  {
    const auto& info = collection.device[i];
    if (info.device_id == nullptr)
      continue;

    if (info.state == CUBEB_DEVICE_STATE_ENABLED)
    {
      const char* name = (info.friendly_name != nullptr) ? info.friendly_name : info.device_id;
      devices.emplace_back(info.device_id, name);
    }
  }

  cubeb_device_collection_destroy(cubeb_ctx.get(), &collection);
  return devices;
}

const void* GetOutputDeviceById(std::string_view id)
{
  if (id.empty())
    return nullptr;

  cubeb_device_collection collection;
  auto cubeb_ctx = GetContext();
  if (!cubeb_ctx)
    return nullptr;

  const int r = cubeb_enumerate_devices(cubeb_ctx.get(), CUBEB_DEVICE_TYPE_OUTPUT, &collection);
  if (r != CUBEB_OK)
  {
    ERROR_LOG_FMT(AUDIO, "Error enumerating cubeb output devices");
    return nullptr;
  }

  cubeb_devid device_id = nullptr;
  for (uint32_t i = 0; i < collection.count; i++)
  {
    const auto& info = collection.device[i];
    if (info.device_id && id.compare(info.device_id) == 0)
    {
      device_id = info.devid;
      break;
    }
  }

  if (device_id == nullptr)
  {
    WARN_LOG_FMT(AUDIO, "Failed to find selected output device, defaulting to system preferences");
  }

  cubeb_device_collection_destroy(cubeb_ctx.get(), &collection);
  return device_id;
}

CoInitSyncWorker::CoInitSyncWorker([[maybe_unused]] std::string worker_name)
#ifdef _WIN32
    : m_work_queue{std::move(worker_name)}
#endif
{
#ifdef _WIN32
  m_work_queue.PushBlocking([this] {
    const auto result = ::CoInitializeEx(nullptr, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
    m_coinit_success = result == S_OK;
    m_should_couninit = m_coinit_success || result == S_FALSE;
  });
#endif
}

CoInitSyncWorker::~CoInitSyncWorker()
{
#ifdef _WIN32
  if (m_should_couninit)
  {
    m_work_queue.PushBlocking([this] {
      m_should_couninit = false;
      CoUninitialize();
    });
  }
  m_coinit_success = false;
#endif
}

bool CoInitSyncWorker::Execute(FunctionType f)
{
#ifdef _WIN32
  if (!m_coinit_success)
    return false;

  m_work_queue.PushBlocking(std::move(f));
#else
  f();
#endif
  return true;
}
}  // namespace CubebUtils