alstreamcb.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /*
  2. * OpenAL Callback-based Stream Example
  3. *
  4. * Copyright (c) 2020 by Chris Robinson <[email protected]>
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. /* This file contains a streaming audio player using a callback buffer. */
  25. #include <string.h>
  26. #include <stdlib.h>
  27. #include <stdio.h>
  28. #include <atomic>
  29. #include <chrono>
  30. #include <memory>
  31. #include <stdexcept>
  32. #include <string>
  33. #include <thread>
  34. #include <vector>
  35. #include "sndfile.h"
  36. #include "AL/al.h"
  37. #include "AL/alc.h"
  38. #include "AL/alext.h"
  39. #include "common/alhelpers.h"
  40. #ifndef AL_SOFT_callback_buffer
  41. #define AL_SOFT_callback_buffer
  42. typedef unsigned int ALbitfieldSOFT;
  43. #define AL_BUFFER_CALLBACK_FUNCTION_SOFT 0x19A0
  44. #define AL_BUFFER_CALLBACK_USER_PARAM_SOFT 0x19A1
  45. typedef ALsizei (AL_APIENTRY*LPALBUFFERCALLBACKTYPESOFT)(ALvoid *userptr, ALvoid *sampledata, ALsizei numsamples);
  46. typedef void (AL_APIENTRY*LPALBUFFERCALLBACKSOFT)(ALuint buffer, ALenum format, ALsizei freq, LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags);
  47. typedef void (AL_APIENTRY*LPALGETBUFFERPTRSOFT)(ALuint buffer, ALenum param, ALvoid **value);
  48. typedef void (AL_APIENTRY*LPALGETBUFFER3PTRSOFT)(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3);
  49. typedef void (AL_APIENTRY*LPALGETBUFFERPTRVSOFT)(ALuint buffer, ALenum param, ALvoid **values);
  50. #endif
  51. namespace {
  52. using std::chrono::seconds;
  53. using std::chrono::nanoseconds;
  54. LPALBUFFERCALLBACKSOFT alBufferCallbackSOFT;
  55. struct StreamPlayer {
  56. /* A lockless ring-buffer (supports single-provider, single-consumer
  57. * operation).
  58. */
  59. std::unique_ptr<ALbyte[]> mBufferData;
  60. size_t mBufferDataSize{0};
  61. std::atomic<size_t> mReadPos{0};
  62. std::atomic<size_t> mWritePos{0};
  63. /* The buffer to get the callback, and source to play with. */
  64. ALuint mBuffer{0}, mSource{0};
  65. size_t mStartOffset{0};
  66. /* Handle for the audio file to decode. */
  67. SNDFILE *mSndfile{nullptr};
  68. SF_INFO mSfInfo{};
  69. size_t mDecoderOffset{0};
  70. /* The format of the callback samples. */
  71. ALenum mFormat;
  72. StreamPlayer()
  73. {
  74. alGenBuffers(1, &mBuffer);
  75. if(ALenum err{alGetError()})
  76. throw std::runtime_error{"alGenBuffers failed"};
  77. alGenSources(1, &mSource);
  78. if(ALenum err{alGetError()})
  79. {
  80. alDeleteBuffers(1, &mBuffer);
  81. throw std::runtime_error{"alGenSources failed"};
  82. }
  83. }
  84. ~StreamPlayer()
  85. {
  86. alDeleteSources(1, &mSource);
  87. alDeleteBuffers(1, &mBuffer);
  88. if(mSndfile)
  89. sf_close(mSndfile);
  90. }
  91. void close()
  92. {
  93. if(mSndfile)
  94. {
  95. alSourceRewind(mSource);
  96. alSourcei(mSource, AL_BUFFER, 0);
  97. sf_close(mSndfile);
  98. mSndfile = nullptr;
  99. }
  100. }
  101. bool open(const char *filename)
  102. {
  103. close();
  104. /* Open the file and figure out the OpenAL format. */
  105. mSndfile = sf_open(filename, SFM_READ, &mSfInfo);
  106. if(!mSndfile)
  107. {
  108. fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(mSndfile));
  109. return false;
  110. }
  111. mFormat = AL_NONE;
  112. if(mSfInfo.channels == 1)
  113. mFormat = AL_FORMAT_MONO16;
  114. else if(mSfInfo.channels == 2)
  115. mFormat = AL_FORMAT_STEREO16;
  116. else if(mSfInfo.channels == 3)
  117. {
  118. if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  119. mFormat = AL_FORMAT_BFORMAT2D_16;
  120. }
  121. else if(mSfInfo.channels == 4)
  122. {
  123. if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  124. mFormat = AL_FORMAT_BFORMAT3D_16;
  125. }
  126. if(!mFormat)
  127. {
  128. fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
  129. sf_close(mSndfile);
  130. mSndfile = nullptr;
  131. return false;
  132. }
  133. /* Set a 1s ring buffer size. */
  134. mBufferDataSize = static_cast<ALuint>(mSfInfo.samplerate*mSfInfo.channels) * sizeof(short);
  135. mBufferData.reset(new ALbyte[mBufferDataSize]);
  136. mReadPos.store(0, std::memory_order_relaxed);
  137. mWritePos.store(0, std::memory_order_relaxed);
  138. mDecoderOffset = 0;
  139. return true;
  140. }
  141. /* The actual C-style callback just forwards to the non-static method. Not
  142. * strictly needed and the compiler will optimize it to a normal function,
  143. * but it allows the callback implementation to have a nice 'this' pointer
  144. * with normal member access.
  145. */
  146. static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size)
  147. { return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
  148. ALsizei bufferCallback(void *data, ALsizei size)
  149. {
  150. /* NOTE: The callback *MUST* be real-time safe! That means no blocking,
  151. * no allocations or deallocations, no I/O, no page faults, or calls to
  152. * functions that could do these things (this includes calling to
  153. * libraries like SDL_sound, libsndfile, ffmpeg, etc). Nothing should
  154. * unexpectedly stall this call since the audio has to get to the
  155. * device on time.
  156. */
  157. ALsizei got{0};
  158. size_t roffset{mReadPos.load(std::memory_order_acquire)};
  159. while(got < size)
  160. {
  161. /* If the write offset == read offset, there's nothing left in the
  162. * ring-buffer. Break from the loop and give what has been written.
  163. */
  164. const size_t woffset{mWritePos.load(std::memory_order_relaxed)};
  165. if(woffset == roffset) break;
  166. /* If the write offset is behind the read offset, the readable
  167. * portion wrapped around. Just read up to the end of the buffer in
  168. * that case, otherwise read up to the write offset. Also limit the
  169. * amount to copy given how much is remaining to write.
  170. */
  171. size_t todo{((woffset < roffset) ? mBufferDataSize : woffset) - roffset};
  172. todo = std::min<size_t>(todo, static_cast<ALuint>(size-got));
  173. /* Copy from the ring buffer to the provided output buffer. Wrap
  174. * the resulting read offset if it reached the end of the ring-
  175. * buffer.
  176. */
  177. memcpy(data, &mBufferData[roffset], todo);
  178. data = static_cast<ALbyte*>(data) + todo;
  179. got += static_cast<ALsizei>(todo);
  180. roffset += todo;
  181. if(roffset == mBufferDataSize)
  182. roffset = 0;
  183. }
  184. /* Finally, store the updated read offset, and return how many bytes
  185. * have been written.
  186. */
  187. mReadPos.store(roffset, std::memory_order_release);
  188. return got;
  189. }
  190. bool prepare()
  191. {
  192. alBufferCallbackSOFT(mBuffer, mFormat, mSfInfo.samplerate, bufferCallbackC, this, 0);
  193. alSourcei(mSource, AL_BUFFER, static_cast<ALint>(mBuffer));
  194. if(ALenum err{alGetError()})
  195. {
  196. fprintf(stderr, "Failed to set callback: %s (0x%04x)\n", alGetString(err), err);
  197. return false;
  198. }
  199. return true;
  200. }
  201. bool update()
  202. {
  203. ALenum state;
  204. ALint pos;
  205. alGetSourcei(mSource, AL_SAMPLE_OFFSET, &pos);
  206. alGetSourcei(mSource, AL_SOURCE_STATE, &state);
  207. const size_t frame_size{static_cast<ALuint>(mSfInfo.channels) * sizeof(short)};
  208. size_t woffset{mWritePos.load(std::memory_order_acquire)};
  209. if(state != AL_INITIAL)
  210. {
  211. const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
  212. const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
  213. roffset};
  214. /* For a stopped (underrun) source, the current playback offset is
  215. * the current decoder offset excluding the readable buffered data.
  216. * For a playing/paused source, it's the source's offset including
  217. * the playback offset the source was started with.
  218. */
  219. const size_t curtime{((state==AL_STOPPED) ? (mDecoderOffset-readable) / frame_size
  220. : (static_cast<ALuint>(pos) + mStartOffset/frame_size))
  221. / static_cast<ALuint>(mSfInfo.samplerate)};
  222. printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferDataSize);
  223. }
  224. else
  225. fputs("Starting...", stdout);
  226. fflush(stdout);
  227. while(!sf_error(mSndfile))
  228. {
  229. size_t read_bytes;
  230. const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
  231. if(roffset > woffset)
  232. {
  233. /* Note that the ring buffer's writable space is one byte less
  234. * than the available area because the write offset ending up
  235. * at the read offset would be interpreted as being empty
  236. * instead of full.
  237. */
  238. const size_t writable{roffset-woffset-1};
  239. if(writable < frame_size) break;
  240. sf_count_t num_frames{sf_readf_short(mSndfile,
  241. reinterpret_cast<short*>(&mBufferData[woffset]),
  242. static_cast<sf_count_t>(writable/frame_size))};
  243. if(num_frames < 1) break;
  244. read_bytes = static_cast<size_t>(num_frames) * frame_size;
  245. woffset += read_bytes;
  246. }
  247. else
  248. {
  249. /* If the read offset is at or behind the write offset, the
  250. * writeable area (might) wrap around. Make sure the sample
  251. * data can fit, and calculate how much can go in front before
  252. * wrapping.
  253. */
  254. const size_t writable{!roffset ? mBufferDataSize-woffset-1 :
  255. (mBufferDataSize-woffset)};
  256. if(writable < frame_size) break;
  257. sf_count_t num_frames{sf_readf_short(mSndfile,
  258. reinterpret_cast<short*>(&mBufferData[woffset]),
  259. static_cast<sf_count_t>(writable/frame_size))};
  260. if(num_frames < 1) break;
  261. read_bytes = static_cast<size_t>(num_frames) * frame_size;
  262. woffset += read_bytes;
  263. if(woffset == mBufferDataSize)
  264. woffset = 0;
  265. }
  266. mWritePos.store(woffset, std::memory_order_release);
  267. mDecoderOffset += read_bytes;
  268. }
  269. if(state != AL_PLAYING && state != AL_PAUSED)
  270. {
  271. /* If the source is not playing or paused, it either underrun
  272. * (AL_STOPPED) or is just getting started (AL_INITIAL). If the
  273. * ring buffer is empty, it's done, otherwise play the source with
  274. * what's available.
  275. */
  276. const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
  277. const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
  278. roffset};
  279. if(readable == 0)
  280. return false;
  281. /* Store the playback offset that the source will start reading
  282. * from, so it can be tracked during playback.
  283. */
  284. mStartOffset = mDecoderOffset - readable;
  285. alSourcePlay(mSource);
  286. if(alGetError() != AL_NO_ERROR)
  287. return false;
  288. }
  289. return true;
  290. }
  291. };
  292. } // namespace
  293. int main(int argc, char **argv)
  294. {
  295. /* A simple RAII container for OpenAL startup and shutdown. */
  296. struct AudioManager {
  297. AudioManager(char ***argv_, int *argc_)
  298. {
  299. if(InitAL(argv_, argc_) != 0)
  300. throw std::runtime_error{"Failed to initialize OpenAL"};
  301. }
  302. ~AudioManager() { CloseAL(); }
  303. };
  304. /* Print out usage if no arguments were specified */
  305. if(argc < 2)
  306. {
  307. fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
  308. return 1;
  309. }
  310. argv++; argc--;
  311. AudioManager almgr{&argv, &argc};
  312. if(!alIsExtensionPresent("AL_SOFTX_callback_buffer"))
  313. {
  314. fprintf(stderr, "AL_SOFT_callback_buffer extension not available\n");
  315. return 1;
  316. }
  317. alBufferCallbackSOFT = reinterpret_cast<LPALBUFFERCALLBACKSOFT>(
  318. alGetProcAddress("alBufferCallbackSOFT"));
  319. ALCint refresh{25};
  320. alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh);
  321. std::unique_ptr<StreamPlayer> player{new StreamPlayer{}};
  322. /* Play each file listed on the command line */
  323. for(int i{0};i < argc;++i)
  324. {
  325. if(!player->open(argv[i]))
  326. continue;
  327. /* Get the name portion, without the path, for display. */
  328. const char *namepart{strrchr(argv[i], '/')};
  329. if(namepart || (namepart=strrchr(argv[i], '\\')))
  330. ++namepart;
  331. else
  332. namepart = argv[i];
  333. printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->mFormat),
  334. player->mSfInfo.samplerate);
  335. fflush(stdout);
  336. if(!player->prepare())
  337. {
  338. player->close();
  339. continue;
  340. }
  341. while(player->update())
  342. std::this_thread::sleep_for(nanoseconds{seconds{1}} / refresh);
  343. putc('\n', stdout);
  344. /* All done with this file. Close it and go to the next */
  345. player->close();
  346. }
  347. /* All done. */
  348. printf("Done.\n");
  349. return 0;
  350. }