portaudio.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 1999-2007 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 "backends/portaudio.h"
  22. #include <cstdio>
  23. #include <cstdlib>
  24. #include <cstring>
  25. #include "alcmain.h"
  26. #include "alexcpt.h"
  27. #include "alu.h"
  28. #include "alconfig.h"
  29. #include "dynload.h"
  30. #include "ringbuffer.h"
  31. #include <portaudio.h>
  32. namespace {
  33. constexpr ALCchar pa_device[] = "PortAudio Default";
  34. #ifdef HAVE_DYNLOAD
  35. void *pa_handle;
  36. #define MAKE_FUNC(x) decltype(x) * p##x
  37. MAKE_FUNC(Pa_Initialize);
  38. MAKE_FUNC(Pa_Terminate);
  39. MAKE_FUNC(Pa_GetErrorText);
  40. MAKE_FUNC(Pa_StartStream);
  41. MAKE_FUNC(Pa_StopStream);
  42. MAKE_FUNC(Pa_OpenStream);
  43. MAKE_FUNC(Pa_CloseStream);
  44. MAKE_FUNC(Pa_GetDefaultOutputDevice);
  45. MAKE_FUNC(Pa_GetDefaultInputDevice);
  46. MAKE_FUNC(Pa_GetStreamInfo);
  47. #undef MAKE_FUNC
  48. #ifndef IN_IDE_PARSER
  49. #define Pa_Initialize pPa_Initialize
  50. #define Pa_Terminate pPa_Terminate
  51. #define Pa_GetErrorText pPa_GetErrorText
  52. #define Pa_StartStream pPa_StartStream
  53. #define Pa_StopStream pPa_StopStream
  54. #define Pa_OpenStream pPa_OpenStream
  55. #define Pa_CloseStream pPa_CloseStream
  56. #define Pa_GetDefaultOutputDevice pPa_GetDefaultOutputDevice
  57. #define Pa_GetDefaultInputDevice pPa_GetDefaultInputDevice
  58. #define Pa_GetStreamInfo pPa_GetStreamInfo
  59. #endif
  60. #endif
  61. struct PortPlayback final : public BackendBase {
  62. PortPlayback(ALCdevice *device) noexcept : BackendBase{device} { }
  63. ~PortPlayback() override;
  64. int writeCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer,
  65. const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags) noexcept;
  66. static int writeCallbackC(const void *inputBuffer, void *outputBuffer,
  67. unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo,
  68. const PaStreamCallbackFlags statusFlags, void *userData) noexcept
  69. {
  70. return static_cast<PortPlayback*>(userData)->writeCallback(inputBuffer, outputBuffer,
  71. framesPerBuffer, timeInfo, statusFlags);
  72. }
  73. void open(const ALCchar *name) override;
  74. bool reset() override;
  75. bool start() override;
  76. void stop() override;
  77. PaStream *mStream{nullptr};
  78. PaStreamParameters mParams{};
  79. ALuint mUpdateSize{0u};
  80. DEF_NEWDEL(PortPlayback)
  81. };
  82. PortPlayback::~PortPlayback()
  83. {
  84. PaError err{mStream ? Pa_CloseStream(mStream) : paNoError};
  85. if(err != paNoError)
  86. ERR("Error closing stream: %s\n", Pa_GetErrorText(err));
  87. mStream = nullptr;
  88. }
  89. int PortPlayback::writeCallback(const void*, void *outputBuffer, unsigned long framesPerBuffer,
  90. const PaStreamCallbackTimeInfo*, const PaStreamCallbackFlags) noexcept
  91. {
  92. std::lock_guard<PortPlayback> _{*this};
  93. aluMixData(mDevice, outputBuffer, static_cast<ALuint>(framesPerBuffer));
  94. return 0;
  95. }
  96. void PortPlayback::open(const ALCchar *name)
  97. {
  98. if(!name)
  99. name = pa_device;
  100. else if(strcmp(name, pa_device) != 0)
  101. throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name};
  102. mUpdateSize = mDevice->UpdateSize;
  103. auto devidopt = ConfigValueInt(nullptr, "port", "device");
  104. if(devidopt && *devidopt >= 0) mParams.device = *devidopt;
  105. else mParams.device = Pa_GetDefaultOutputDevice();
  106. mParams.suggestedLatency = mDevice->BufferSize / static_cast<double>(mDevice->Frequency);
  107. mParams.hostApiSpecificStreamInfo = nullptr;
  108. mParams.channelCount = ((mDevice->FmtChans == DevFmtMono) ? 1 : 2);
  109. switch(mDevice->FmtType)
  110. {
  111. case DevFmtByte:
  112. mParams.sampleFormat = paInt8;
  113. break;
  114. case DevFmtUByte:
  115. mParams.sampleFormat = paUInt8;
  116. break;
  117. case DevFmtUShort:
  118. /* fall-through */
  119. case DevFmtShort:
  120. mParams.sampleFormat = paInt16;
  121. break;
  122. case DevFmtUInt:
  123. /* fall-through */
  124. case DevFmtInt:
  125. mParams.sampleFormat = paInt32;
  126. break;
  127. case DevFmtFloat:
  128. mParams.sampleFormat = paFloat32;
  129. break;
  130. }
  131. retry_open:
  132. PaError err{Pa_OpenStream(&mStream, nullptr, &mParams, mDevice->Frequency, mDevice->UpdateSize,
  133. paNoFlag, &PortPlayback::writeCallbackC, this)};
  134. if(err != paNoError)
  135. {
  136. if(mParams.sampleFormat == paFloat32)
  137. {
  138. mParams.sampleFormat = paInt16;
  139. goto retry_open;
  140. }
  141. throw al::backend_exception{ALC_INVALID_VALUE, "Failed to open stream: %s",
  142. Pa_GetErrorText(err)};
  143. }
  144. mDevice->DeviceName = name;
  145. }
  146. bool PortPlayback::reset()
  147. {
  148. const PaStreamInfo *streamInfo{Pa_GetStreamInfo(mStream)};
  149. mDevice->Frequency = static_cast<ALuint>(streamInfo->sampleRate);
  150. mDevice->UpdateSize = mUpdateSize;
  151. if(mParams.sampleFormat == paInt8)
  152. mDevice->FmtType = DevFmtByte;
  153. else if(mParams.sampleFormat == paUInt8)
  154. mDevice->FmtType = DevFmtUByte;
  155. else if(mParams.sampleFormat == paInt16)
  156. mDevice->FmtType = DevFmtShort;
  157. else if(mParams.sampleFormat == paInt32)
  158. mDevice->FmtType = DevFmtInt;
  159. else if(mParams.sampleFormat == paFloat32)
  160. mDevice->FmtType = DevFmtFloat;
  161. else
  162. {
  163. ERR("Unexpected sample format: 0x%lx\n", mParams.sampleFormat);
  164. return false;
  165. }
  166. if(mParams.channelCount == 2)
  167. mDevice->FmtChans = DevFmtStereo;
  168. else if(mParams.channelCount == 1)
  169. mDevice->FmtChans = DevFmtMono;
  170. else
  171. {
  172. ERR("Unexpected channel count: %u\n", mParams.channelCount);
  173. return false;
  174. }
  175. SetDefaultChannelOrder(mDevice);
  176. return true;
  177. }
  178. bool PortPlayback::start()
  179. {
  180. PaError err{Pa_StartStream(mStream)};
  181. if(err != paNoError)
  182. {
  183. ERR("Pa_StartStream() returned an error: %s\n", Pa_GetErrorText(err));
  184. return false;
  185. }
  186. return true;
  187. }
  188. void PortPlayback::stop()
  189. {
  190. PaError err{Pa_StopStream(mStream)};
  191. if(err != paNoError)
  192. ERR("Error stopping stream: %s\n", Pa_GetErrorText(err));
  193. }
  194. struct PortCapture final : public BackendBase {
  195. PortCapture(ALCdevice *device) noexcept : BackendBase{device} { }
  196. ~PortCapture() override;
  197. int readCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer,
  198. const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags) noexcept;
  199. static int readCallbackC(const void *inputBuffer, void *outputBuffer,
  200. unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo,
  201. const PaStreamCallbackFlags statusFlags, void *userData) noexcept
  202. {
  203. return static_cast<PortCapture*>(userData)->readCallback(inputBuffer, outputBuffer,
  204. framesPerBuffer, timeInfo, statusFlags);
  205. }
  206. void open(const ALCchar *name) override;
  207. bool start() override;
  208. void stop() override;
  209. ALCenum captureSamples(al::byte *buffer, ALCuint samples) override;
  210. ALCuint availableSamples() override;
  211. PaStream *mStream{nullptr};
  212. PaStreamParameters mParams;
  213. RingBufferPtr mRing{nullptr};
  214. DEF_NEWDEL(PortCapture)
  215. };
  216. PortCapture::~PortCapture()
  217. {
  218. PaError err{mStream ? Pa_CloseStream(mStream) : paNoError};
  219. if(err != paNoError)
  220. ERR("Error closing stream: %s\n", Pa_GetErrorText(err));
  221. mStream = nullptr;
  222. }
  223. int PortCapture::readCallback(const void *inputBuffer, void*, unsigned long framesPerBuffer,
  224. const PaStreamCallbackTimeInfo*, const PaStreamCallbackFlags) noexcept
  225. {
  226. mRing->write(inputBuffer, framesPerBuffer);
  227. return 0;
  228. }
  229. void PortCapture::open(const ALCchar *name)
  230. {
  231. if(!name)
  232. name = pa_device;
  233. else if(strcmp(name, pa_device) != 0)
  234. throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name};
  235. ALuint samples{mDevice->BufferSize};
  236. samples = maxu(samples, 100 * mDevice->Frequency / 1000);
  237. ALuint frame_size{mDevice->frameSizeFromFmt()};
  238. mRing = CreateRingBuffer(samples, frame_size, false);
  239. auto devidopt = ConfigValueInt(nullptr, "port", "capture");
  240. if(devidopt && *devidopt >= 0) mParams.device = *devidopt;
  241. else mParams.device = Pa_GetDefaultOutputDevice();
  242. mParams.suggestedLatency = 0.0f;
  243. mParams.hostApiSpecificStreamInfo = nullptr;
  244. switch(mDevice->FmtType)
  245. {
  246. case DevFmtByte:
  247. mParams.sampleFormat = paInt8;
  248. break;
  249. case DevFmtUByte:
  250. mParams.sampleFormat = paUInt8;
  251. break;
  252. case DevFmtShort:
  253. mParams.sampleFormat = paInt16;
  254. break;
  255. case DevFmtInt:
  256. mParams.sampleFormat = paInt32;
  257. break;
  258. case DevFmtFloat:
  259. mParams.sampleFormat = paFloat32;
  260. break;
  261. case DevFmtUInt:
  262. case DevFmtUShort:
  263. throw al::backend_exception{ALC_INVALID_VALUE, "%s samples not supported",
  264. DevFmtTypeString(mDevice->FmtType)};
  265. }
  266. mParams.channelCount = static_cast<int>(mDevice->channelsFromFmt());
  267. PaError err{Pa_OpenStream(&mStream, &mParams, nullptr, mDevice->Frequency,
  268. paFramesPerBufferUnspecified, paNoFlag, &PortCapture::readCallbackC, this)};
  269. if(err != paNoError)
  270. throw al::backend_exception{ALC_INVALID_VALUE, "Failed to open stream: %s",
  271. Pa_GetErrorText(err)};
  272. mDevice->DeviceName = name;
  273. }
  274. bool PortCapture::start()
  275. {
  276. PaError err{Pa_StartStream(mStream)};
  277. if(err != paNoError)
  278. {
  279. ERR("Error starting stream: %s\n", Pa_GetErrorText(err));
  280. return false;
  281. }
  282. return true;
  283. }
  284. void PortCapture::stop()
  285. {
  286. PaError err{Pa_StopStream(mStream)};
  287. if(err != paNoError)
  288. ERR("Error stopping stream: %s\n", Pa_GetErrorText(err));
  289. }
  290. ALCuint PortCapture::availableSamples()
  291. { return static_cast<ALCuint>(mRing->readSpace()); }
  292. ALCenum PortCapture::captureSamples(al::byte *buffer, ALCuint samples)
  293. {
  294. mRing->read(buffer, samples);
  295. return ALC_NO_ERROR;
  296. }
  297. } // namespace
  298. bool PortBackendFactory::init()
  299. {
  300. PaError err;
  301. #ifdef HAVE_DYNLOAD
  302. if(!pa_handle)
  303. {
  304. #ifdef _WIN32
  305. # define PALIB "portaudio.dll"
  306. #elif defined(__APPLE__) && defined(__MACH__)
  307. # define PALIB "libportaudio.2.dylib"
  308. #elif defined(__OpenBSD__)
  309. # define PALIB "libportaudio.so"
  310. #else
  311. # define PALIB "libportaudio.so.2"
  312. #endif
  313. pa_handle = LoadLib(PALIB);
  314. if(!pa_handle)
  315. return false;
  316. #define LOAD_FUNC(f) do { \
  317. p##f = reinterpret_cast<decltype(p##f)>(GetSymbol(pa_handle, #f)); \
  318. if(p##f == nullptr) \
  319. { \
  320. CloseLib(pa_handle); \
  321. pa_handle = nullptr; \
  322. return false; \
  323. } \
  324. } while(0)
  325. LOAD_FUNC(Pa_Initialize);
  326. LOAD_FUNC(Pa_Terminate);
  327. LOAD_FUNC(Pa_GetErrorText);
  328. LOAD_FUNC(Pa_StartStream);
  329. LOAD_FUNC(Pa_StopStream);
  330. LOAD_FUNC(Pa_OpenStream);
  331. LOAD_FUNC(Pa_CloseStream);
  332. LOAD_FUNC(Pa_GetDefaultOutputDevice);
  333. LOAD_FUNC(Pa_GetDefaultInputDevice);
  334. LOAD_FUNC(Pa_GetStreamInfo);
  335. #undef LOAD_FUNC
  336. if((err=Pa_Initialize()) != paNoError)
  337. {
  338. ERR("Pa_Initialize() returned an error: %s\n", Pa_GetErrorText(err));
  339. CloseLib(pa_handle);
  340. pa_handle = nullptr;
  341. return false;
  342. }
  343. }
  344. #else
  345. if((err=Pa_Initialize()) != paNoError)
  346. {
  347. ERR("Pa_Initialize() returned an error: %s\n", Pa_GetErrorText(err));
  348. return false;
  349. }
  350. #endif
  351. return true;
  352. }
  353. bool PortBackendFactory::querySupport(BackendType type)
  354. { return (type == BackendType::Playback || type == BackendType::Capture); }
  355. void PortBackendFactory::probe(DevProbe type, std::string *outnames)
  356. {
  357. switch(type)
  358. {
  359. case DevProbe::Playback:
  360. case DevProbe::Capture:
  361. /* Includes null char. */
  362. outnames->append(pa_device, sizeof(pa_device));
  363. break;
  364. }
  365. }
  366. BackendPtr PortBackendFactory::createBackend(ALCdevice *device, BackendType type)
  367. {
  368. if(type == BackendType::Playback)
  369. return BackendPtr{new PortPlayback{device}};
  370. if(type == BackendType::Capture)
  371. return BackendPtr{new PortCapture{device}};
  372. return nullptr;
  373. }
  374. BackendFactory &PortBackendFactory::getFactory()
  375. {
  376. static PortBackendFactory factory{};
  377. return factory;
  378. }