cubeb_sink.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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(left + (clev * center / 1000) + (slev * surround_left / 1000));
  82. buf.push_back(right + (clev * center / 1000) + (slev * surround_right / 1000));
  83. }
  84. queue.Push(buf);
  85. return;
  86. }
  87. queue.Push(samples);
  88. }
  89. std::size_t SamplesInQueue(u32 channel_count) const override {
  90. if (!ctx)
  91. return 0;
  92. return queue.Size() / channel_count;
  93. }
  94. void Flush() override {
  95. should_flush = true;
  96. }
  97. u32 GetNumChannels() const {
  98. return num_channels;
  99. }
  100. private:
  101. std::vector<std::string> device_list;
  102. cubeb* ctx{};
  103. cubeb_stream* stream_backend{};
  104. u32 num_channels{};
  105. Common::RingBuffer<s16, 0x10000> queue;
  106. std::array<s16, 2> last_frame{};
  107. std::atomic<bool> should_flush{};
  108. TimeStretcher time_stretch;
  109. static long DataCallback(cubeb_stream* stream, void* user_data, const void* input_buffer,
  110. void* output_buffer, long num_frames);
  111. static void StateCallback(cubeb_stream* stream, void* user_data, cubeb_state state);
  112. };
  113. CubebSink::CubebSink(std::string_view target_device_name) {
  114. // Cubeb requires COM to be initialized on the thread calling cubeb_init on Windows
  115. #ifdef _WIN32
  116. com_init_result = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
  117. #endif
  118. if (cubeb_init(&ctx, "yuzu", nullptr) != CUBEB_OK) {
  119. LOG_CRITICAL(Audio_Sink, "cubeb_init failed");
  120. return;
  121. }
  122. if (target_device_name != auto_device_name && !target_device_name.empty()) {
  123. cubeb_device_collection collection;
  124. if (cubeb_enumerate_devices(ctx, CUBEB_DEVICE_TYPE_OUTPUT, &collection) != CUBEB_OK) {
  125. LOG_WARNING(Audio_Sink, "Audio output device enumeration not supported");
  126. } else {
  127. const auto collection_end{collection.device + collection.count};
  128. const auto device{
  129. std::find_if(collection.device, collection_end, [&](const cubeb_device_info& info) {
  130. return info.friendly_name != nullptr &&
  131. target_device_name == info.friendly_name;
  132. })};
  133. if (device != collection_end) {
  134. output_device = device->devid;
  135. }
  136. cubeb_device_collection_destroy(ctx, &collection);
  137. }
  138. }
  139. }
  140. CubebSink::~CubebSink() {
  141. if (!ctx) {
  142. return;
  143. }
  144. for (auto& sink_stream : sink_streams) {
  145. sink_stream.reset();
  146. }
  147. cubeb_destroy(ctx);
  148. #ifdef _WIN32
  149. if (SUCCEEDED(com_init_result)) {
  150. CoUninitialize();
  151. }
  152. #endif
  153. }
  154. SinkStream& CubebSink::AcquireSinkStream(u32 sample_rate, u32 num_channels,
  155. const std::string& name) {
  156. sink_streams.push_back(
  157. std::make_unique<CubebSinkStream>(ctx, sample_rate, num_channels, output_device, name));
  158. return *sink_streams.back();
  159. }
  160. long CubebSinkStream::DataCallback(cubeb_stream* stream, void* user_data, const void* input_buffer,
  161. void* output_buffer, long num_frames) {
  162. auto* impl = static_cast<CubebSinkStream*>(user_data);
  163. auto* buffer = static_cast<u8*>(output_buffer);
  164. if (!impl) {
  165. return {};
  166. }
  167. const std::size_t num_channels = impl->GetNumChannels();
  168. const std::size_t samples_to_write = num_channels * num_frames;
  169. std::size_t samples_written;
  170. /*
  171. if (Settings::values.enable_audio_stretching.GetValue()) {
  172. const std::vector<s16> in{impl->queue.Pop()};
  173. const std::size_t num_in{in.size() / num_channels};
  174. s16* const out{reinterpret_cast<s16*>(buffer)};
  175. const std::size_t out_frames =
  176. impl->time_stretch.Process(in.data(), num_in, out, num_frames);
  177. samples_written = out_frames * num_channels;
  178. if (impl->should_flush) {
  179. impl->time_stretch.Flush();
  180. impl->should_flush = false;
  181. }
  182. } else {
  183. samples_written = impl->queue.Pop(buffer, samples_to_write);
  184. }*/
  185. samples_written = impl->queue.Pop(buffer, samples_to_write);
  186. if (samples_written >= num_channels) {
  187. std::memcpy(&impl->last_frame[0], buffer + (samples_written - num_channels) * sizeof(s16),
  188. num_channels * sizeof(s16));
  189. }
  190. // Fill the rest of the frames with last_frame
  191. for (std::size_t i = samples_written; i < samples_to_write; i += num_channels) {
  192. std::memcpy(buffer + i * sizeof(s16), &impl->last_frame[0], num_channels * sizeof(s16));
  193. }
  194. return num_frames;
  195. }
  196. void CubebSinkStream::StateCallback(cubeb_stream* stream, void* user_data, cubeb_state state) {}
  197. std::vector<std::string> ListCubebSinkDevices() {
  198. std::vector<std::string> device_list;
  199. cubeb* ctx;
  200. if (cubeb_init(&ctx, "yuzu Device Enumerator", nullptr) != CUBEB_OK) {
  201. LOG_CRITICAL(Audio_Sink, "cubeb_init failed");
  202. return {};
  203. }
  204. cubeb_device_collection collection;
  205. if (cubeb_enumerate_devices(ctx, CUBEB_DEVICE_TYPE_OUTPUT, &collection) != CUBEB_OK) {
  206. LOG_WARNING(Audio_Sink, "Audio output device enumeration not supported");
  207. } else {
  208. for (std::size_t i = 0; i < collection.count; i++) {
  209. const cubeb_device_info& device = collection.device[i];
  210. if (device.friendly_name) {
  211. device_list.emplace_back(device.friendly_name);
  212. }
  213. }
  214. cubeb_device_collection_destroy(ctx, &collection);
  215. }
  216. cubeb_destroy(ctx);
  217. return device_list;
  218. }
  219. } // namespace AudioCore