sdl2_sink.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <span>
  4. #include <vector>
  5. #include <SDL.h>
  6. #include "audio_core/common/common.h"
  7. #include "audio_core/sink/sdl2_sink.h"
  8. #include "audio_core/sink/sink_stream.h"
  9. #include "common/logging/log.h"
  10. #include "common/scope_exit.h"
  11. #include "core/core.h"
  12. namespace AudioCore::Sink {
  13. /**
  14. * SDL sink stream, responsible for sinking samples to hardware.
  15. */
  16. class SDLSinkStream final : public SinkStream {
  17. public:
  18. /**
  19. * Create a new sink stream.
  20. *
  21. * @param device_channels_ - Number of channels supported by the hardware.
  22. * @param system_channels_ - Number of channels the audio systems expect.
  23. * @param output_device - Name of the output device to use for this stream.
  24. * @param input_device - Name of the input device to use for this stream.
  25. * @param type_ - Type of this stream.
  26. * @param system_ - Core system.
  27. * @param event - Event used only for audio renderer, signalled on buffer consume.
  28. */
  29. SDLSinkStream(u32 device_channels_, u32 system_channels_, const std::string& output_device,
  30. const std::string& input_device, StreamType type_, Core::System& system_)
  31. : SinkStream{system_, type_} {
  32. system_channels = system_channels_;
  33. device_channels = device_channels_;
  34. SDL_AudioSpec spec;
  35. spec.freq = TargetSampleRate;
  36. spec.channels = static_cast<u8>(device_channels);
  37. spec.format = AUDIO_S16SYS;
  38. spec.samples = TargetSampleCount * 2;
  39. spec.callback = &SDLSinkStream::DataCallback;
  40. spec.userdata = this;
  41. std::string device_name{output_device};
  42. bool capture{false};
  43. if (type == StreamType::In) {
  44. device_name = input_device;
  45. capture = true;
  46. }
  47. SDL_AudioSpec obtained;
  48. if (device_name.empty()) {
  49. device = SDL_OpenAudioDevice(nullptr, capture, &spec, &obtained, false);
  50. } else {
  51. device = SDL_OpenAudioDevice(device_name.c_str(), capture, &spec, &obtained, false);
  52. }
  53. if (device == 0) {
  54. LOG_CRITICAL(Audio_Sink, "Error opening SDL audio device: {}", SDL_GetError());
  55. return;
  56. }
  57. LOG_INFO(Service_Audio,
  58. "Opening SDL stream {} with: rate {} channels {} (system channels {}) "
  59. " samples {}",
  60. device, obtained.freq, obtained.channels, system_channels, obtained.samples);
  61. }
  62. /**
  63. * Destroy the sink stream.
  64. */
  65. ~SDLSinkStream() override {
  66. LOG_DEBUG(Service_Audio, "Destructing SDL stream {}", name);
  67. Finalize();
  68. }
  69. /**
  70. * Finalize the sink stream.
  71. */
  72. void Finalize() override {
  73. if (device == 0) {
  74. return;
  75. }
  76. Stop();
  77. SDL_ClearQueuedAudio(device);
  78. SDL_CloseAudioDevice(device);
  79. }
  80. /**
  81. * Start the sink stream.
  82. *
  83. * @param resume - Set to true if this is resuming the stream a previously-active stream.
  84. * Default false.
  85. */
  86. void Start(bool resume = false) override {
  87. if (device == 0 || !paused) {
  88. return;
  89. }
  90. paused = false;
  91. SDL_PauseAudioDevice(device, 0);
  92. }
  93. /**
  94. * Stop the sink stream.
  95. */
  96. void Stop() override {
  97. if (device == 0 || paused) {
  98. return;
  99. }
  100. SignalPause();
  101. SDL_PauseAudioDevice(device, 1);
  102. }
  103. private:
  104. /**
  105. * Main callback from SDL. Either expects samples from us (audio render/audio out), or will
  106. * provide samples to be copied (audio in).
  107. *
  108. * @param userdata - Custom data pointer passed along, points to a SDLSinkStream.
  109. * @param stream - Buffer of samples to be filled or read.
  110. * @param len - Length of the stream in bytes.
  111. */
  112. static void DataCallback(void* userdata, Uint8* stream, int len) {
  113. auto* impl = static_cast<SDLSinkStream*>(userdata);
  114. if (!impl) {
  115. return;
  116. }
  117. const std::size_t num_channels = impl->GetDeviceChannels();
  118. const std::size_t frame_size = num_channels;
  119. const std::size_t num_frames{len / num_channels / sizeof(s16)};
  120. if (impl->type == StreamType::In) {
  121. std::span<const s16> input_buffer{reinterpret_cast<const s16*>(stream),
  122. num_frames * frame_size};
  123. impl->ProcessAudioIn(input_buffer, num_frames);
  124. } else {
  125. std::span<s16> output_buffer{reinterpret_cast<s16*>(stream), num_frames * frame_size};
  126. impl->ProcessAudioOutAndRender(output_buffer, num_frames);
  127. }
  128. }
  129. /// SDL device id of the opened input/output device
  130. SDL_AudioDeviceID device{};
  131. };
  132. SDLSink::SDLSink(std::string_view target_device_name) {
  133. if (!SDL_WasInit(SDL_INIT_AUDIO)) {
  134. if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
  135. LOG_CRITICAL(Audio_Sink, "SDL_InitSubSystem audio failed: {}", SDL_GetError());
  136. return;
  137. }
  138. }
  139. if (target_device_name != auto_device_name && !target_device_name.empty()) {
  140. output_device = target_device_name;
  141. } else {
  142. output_device.clear();
  143. }
  144. device_channels = 2;
  145. }
  146. SDLSink::~SDLSink() = default;
  147. SinkStream* SDLSink::AcquireSinkStream(Core::System& system, u32 system_channels_,
  148. const std::string&, StreamType type) {
  149. system_channels = system_channels_;
  150. SinkStreamPtr& stream = sink_streams.emplace_back(std::make_unique<SDLSinkStream>(
  151. device_channels, system_channels, output_device, input_device, type, system));
  152. return stream.get();
  153. }
  154. void SDLSink::CloseStream(SinkStream* stream) {
  155. for (size_t i = 0; i < sink_streams.size(); i++) {
  156. if (sink_streams[i].get() == stream) {
  157. sink_streams[i].reset();
  158. sink_streams.erase(sink_streams.begin() + i);
  159. break;
  160. }
  161. }
  162. }
  163. void SDLSink::CloseStreams() {
  164. sink_streams.clear();
  165. }
  166. f32 SDLSink::GetDeviceVolume() const {
  167. if (sink_streams.empty()) {
  168. return 1.0f;
  169. }
  170. return sink_streams[0]->GetDeviceVolume();
  171. }
  172. void SDLSink::SetDeviceVolume(f32 volume) {
  173. for (auto& stream : sink_streams) {
  174. stream->SetDeviceVolume(volume);
  175. }
  176. }
  177. void SDLSink::SetSystemVolume(f32 volume) {
  178. for (auto& stream : sink_streams) {
  179. stream->SetSystemVolume(volume);
  180. }
  181. }
  182. std::vector<std::string> ListSDLSinkDevices(bool capture) {
  183. std::vector<std::string> device_list;
  184. if (!SDL_WasInit(SDL_INIT_AUDIO)) {
  185. if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
  186. LOG_CRITICAL(Audio_Sink, "SDL_InitSubSystem audio failed: {}", SDL_GetError());
  187. return {};
  188. }
  189. }
  190. const int device_count = SDL_GetNumAudioDevices(capture);
  191. for (int i = 0; i < device_count; ++i) {
  192. if (const char* name = SDL_GetAudioDeviceName(i, capture)) {
  193. device_list.emplace_back(name);
  194. }
  195. }
  196. return device_list;
  197. }
  198. bool IsSDLSuitable() {
  199. #if !defined(HAVE_SDL2)
  200. return false;
  201. #else
  202. // Check SDL can init
  203. if (!SDL_WasInit(SDL_INIT_AUDIO)) {
  204. if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
  205. LOG_ERROR(Audio_Sink, "SDL failed to init, it is not suitable. Error: {}",
  206. SDL_GetError());
  207. return false;
  208. }
  209. }
  210. // We can set any latency frequency we want with SDL, so no need to check that.
  211. // Check we can open a device with standard parameters
  212. SDL_AudioSpec spec;
  213. spec.freq = TargetSampleRate;
  214. spec.channels = 2u;
  215. spec.format = AUDIO_S16SYS;
  216. spec.samples = TargetSampleCount * 2;
  217. spec.callback = nullptr;
  218. spec.userdata = nullptr;
  219. SDL_AudioSpec obtained;
  220. auto device = SDL_OpenAudioDevice(nullptr, false, &spec, &obtained, false);
  221. if (device == 0) {
  222. LOG_ERROR(Audio_Sink, "SDL failed to open a device, it is not suitable. Error: {}",
  223. SDL_GetError());
  224. return false;
  225. }
  226. SDL_CloseAudioDevice(device);
  227. return true;
  228. #endif
  229. }
  230. } // namespace AudioCore::Sink