alstreamcb.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. 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. size_t mSamplesPerBlock{1};
  53. size_t mBytesPerBlock{1};
  54. enum class SampleType {
  55. Int16, Float, IMA4, MSADPCM
  56. };
  57. SampleType mSampleFormat{SampleType::Int16};
  58. /* The buffer to get the callback, and source to play with. */
  59. ALuint mBuffer{0}, mSource{0};
  60. size_t mStartOffset{0};
  61. /* Handle for the audio file to decode. */
  62. SNDFILE *mSndfile{nullptr};
  63. SF_INFO mSfInfo{};
  64. size_t mDecoderOffset{0};
  65. /* The format of the callback samples. */
  66. ALenum mFormat;
  67. StreamPlayer()
  68. {
  69. alGenBuffers(1, &mBuffer);
  70. if(alGetError() != AL_NO_ERROR)
  71. throw std::runtime_error{"alGenBuffers failed"};
  72. alGenSources(1, &mSource);
  73. if(alGetError() != AL_NO_ERROR)
  74. {
  75. alDeleteBuffers(1, &mBuffer);
  76. throw std::runtime_error{"alGenSources failed"};
  77. }
  78. }
  79. ~StreamPlayer()
  80. {
  81. alDeleteSources(1, &mSource);
  82. alDeleteBuffers(1, &mBuffer);
  83. if(mSndfile)
  84. sf_close(mSndfile);
  85. }
  86. void close()
  87. {
  88. if(mSamplesPerBlock > 1)
  89. alBufferi(mBuffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, 0);
  90. if(mSndfile)
  91. {
  92. alSourceRewind(mSource);
  93. alSourcei(mSource, AL_BUFFER, 0);
  94. sf_close(mSndfile);
  95. mSndfile = nullptr;
  96. }
  97. }
  98. bool open(const char *filename)
  99. {
  100. close();
  101. /* Open the file and figure out the OpenAL format. */
  102. mSndfile = sf_open(filename, SFM_READ, &mSfInfo);
  103. if(!mSndfile)
  104. {
  105. fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(mSndfile));
  106. return false;
  107. }
  108. switch((mSfInfo.format&SF_FORMAT_SUBMASK))
  109. {
  110. case SF_FORMAT_PCM_24:
  111. case SF_FORMAT_PCM_32:
  112. case SF_FORMAT_FLOAT:
  113. case SF_FORMAT_DOUBLE:
  114. case SF_FORMAT_VORBIS:
  115. case SF_FORMAT_OPUS:
  116. case SF_FORMAT_ALAC_20:
  117. case SF_FORMAT_ALAC_24:
  118. case SF_FORMAT_ALAC_32:
  119. case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
  120. case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
  121. case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
  122. if(alIsExtensionPresent("AL_EXT_FLOAT32"))
  123. mSampleFormat = SampleType::Float;
  124. break;
  125. case SF_FORMAT_IMA_ADPCM:
  126. if(mSfInfo.channels <= 2 && (mSfInfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
  127. && alIsExtensionPresent("AL_EXT_IMA4")
  128. && alIsExtensionPresent("AL_SOFT_block_alignment"))
  129. mSampleFormat = SampleType::IMA4;
  130. break;
  131. case SF_FORMAT_MS_ADPCM:
  132. if(mSfInfo.channels <= 2 && (mSfInfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
  133. && alIsExtensionPresent("AL_SOFT_MSADPCM")
  134. && alIsExtensionPresent("AL_SOFT_block_alignment"))
  135. mSampleFormat = SampleType::MSADPCM;
  136. break;
  137. }
  138. int splblocksize{}, byteblocksize{};
  139. if(mSampleFormat == SampleType::IMA4 || mSampleFormat == SampleType::MSADPCM)
  140. {
  141. SF_CHUNK_INFO inf{ "fmt ", 4, 0, nullptr };
  142. SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(mSndfile, &inf);
  143. if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
  144. mSampleFormat = SampleType::Int16;
  145. else
  146. {
  147. auto fmtbuf = std::make_unique<ALubyte[]>(inf.datalen);
  148. inf.data = fmtbuf.get();
  149. if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
  150. mSampleFormat = SampleType::Int16;
  151. else
  152. {
  153. byteblocksize = fmtbuf[12] | (fmtbuf[13]<<8u);
  154. if(mSampleFormat == SampleType::IMA4)
  155. {
  156. splblocksize = (byteblocksize/mSfInfo.channels - 4)/4*8 + 1;
  157. if(splblocksize < 1
  158. || ((splblocksize-1)/2 + 4)*mSfInfo.channels != byteblocksize)
  159. mSampleFormat = SampleType::Int16;
  160. }
  161. else
  162. {
  163. splblocksize = (byteblocksize/mSfInfo.channels - 7)*2 + 2;
  164. if(splblocksize < 2
  165. || ((splblocksize-2)/2 + 7)*mSfInfo.channels != byteblocksize)
  166. mSampleFormat = SampleType::Int16;
  167. }
  168. }
  169. }
  170. }
  171. if(mSampleFormat == SampleType::Int16)
  172. {
  173. mSamplesPerBlock = 1;
  174. mBytesPerBlock = static_cast<size_t>(mSfInfo.channels * 2);
  175. }
  176. else if(mSampleFormat == SampleType::Float)
  177. {
  178. mSamplesPerBlock = 1;
  179. mBytesPerBlock = static_cast<size_t>(mSfInfo.channels * 4);
  180. }
  181. else
  182. {
  183. mSamplesPerBlock = static_cast<size_t>(splblocksize);
  184. mBytesPerBlock = static_cast<size_t>(byteblocksize);
  185. }
  186. mFormat = AL_NONE;
  187. if(mSfInfo.channels == 1)
  188. {
  189. if(mSampleFormat == SampleType::Int16)
  190. mFormat = AL_FORMAT_MONO16;
  191. else if(mSampleFormat == SampleType::Float)
  192. mFormat = AL_FORMAT_MONO_FLOAT32;
  193. else if(mSampleFormat == SampleType::IMA4)
  194. mFormat = AL_FORMAT_MONO_IMA4;
  195. else if(mSampleFormat == SampleType::MSADPCM)
  196. mFormat = AL_FORMAT_MONO_MSADPCM_SOFT;
  197. }
  198. else if(mSfInfo.channels == 2)
  199. {
  200. if(mSampleFormat == SampleType::Int16)
  201. mFormat = AL_FORMAT_STEREO16;
  202. else if(mSampleFormat == SampleType::Float)
  203. mFormat = AL_FORMAT_STEREO_FLOAT32;
  204. else if(mSampleFormat == SampleType::IMA4)
  205. mFormat = AL_FORMAT_STEREO_IMA4;
  206. else if(mSampleFormat == SampleType::MSADPCM)
  207. mFormat = AL_FORMAT_STEREO_MSADPCM_SOFT;
  208. }
  209. else if(mSfInfo.channels == 3)
  210. {
  211. if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  212. {
  213. if(mSampleFormat == SampleType::Int16)
  214. mFormat = AL_FORMAT_BFORMAT2D_16;
  215. else if(mSampleFormat == SampleType::Float)
  216. mFormat = AL_FORMAT_BFORMAT2D_FLOAT32;
  217. }
  218. }
  219. else if(mSfInfo.channels == 4)
  220. {
  221. if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  222. {
  223. if(mSampleFormat == SampleType::Int16)
  224. mFormat = AL_FORMAT_BFORMAT3D_16;
  225. else if(mSampleFormat == SampleType::Float)
  226. mFormat = AL_FORMAT_BFORMAT3D_FLOAT32;
  227. }
  228. }
  229. if(!mFormat)
  230. {
  231. fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
  232. sf_close(mSndfile);
  233. mSndfile = nullptr;
  234. return false;
  235. }
  236. /* Set a 1s ring buffer size. */
  237. size_t numblocks{(static_cast<ALuint>(mSfInfo.samplerate) + mSamplesPerBlock-1)
  238. / mSamplesPerBlock};
  239. mBufferDataSize = static_cast<ALuint>(numblocks * mBytesPerBlock);
  240. mBufferData.reset(new ALbyte[mBufferDataSize]);
  241. mReadPos.store(0, std::memory_order_relaxed);
  242. mWritePos.store(0, std::memory_order_relaxed);
  243. mDecoderOffset = 0;
  244. return true;
  245. }
  246. /* The actual C-style callback just forwards to the non-static method. Not
  247. * strictly needed and the compiler will optimize it to a normal function,
  248. * but it allows the callback implementation to have a nice 'this' pointer
  249. * with normal member access.
  250. */
  251. static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size)
  252. { return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
  253. ALsizei bufferCallback(void *data, ALsizei size)
  254. {
  255. /* NOTE: The callback *MUST* be real-time safe! That means no blocking,
  256. * no allocations or deallocations, no I/O, no page faults, or calls to
  257. * functions that could do these things (this includes calling to
  258. * libraries like SDL_sound, libsndfile, ffmpeg, etc). Nothing should
  259. * unexpectedly stall this call since the audio has to get to the
  260. * device on time.
  261. */
  262. ALsizei got{0};
  263. size_t roffset{mReadPos.load(std::memory_order_acquire)};
  264. while(got < size)
  265. {
  266. /* If the write offset == read offset, there's nothing left in the
  267. * ring-buffer. Break from the loop and give what has been written.
  268. */
  269. const size_t woffset{mWritePos.load(std::memory_order_relaxed)};
  270. if(woffset == roffset) break;
  271. /* If the write offset is behind the read offset, the readable
  272. * portion wrapped around. Just read up to the end of the buffer in
  273. * that case, otherwise read up to the write offset. Also limit the
  274. * amount to copy given how much is remaining to write.
  275. */
  276. size_t todo{((woffset < roffset) ? mBufferDataSize : woffset) - roffset};
  277. todo = std::min<size_t>(todo, static_cast<ALuint>(size-got));
  278. /* Copy from the ring buffer to the provided output buffer. Wrap
  279. * the resulting read offset if it reached the end of the ring-
  280. * buffer.
  281. */
  282. memcpy(data, &mBufferData[roffset], todo);
  283. data = static_cast<ALbyte*>(data) + todo;
  284. got += static_cast<ALsizei>(todo);
  285. roffset += todo;
  286. if(roffset == mBufferDataSize)
  287. roffset = 0;
  288. }
  289. /* Finally, store the updated read offset, and return how many bytes
  290. * have been written.
  291. */
  292. mReadPos.store(roffset, std::memory_order_release);
  293. return got;
  294. }
  295. bool prepare()
  296. {
  297. if(mSamplesPerBlock > 1)
  298. alBufferi(mBuffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, static_cast<int>(mSamplesPerBlock));
  299. alBufferCallbackSOFT(mBuffer, mFormat, mSfInfo.samplerate, bufferCallbackC, this);
  300. alSourcei(mSource, AL_BUFFER, static_cast<ALint>(mBuffer));
  301. if(ALenum err{alGetError()})
  302. {
  303. fprintf(stderr, "Failed to set callback: %s (0x%04x)\n", alGetString(err), err);
  304. return false;
  305. }
  306. return true;
  307. }
  308. bool update()
  309. {
  310. ALenum state;
  311. ALint pos;
  312. alGetSourcei(mSource, AL_SAMPLE_OFFSET, &pos);
  313. alGetSourcei(mSource, AL_SOURCE_STATE, &state);
  314. size_t woffset{mWritePos.load(std::memory_order_acquire)};
  315. if(state != AL_INITIAL)
  316. {
  317. const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
  318. const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
  319. roffset};
  320. /* For a stopped (underrun) source, the current playback offset is
  321. * the current decoder offset excluding the readable buffered data.
  322. * For a playing/paused source, it's the source's offset including
  323. * the playback offset the source was started with.
  324. */
  325. const size_t curtime{((state == AL_STOPPED)
  326. ? (mDecoderOffset-readable) / mBytesPerBlock * mSamplesPerBlock
  327. : (static_cast<ALuint>(pos) + mStartOffset/mBytesPerBlock*mSamplesPerBlock))
  328. / static_cast<ALuint>(mSfInfo.samplerate)};
  329. printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferDataSize);
  330. }
  331. else
  332. fputs("Starting...", stdout);
  333. fflush(stdout);
  334. while(!sf_error(mSndfile))
  335. {
  336. size_t read_bytes;
  337. const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
  338. if(roffset > woffset)
  339. {
  340. /* Note that the ring buffer's writable space is one byte less
  341. * than the available area because the write offset ending up
  342. * at the read offset would be interpreted as being empty
  343. * instead of full.
  344. */
  345. const size_t writable{(roffset-woffset-1) / mBytesPerBlock};
  346. if(!writable) break;
  347. if(mSampleFormat == SampleType::Int16)
  348. {
  349. sf_count_t num_frames{sf_readf_short(mSndfile,
  350. reinterpret_cast<short*>(&mBufferData[woffset]),
  351. static_cast<sf_count_t>(writable*mSamplesPerBlock))};
  352. if(num_frames < 1) break;
  353. read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
  354. }
  355. else if(mSampleFormat == SampleType::Float)
  356. {
  357. sf_count_t num_frames{sf_readf_float(mSndfile,
  358. reinterpret_cast<float*>(&mBufferData[woffset]),
  359. static_cast<sf_count_t>(writable*mSamplesPerBlock))};
  360. if(num_frames < 1) break;
  361. read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
  362. }
  363. else
  364. {
  365. sf_count_t numbytes{sf_read_raw(mSndfile, &mBufferData[woffset],
  366. static_cast<sf_count_t>(writable*mBytesPerBlock))};
  367. if(numbytes < 1) break;
  368. read_bytes = static_cast<size_t>(numbytes);
  369. }
  370. woffset += read_bytes;
  371. }
  372. else
  373. {
  374. /* If the read offset is at or behind the write offset, the
  375. * writeable area (might) wrap around. Make sure the sample
  376. * data can fit, and calculate how much can go in front before
  377. * wrapping.
  378. */
  379. const size_t writable{(!roffset ? mBufferDataSize-woffset-1 :
  380. (mBufferDataSize-woffset)) / mBytesPerBlock};
  381. if(!writable) break;
  382. if(mSampleFormat == SampleType::Int16)
  383. {
  384. sf_count_t num_frames{sf_readf_short(mSndfile,
  385. reinterpret_cast<short*>(&mBufferData[woffset]),
  386. static_cast<sf_count_t>(writable*mSamplesPerBlock))};
  387. if(num_frames < 1) break;
  388. read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
  389. }
  390. else if(mSampleFormat == SampleType::Float)
  391. {
  392. sf_count_t num_frames{sf_readf_float(mSndfile,
  393. reinterpret_cast<float*>(&mBufferData[woffset]),
  394. static_cast<sf_count_t>(writable*mSamplesPerBlock))};
  395. if(num_frames < 1) break;
  396. read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
  397. }
  398. else
  399. {
  400. sf_count_t numbytes{sf_read_raw(mSndfile, &mBufferData[woffset],
  401. static_cast<sf_count_t>(writable*mBytesPerBlock))};
  402. if(numbytes < 1) break;
  403. read_bytes = static_cast<size_t>(numbytes);
  404. }
  405. woffset += read_bytes;
  406. if(woffset == mBufferDataSize)
  407. woffset = 0;
  408. }
  409. mWritePos.store(woffset, std::memory_order_release);
  410. mDecoderOffset += read_bytes;
  411. }
  412. if(state != AL_PLAYING && state != AL_PAUSED)
  413. {
  414. /* If the source is not playing or paused, it either underrun
  415. * (AL_STOPPED) or is just getting started (AL_INITIAL). If the
  416. * ring buffer is empty, it's done, otherwise play the source with
  417. * what's available.
  418. */
  419. const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
  420. const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
  421. roffset};
  422. if(readable == 0)
  423. return false;
  424. /* Store the playback offset that the source will start reading
  425. * from, so it can be tracked during playback.
  426. */
  427. mStartOffset = mDecoderOffset - readable;
  428. alSourcePlay(mSource);
  429. if(alGetError() != AL_NO_ERROR)
  430. return false;
  431. }
  432. return true;
  433. }
  434. };
  435. } // namespace
  436. int main(int argc, char **argv)
  437. {
  438. /* A simple RAII container for OpenAL startup and shutdown. */
  439. struct AudioManager {
  440. AudioManager(char ***argv_, int *argc_)
  441. {
  442. if(InitAL(argv_, argc_) != 0)
  443. throw std::runtime_error{"Failed to initialize OpenAL"};
  444. }
  445. ~AudioManager() { CloseAL(); }
  446. };
  447. /* Print out usage if no arguments were specified */
  448. if(argc < 2)
  449. {
  450. fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
  451. return 1;
  452. }
  453. argv++; argc--;
  454. AudioManager almgr{&argv, &argc};
  455. if(!alIsExtensionPresent("AL_SOFT_callback_buffer"))
  456. {
  457. fprintf(stderr, "AL_SOFT_callback_buffer extension not available\n");
  458. return 1;
  459. }
  460. alBufferCallbackSOFT = reinterpret_cast<LPALBUFFERCALLBACKSOFT>(
  461. alGetProcAddress("alBufferCallbackSOFT"));
  462. ALCint refresh{25};
  463. alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh);
  464. std::unique_ptr<StreamPlayer> player{new StreamPlayer{}};
  465. /* Play each file listed on the command line */
  466. for(int i{0};i < argc;++i)
  467. {
  468. if(!player->open(argv[i]))
  469. continue;
  470. /* Get the name portion, without the path, for display. */
  471. const char *namepart{strrchr(argv[i], '/')};
  472. if(namepart || (namepart=strrchr(argv[i], '\\')))
  473. ++namepart;
  474. else
  475. namepart = argv[i];
  476. printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->mFormat),
  477. player->mSfInfo.samplerate);
  478. fflush(stdout);
  479. if(!player->prepare())
  480. {
  481. player->close();
  482. continue;
  483. }
  484. while(player->update())
  485. std::this_thread::sleep_for(nanoseconds{seconds{1}} / refresh);
  486. putc('\n', stdout);
  487. /* All done with this file. Close it and go to the next */
  488. player->close();
  489. }
  490. /* All done. */
  491. printf("Done.\n");
  492. return 0;
  493. }