🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

392 lines
13 KiB

  1. /*
  2. * OpenAL Callback-based Stream Example
  3. *
  4. * Copyright (c) 2020 by Chris Robinson <chris.kcat@gmail.com>
  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. namespace {
  41. using std::chrono::seconds;
  42. using std::chrono::nanoseconds;
  43. LPALBUFFERCALLBACKSOFT alBufferCallbackSOFT;
  44. struct StreamPlayer {
  45. /* A lockless ring-buffer (supports single-provider, single-consumer
  46. * operation).
  47. */
  48. std::unique_ptr<ALbyte[]> mBufferData;
  49. size_t mBufferDataSize{0};
  50. std::atomic<size_t> mReadPos{0};
  51. std::atomic<size_t> mWritePos{0};
  52. /* The buffer to get the callback, and source to play with. */
  53. ALuint mBuffer{0}, mSource{0};
  54. size_t mStartOffset{0};
  55. /* Handle for the audio file to decode. */
  56. SNDFILE *mSndfile{nullptr};
  57. SF_INFO mSfInfo{};
  58. size_t mDecoderOffset{0};
  59. /* The format of the callback samples. */
  60. ALenum mFormat;
  61. StreamPlayer()
  62. {
  63. alGenBuffers(1, &mBuffer);
  64. if(ALenum err{alGetError()})
  65. throw std::runtime_error{"alGenBuffers failed"};
  66. alGenSources(1, &mSource);
  67. if(ALenum err{alGetError()})
  68. {
  69. alDeleteBuffers(1, &mBuffer);
  70. throw std::runtime_error{"alGenSources failed"};
  71. }
  72. }
  73. ~StreamPlayer()
  74. {
  75. alDeleteSources(1, &mSource);
  76. alDeleteBuffers(1, &mBuffer);
  77. if(mSndfile)
  78. sf_close(mSndfile);
  79. }
  80. void close()
  81. {
  82. if(mSndfile)
  83. {
  84. alSourceRewind(mSource);
  85. alSourcei(mSource, AL_BUFFER, 0);
  86. sf_close(mSndfile);
  87. mSndfile = nullptr;
  88. }
  89. }
  90. bool open(const char *filename)
  91. {
  92. close();
  93. /* Open the file and figure out the OpenAL format. */
  94. mSndfile = sf_open(filename, SFM_READ, &mSfInfo);
  95. if(!mSndfile)
  96. {
  97. fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(mSndfile));
  98. return false;
  99. }
  100. mFormat = AL_NONE;
  101. if(mSfInfo.channels == 1)
  102. mFormat = AL_FORMAT_MONO_FLOAT32;
  103. else if(mSfInfo.channels == 2)
  104. mFormat = AL_FORMAT_STEREO_FLOAT32;
  105. else if(mSfInfo.channels == 3)
  106. {
  107. if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  108. mFormat = AL_FORMAT_BFORMAT2D_FLOAT32;
  109. }
  110. else if(mSfInfo.channels == 4)
  111. {
  112. if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  113. mFormat = AL_FORMAT_BFORMAT3D_FLOAT32;
  114. }
  115. if(!mFormat)
  116. {
  117. fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
  118. sf_close(mSndfile);
  119. mSndfile = nullptr;
  120. return false;
  121. }
  122. /* Set a 1s ring buffer size. */
  123. mBufferDataSize = static_cast<ALuint>(mSfInfo.samplerate*mSfInfo.channels) * sizeof(float);
  124. mBufferData.reset(new ALbyte[mBufferDataSize]);
  125. mReadPos.store(0, std::memory_order_relaxed);
  126. mWritePos.store(0, std::memory_order_relaxed);
  127. mDecoderOffset = 0;
  128. return true;
  129. }
  130. /* The actual C-style callback just forwards to the non-static method. Not
  131. * strictly needed and the compiler will optimize it to a normal function,
  132. * but it allows the callback implementation to have a nice 'this' pointer
  133. * with normal member access.
  134. */
  135. static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size)
  136. { return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
  137. ALsizei bufferCallback(void *data, ALsizei size)
  138. {
  139. /* NOTE: The callback *MUST* be real-time safe! That means no blocking,
  140. * no allocations or deallocations, no I/O, no page faults, or calls to
  141. * functions that could do these things (this includes calling to
  142. * libraries like SDL_sound, libsndfile, ffmpeg, etc). Nothing should
  143. * unexpectedly stall this call since the audio has to get to the
  144. * device on time.
  145. */
  146. ALsizei got{0};
  147. size_t roffset{mReadPos.load(std::memory_order_acquire)};
  148. while(got < size)
  149. {
  150. /* If the write offset == read offset, there's nothing left in the
  151. * ring-buffer. Break from the loop and give what has been written.
  152. */
  153. const size_t woffset{mWritePos.load(std::memory_order_relaxed)};
  154. if(woffset == roffset) break;
  155. /* If the write offset is behind the read offset, the readable
  156. * portion wrapped around. Just read up to the end of the buffer in
  157. * that case, otherwise read up to the write offset. Also limit the
  158. * amount to copy given how much is remaining to write.
  159. */
  160. size_t todo{((woffset < roffset) ? mBufferDataSize : woffset) - roffset};
  161. todo = std::min<size_t>(todo, static_cast<ALuint>(size-got));
  162. /* Copy from the ring buffer to the provided output buffer. Wrap
  163. * the resulting read offset if it reached the end of the ring-
  164. * buffer.
  165. */
  166. memcpy(data, &mBufferData[roffset], todo);
  167. data = static_cast<ALbyte*>(data) + todo;
  168. got += static_cast<ALsizei>(todo);
  169. roffset += todo;
  170. if(roffset == mBufferDataSize)
  171. roffset = 0;
  172. }
  173. /* Finally, store the updated read offset, and return how many bytes
  174. * have been written.
  175. */
  176. mReadPos.store(roffset, std::memory_order_release);
  177. return got;
  178. }
  179. bool prepare()
  180. {
  181. alBufferCallbackSOFT(mBuffer, mFormat, mSfInfo.samplerate, bufferCallbackC, this);
  182. alSourcei(mSource, AL_BUFFER, static_cast<ALint>(mBuffer));
  183. if(ALenum err{alGetError()})
  184. {
  185. fprintf(stderr, "Failed to set callback: %s (0x%04x)\n", alGetString(err), err);
  186. return false;
  187. }
  188. return true;
  189. }
  190. bool update()
  191. {
  192. ALenum state;
  193. ALint pos;
  194. alGetSourcei(mSource, AL_SAMPLE_OFFSET, &pos);
  195. alGetSourcei(mSource, AL_SOURCE_STATE, &state);
  196. const size_t frame_size{static_cast<ALuint>(mSfInfo.channels) * sizeof(float)};
  197. size_t woffset{mWritePos.load(std::memory_order_acquire)};
  198. if(state != AL_INITIAL)
  199. {
  200. const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
  201. const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
  202. roffset};
  203. /* For a stopped (underrun) source, the current playback offset is
  204. * the current decoder offset excluding the readable buffered data.
  205. * For a playing/paused source, it's the source's offset including
  206. * the playback offset the source was started with.
  207. */
  208. const size_t curtime{((state==AL_STOPPED) ? (mDecoderOffset-readable) / frame_size
  209. : (static_cast<ALuint>(pos) + mStartOffset/frame_size))
  210. / static_cast<ALuint>(mSfInfo.samplerate)};
  211. printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferDataSize);
  212. }
  213. else
  214. fputs("Starting...", stdout);
  215. fflush(stdout);
  216. while(!sf_error(mSndfile))
  217. {
  218. size_t read_bytes;
  219. const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
  220. if(roffset > woffset)
  221. {
  222. /* Note that the ring buffer's writable space is one byte less
  223. * than the available area because the write offset ending up
  224. * at the read offset would be interpreted as being empty
  225. * instead of full.
  226. */
  227. const size_t writable{roffset-woffset-1};
  228. if(writable < frame_size) break;
  229. sf_count_t num_frames{sf_readf_float(mSndfile,
  230. reinterpret_cast<float*>(&mBufferData[woffset]),
  231. static_cast<sf_count_t>(writable/frame_size))};
  232. if(num_frames < 1) break;
  233. read_bytes = static_cast<size_t>(num_frames) * frame_size;
  234. woffset += read_bytes;
  235. }
  236. else
  237. {
  238. /* If the read offset is at or behind the write offset, the
  239. * writeable area (might) wrap around. Make sure the sample
  240. * data can fit, and calculate how much can go in front before
  241. * wrapping.
  242. */
  243. const size_t writable{!roffset ? mBufferDataSize-woffset-1 :
  244. (mBufferDataSize-woffset)};
  245. if(writable < frame_size) break;
  246. sf_count_t num_frames{sf_readf_float(mSndfile,
  247. reinterpret_cast<float*>(&mBufferData[woffset]),
  248. static_cast<sf_count_t>(writable/frame_size))};
  249. if(num_frames < 1) break;
  250. read_bytes = static_cast<size_t>(num_frames) * frame_size;
  251. woffset += read_bytes;
  252. if(woffset == mBufferDataSize)
  253. woffset = 0;
  254. }
  255. mWritePos.store(woffset, std::memory_order_release);
  256. mDecoderOffset += read_bytes;
  257. }
  258. if(state != AL_PLAYING && state != AL_PAUSED)
  259. {
  260. /* If the source is not playing or paused, it either underrun
  261. * (AL_STOPPED) or is just getting started (AL_INITIAL). If the
  262. * ring buffer is empty, it's done, otherwise play the source with
  263. * what's available.
  264. */
  265. const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
  266. const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
  267. roffset};
  268. if(readable == 0)
  269. return false;
  270. /* Store the playback offset that the source will start reading
  271. * from, so it can be tracked during playback.
  272. */
  273. mStartOffset = mDecoderOffset - readable;
  274. alSourcePlay(mSource);
  275. if(alGetError() != AL_NO_ERROR)
  276. return false;
  277. }
  278. return true;
  279. }
  280. };
  281. } // namespace
  282. int main(int argc, char **argv)
  283. {
  284. /* A simple RAII container for OpenAL startup and shutdown. */
  285. struct AudioManager {
  286. AudioManager(char ***argv_, int *argc_)
  287. {
  288. if(InitAL(argv_, argc_) != 0)
  289. throw std::runtime_error{"Failed to initialize OpenAL"};
  290. }
  291. ~AudioManager() { CloseAL(); }
  292. };
  293. /* Print out usage if no arguments were specified */
  294. if(argc < 2)
  295. {
  296. fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
  297. return 1;
  298. }
  299. argv++; argc--;
  300. AudioManager almgr{&argv, &argc};
  301. if(!alIsExtensionPresent("AL_SOFT_callback_buffer"))
  302. {
  303. fprintf(stderr, "AL_SOFT_callback_buffer extension not available\n");
  304. return 1;
  305. }
  306. alBufferCallbackSOFT = reinterpret_cast<LPALBUFFERCALLBACKSOFT>(
  307. alGetProcAddress("alBufferCallbackSOFT"));
  308. ALCint refresh{25};
  309. alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh);
  310. std::unique_ptr<StreamPlayer> player{new StreamPlayer{}};
  311. /* Play each file listed on the command line */
  312. for(int i{0};i < argc;++i)
  313. {
  314. if(!player->open(argv[i]))
  315. continue;
  316. /* Get the name portion, without the path, for display. */
  317. const char *namepart{strrchr(argv[i], '/')};
  318. if(namepart || (namepart=strrchr(argv[i], '\\')))
  319. ++namepart;
  320. else
  321. namepart = argv[i];
  322. printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->mFormat),
  323. player->mSfInfo.samplerate);
  324. fflush(stdout);
  325. if(!player->prepare())
  326. {
  327. player->close();
  328. continue;
  329. }
  330. while(player->update())
  331. std::this_thread::sleep_for(nanoseconds{seconds{1}} / refresh);
  332. putc('\n', stdout);
  333. /* All done with this file. Close it and go to the next */
  334. player->close();
  335. }
  336. /* All done. */
  337. printf("Done.\n");
  338. return 0;
  339. }