cubeb_sink.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. // Copyright 2018 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <atomic>
  6. #include <cstring>
  7. #include "audio_core/cubeb_sink.h"
  8. #include "audio_core/stream.h"
  9. #include "audio_core/time_stretch.h"
  10. #include "common/assert.h"
  11. #include "common/logging/log.h"
  12. #include "common/ring_buffer.h"
  13. #include "core/settings.h"
  14. #ifdef _WIN32
  15. #include <objbase.h>
  16. #endif
  17. namespace AudioCore {
  18. class CubebSinkStream final : public SinkStream {
  19. public:
  20. CubebSinkStream(cubeb* ctx_, u32 sample_rate, u32 num_channels_, cubeb_devid output_device,
  21. const std::string& name)
  22. : ctx{ctx_}, num_channels{std::min(num_channels_, 6u)}, time_stretch{sample_rate,
  23. num_channels} {
  24. cubeb_stream_params params{};
  25. params.rate = sample_rate;
  26. params.channels = num_channels;
  27. params.format = CUBEB_SAMPLE_S16NE;
  28. params.prefs = CUBEB_STREAM_PREF_PERSIST;
  29. switch (num_channels) {
  30. case 1:
  31. params.layout = CUBEB_LAYOUT_MONO;
  32. break;
  33. case 2:
  34. params.layout = CUBEB_LAYOUT_STEREO;
  35. break;
  36. case 6:
  37. params.layout = CUBEB_LAYOUT_3F2_LFE;
  38. break;
  39. }
  40. u32 minimum_latency{};
  41. if (cubeb_get_min_latency(ctx, &params, &minimum_latency) != CUBEB_OK) {
  42. LOG_CRITICAL(Audio_Sink, "Error getting minimum latency");
  43. }
  44. if (cubeb_stream_init(ctx, &stream_backend, name.c_str(), nullptr, nullptr, output_device,
  45. &params, std::max(512u, minimum_latency),
  46. &CubebSinkStream::DataCallback, &CubebSinkStream::StateCallback,
  47. this) != CUBEB_OK) {
  48. LOG_CRITICAL(Audio_Sink, "Error initializing cubeb stream");
  49. return;
  50. }
  51. if (cubeb_stream_start(stream_backend) != CUBEB_OK) {
  52. LOG_CRITICAL(Audio_Sink, "Error starting cubeb stream");
  53. return;
  54. }
  55. }
  56. ~CubebSinkStream() override {
  57. if (!ctx) {
  58. return;
  59. }
  60. if (cubeb_stream_stop(stream_backend) != CUBEB_OK) {
  61. LOG_CRITICAL(Audio_Sink, "Error stopping cubeb stream");
  62. }
  63. cubeb_stream_destroy(stream_backend);
  64. }
  65. void EnqueueSamples(u32 source_num_channels, const std::vector<s16>& samples) override {
  66. if (source_num_channels > num_channels) {
  67. // Downsample 6 channels to 2
  68. ASSERT_MSG(source_num_channels == 6, "Channel count must be 6");
  69. std::vector<s16> buf;
  70. buf.reserve(samples.size() * num_channels / source_num_channels);
  71. for (std::size_t i = 0; i < samples.size(); i += source_num_channels) {
  72. // Downmixing implementation taken from the ATSC standard
  73. const s16 left{samples[i + 0]};
  74. const s16 right{samples[i + 1]};
  75. const s16 center{samples[i + 2]};
  76. const s16 surround_left{samples[i + 4]};
  77. const s16 surround_right{samples[i + 5]};
  78. // Not used in the ATSC reference implementation
  79. [[maybe_unused]] const s16 low_frequency_effects{samples[i + 3]};
  80. constexpr s32 clev{707}; // center mixing level coefficient
  81. constexpr s32 slev{707}; // surround mixing level coefficient
  82. buf.push_back(static_cast<s16>(left + (clev * center / 1000) +
  83. (slev * surround_left / 1000)));
  84. buf.push_back(static_cast<s16>(right + (clev * center / 1000) +
  85. (slev * surround_right / 1000)));
  86. }
  87. queue.Push(buf);
  88. return;
  89. }
  90. queue.Push(samples);
  91. }
  92. std::size_t SamplesInQueue(u32 channel_count) const override {
  93. if (!ctx)
  94. return 0;
  95. return queue.Size() / channel_count;
  96. }
  97. void Flush() override {
  98. should_flush = true;
  99. }
  100. u32 GetNumChannels() const {
  101. return num_channels;
  102. }
  103. private:
  104. std::vector<std::string> device_list;
  105. cubeb* ctx{};
  106. cubeb_stream* stream_backend{};
  107. u32 num_channels{};
  108. Common::RingBuffer<s16, 0x10000> queue;
  109. std::array<s16, 2> last_frame{};
  110. std::atomic<bool> should_flush{};
  111. TimeStretcher time_stretch;
  112. static long DataCallback(cubeb_stream* stream, void* user_data, const void* input_buffer,
  113. void* output_buffer, long num_frames);
  114. static void StateCallback(cubeb_stream* stream, void* user_data, cubeb_state state);
  115. };
  116. CubebSink::CubebSink(std::string_view target_device_name) {
  117. // Cubeb requires COM to be initialized on the thread calling cubeb_init on Windows
  118. #ifdef _WIN32
  119. com_init_result = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
  120. #endif
  121. if (cubeb_init(&ctx, "yuzu", nullptr) != CUBEB_OK) {
  122. LOG_CRITICAL(Audio_Sink, "cubeb_init failed");
  123. return;
  124. }
  125. if (target_device_name != auto_device_name && !target_device_name.empty()) {
  126. cubeb_device_collection collection;
  127. if (cubeb_enumerate_devices(ctx, CUBEB_DEVICE_TYPE_OUTPUT, &collection) != CUBEB_OK) {
  128. LOG_WARNING(Audio_Sink, "Audio output device enumeration not supported");
  129. } else {
  130. const auto collection_end{collection.device + collection.count};
  131. const auto device{
  132. std::find_if(collection.device, collection_end, [&](const cubeb_device_info& info) {
  133. return info.friendly_name != nullptr &&
  134. target_device_name == info.friendly_name;
  135. })};
  136. if (device != collection_end) {
  137. output_device = device->devid;
  138. }
  139. cubeb_device_collection_destroy(ctx, &collection);
  140. }
  141. }
  142. }
  143. CubebSink::~CubebSink() {
  144. if (!ctx) {
  145. return;
  146. }
  147. for (auto& sink_stream : sink_streams) {
  148. sink_stream.reset();
  149. }
  150. cubeb_destroy(ctx);
  151. #ifdef _WIN32
  152. if (SUCCEEDED(com_init_result)) {
  153. CoUninitialize();
  154. }
  155. #endif
  156. }
  157. SinkStream& CubebSink::AcquireSinkStream(u32 sample_rate, u32 num_channels,
  158. const std::string& name) {
  159. sink_streams.push_back(
  160. std::make_unique<CubebSinkStream>(ctx, sample_rate, num_channels, output_device, name));
  161. return *sink_streams.back();
  162. }
  163. long CubebSinkStream::DataCallback([[maybe_unused]] cubeb_stream* stream, void* user_data,
  164. [[maybe_unused]] const void* input_buffer, void* output_buffer,
  165. long num_frames) {
  166. auto* impl = static_cast<CubebSinkStream*>(user_data);
  167. auto* buffer = static_cast<u8*>(output_buffer);
  168. if (!impl) {
  169. return {};
  170. }
  171. const std::size_t num_channels = impl->GetNumChannels();
  172. const std::size_t samples_to_write = num_channels * num_frames;
  173. std::size_t samples_written;
  174. /*
  175. if (Settings::values.enable_audio_stretching.GetValue()) {
  176. const std::vector<s16> in{impl->queue.Pop()};
  177. const std::size_t num_in{in.size() / num_channels};
  178. s16* const out{reinterpret_cast<s16*>(buffer)};
  179. const std::size_t out_frames =
  180. impl->time_stretch.Process(in.data(), num_in, out, num_frames);
  181. samples_written = out_frames * num_channels;
  182. if (impl->should_flush) {
  183. impl->time_stretch.Flush();
  184. impl->should_flush = false;
  185. }
  186. } else {
  187. samples_written = impl->queue.Pop(buffer, samples_to_write);
  188. }*/
  189. samples_written = impl->queue.Pop(buffer, samples_to_write);
  190. if (samples_written >= num_channels) {
  191. std::memcpy(&impl->last_frame[0], buffer + (samples_written - num_channels) * sizeof(s16),
  192. num_channels * sizeof(s16));
  193. }
  194. // Fill the rest of the frames with last_frame
  195. for (std::size_t i = samples_written; i < samples_to_write; i += num_channels) {
  196. std::memcpy(buffer + i * sizeof(s16), &impl->last_frame[0], num_channels * sizeof(s16));
  197. }
  198. return num_frames;
  199. }
  200. void CubebSinkStream::StateCallback([[maybe_unused]] cubeb_stream* stream,
  201. [[maybe_unused]] void* user_data,
  202. [[maybe_unused]] cubeb_state state) {}
  203. std::vector<std::string> ListCubebSinkDevices() {
  204. std::vector<std::string> device_list;
  205. cubeb* ctx;
  206. if (cubeb_init(&ctx, "yuzu Device Enumerator", nullptr) != CUBEB_OK) {
  207. LOG_CRITICAL(Audio_Sink, "cubeb_init failed");
  208. return {};
  209. }
  210. cubeb_device_collection collection;
  211. if (cubeb_enumerate_devices(ctx, CUBEB_DEVICE_TYPE_OUTPUT, &collection) != CUBEB_OK) {
  212. LOG_WARNING(Audio_Sink, "Audio output device enumeration not supported");
  213. } else {
  214. for (std::size_t i = 0; i < collection.count; i++) {
  215. const cubeb_device_info& device = collection.device[i];
  216. if (device.friendly_name) {
  217. device_list.emplace_back(device.friendly_name);
  218. }
  219. }
  220. cubeb_device_collection_destroy(ctx, &collection);
  221. }
  222. cubeb_destroy(ctx);
  223. return device_list;
  224. }
  225. } // namespace AudioCore