sdl2.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 2018 by authors.
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Library General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Library General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Library General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. * Or go to http://www.gnu.org/copyleft/lgpl.html
  19. */
  20. #include "config.h"
  21. #include "sdl2.h"
  22. #include <cassert>
  23. #include <cstdlib>
  24. #include <cstring>
  25. #include <string>
  26. #include <string_view>
  27. #include "almalloc.h"
  28. #include "alnumeric.h"
  29. #include "core/device.h"
  30. #include "core/logging.h"
  31. _Pragma("GCC diagnostic push")
  32. _Pragma("GCC diagnostic ignored \"-Wold-style-cast\"")
  33. #include "SDL.h"
  34. _Pragma("GCC diagnostic pop")
  35. namespace {
  36. #ifdef _WIN32
  37. #define DEVNAME_PREFIX "OpenAL Soft on "
  38. #else
  39. #define DEVNAME_PREFIX ""
  40. #endif
  41. constexpr auto getDevicePrefix() noexcept -> std::string_view { return DEVNAME_PREFIX; }
  42. constexpr auto getDefaultDeviceName() noexcept -> std::string_view
  43. { return DEVNAME_PREFIX "Default Device"; }
  44. struct Sdl2Backend final : public BackendBase {
  45. Sdl2Backend(DeviceBase *device) noexcept : BackendBase{device} { }
  46. ~Sdl2Backend() override;
  47. void audioCallback(Uint8 *stream, int len) noexcept;
  48. void open(std::string_view name) override;
  49. bool reset() override;
  50. void start() override;
  51. void stop() override;
  52. SDL_AudioDeviceID mDeviceID{0u};
  53. uint mFrameSize{0};
  54. uint mFrequency{0u};
  55. DevFmtChannels mFmtChans{};
  56. DevFmtType mFmtType{};
  57. uint mUpdateSize{0u};
  58. };
  59. Sdl2Backend::~Sdl2Backend()
  60. {
  61. if(mDeviceID)
  62. SDL_CloseAudioDevice(mDeviceID);
  63. mDeviceID = 0;
  64. }
  65. void Sdl2Backend::audioCallback(Uint8 *stream, int len) noexcept
  66. {
  67. const auto ulen = static_cast<unsigned int>(len);
  68. assert((ulen % mFrameSize) == 0);
  69. mDevice->renderSamples(stream, ulen / mFrameSize, mDevice->channelsFromFmt());
  70. }
  71. void Sdl2Backend::open(std::string_view name)
  72. {
  73. SDL_AudioSpec want{}, have{};
  74. want.freq = static_cast<int>(mDevice->Frequency);
  75. switch(mDevice->FmtType)
  76. {
  77. case DevFmtUByte: want.format = AUDIO_U8; break;
  78. case DevFmtByte: want.format = AUDIO_S8; break;
  79. case DevFmtUShort: want.format = AUDIO_U16SYS; break;
  80. case DevFmtShort: want.format = AUDIO_S16SYS; break;
  81. case DevFmtUInt: /* fall-through */
  82. case DevFmtInt: want.format = AUDIO_S32SYS; break;
  83. case DevFmtFloat: want.format = AUDIO_F32; break;
  84. }
  85. want.channels = (mDevice->FmtChans == DevFmtMono) ? 1 : 2;
  86. want.samples = static_cast<Uint16>(std::min(mDevice->UpdateSize, 8192u));
  87. want.callback = [](void *ptr, Uint8 *stream, int len) noexcept
  88. { return static_cast<Sdl2Backend*>(ptr)->audioCallback(stream, len); };
  89. want.userdata = this;
  90. /* Passing nullptr to SDL_OpenAudioDevice opens a default, which isn't
  91. * necessarily the first in the list.
  92. */
  93. const auto defaultDeviceName = getDefaultDeviceName();
  94. SDL_AudioDeviceID devid;
  95. if(name.empty() || name == defaultDeviceName)
  96. {
  97. name = defaultDeviceName;
  98. devid = SDL_OpenAudioDevice(nullptr, SDL_FALSE, &want, &have, SDL_AUDIO_ALLOW_ANY_CHANGE);
  99. }
  100. else
  101. {
  102. const auto namePrefix = getDevicePrefix();
  103. if(name.size() >= namePrefix.size() && name.substr(0, namePrefix.size()) == namePrefix)
  104. {
  105. /* Copy the string_view to a string to ensure it's null terminated
  106. * for this call.
  107. */
  108. const std::string devname{name.substr(namePrefix.size())};
  109. devid = SDL_OpenAudioDevice(devname.c_str(), SDL_FALSE, &want, &have,
  110. SDL_AUDIO_ALLOW_ANY_CHANGE);
  111. }
  112. else
  113. {
  114. const std::string devname{name};
  115. devid = SDL_OpenAudioDevice(devname.c_str(), SDL_FALSE, &want, &have,
  116. SDL_AUDIO_ALLOW_ANY_CHANGE);
  117. }
  118. }
  119. if(!devid)
  120. throw al::backend_exception{al::backend_error::NoDevice, "%s", SDL_GetError()};
  121. DevFmtChannels devchans{};
  122. if(have.channels >= 2)
  123. devchans = DevFmtStereo;
  124. else if(have.channels == 1)
  125. devchans = DevFmtMono;
  126. else
  127. {
  128. SDL_CloseAudioDevice(devid);
  129. throw al::backend_exception{al::backend_error::DeviceError,
  130. "Unhandled SDL channel count: %d", int{have.channels}};
  131. }
  132. DevFmtType devtype{};
  133. switch(have.format)
  134. {
  135. case AUDIO_U8: devtype = DevFmtUByte; break;
  136. case AUDIO_S8: devtype = DevFmtByte; break;
  137. case AUDIO_U16SYS: devtype = DevFmtUShort; break;
  138. case AUDIO_S16SYS: devtype = DevFmtShort; break;
  139. case AUDIO_S32SYS: devtype = DevFmtInt; break;
  140. case AUDIO_F32SYS: devtype = DevFmtFloat; break;
  141. default:
  142. SDL_CloseAudioDevice(devid);
  143. throw al::backend_exception{al::backend_error::DeviceError, "Unhandled SDL format: 0x%04x",
  144. have.format};
  145. }
  146. if(mDeviceID)
  147. SDL_CloseAudioDevice(mDeviceID);
  148. mDeviceID = devid;
  149. mFrameSize = BytesFromDevFmt(devtype) * have.channels;
  150. mFrequency = static_cast<uint>(have.freq);
  151. mFmtChans = devchans;
  152. mFmtType = devtype;
  153. mUpdateSize = have.samples;
  154. mDevice->DeviceName = name;
  155. }
  156. bool Sdl2Backend::reset()
  157. {
  158. mDevice->Frequency = mFrequency;
  159. mDevice->FmtChans = mFmtChans;
  160. mDevice->FmtType = mFmtType;
  161. mDevice->UpdateSize = mUpdateSize;
  162. mDevice->BufferSize = mUpdateSize * 2; /* SDL always (tries to) use two periods. */
  163. setDefaultWFXChannelOrder();
  164. return true;
  165. }
  166. void Sdl2Backend::start()
  167. { SDL_PauseAudioDevice(mDeviceID, 0); }
  168. void Sdl2Backend::stop()
  169. { SDL_PauseAudioDevice(mDeviceID, 1); }
  170. } // namespace
  171. BackendFactory &SDL2BackendFactory::getFactory()
  172. {
  173. static SDL2BackendFactory factory{};
  174. return factory;
  175. }
  176. bool SDL2BackendFactory::init()
  177. { return (SDL_InitSubSystem(SDL_INIT_AUDIO) == 0); }
  178. bool SDL2BackendFactory::querySupport(BackendType type)
  179. { return type == BackendType::Playback; }
  180. auto SDL2BackendFactory::enumerate(BackendType type) -> std::vector<std::string>
  181. {
  182. std::vector<std::string> outnames;
  183. if(type != BackendType::Playback)
  184. return outnames;
  185. int num_devices{SDL_GetNumAudioDevices(SDL_FALSE)};
  186. if(num_devices <= 0)
  187. return outnames;
  188. outnames.reserve(static_cast<unsigned int>(num_devices));
  189. outnames.emplace_back(getDefaultDeviceName());
  190. for(int i{0};i < num_devices;++i)
  191. {
  192. std::string outname{getDevicePrefix()};
  193. if(const char *name = SDL_GetAudioDeviceName(i, SDL_FALSE))
  194. outname += name;
  195. else
  196. outname += "Unknown Device Name #"+std::to_string(i);
  197. outnames.emplace_back(std::move(outname));
  198. }
  199. return outnames;
  200. }
  201. BackendPtr SDL2BackendFactory::createBackend(DeviceBase *device, BackendType type)
  202. {
  203. if(type == BackendType::Playback)
  204. return BackendPtr{new Sdl2Backend{device}};
  205. return nullptr;
  206. }