cubeb_sink.cpp 8.6 KB

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