cubeb_sink.cpp 9.0 KB

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