alstream.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /*
  2. * OpenAL Audio Stream Example
  3. *
  4. * Copyright (c) 2011 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 relatively simple streaming audio player. */
  25. #include <assert.h>
  26. #include <inttypes.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include "sndfile.h"
  31. #include "AL/al.h"
  32. #include "AL/alext.h"
  33. #include "common/alhelpers.h"
  34. #include "win_main_utf8.h"
  35. /* Define the number of buffers and buffer size (in milliseconds) to use. 4
  36. * buffers at 200ms each gives a nice per-chunk size, and lets the queue last
  37. * for almost one second.
  38. */
  39. enum { NumBuffers = 4 };
  40. enum { BufferMillisec = 200 };
  41. typedef enum SampleType {
  42. Int16, Float, IMA4, MSADPCM
  43. } SampleType;
  44. typedef struct StreamPlayer {
  45. /* These are the buffers and source to play out through OpenAL with. */
  46. ALuint buffers[NumBuffers];
  47. ALuint source;
  48. /* Handle for the audio file */
  49. SNDFILE *sndfile;
  50. SF_INFO sfinfo;
  51. void *membuf;
  52. /* The sample type and block/frame size being read for the buffer. */
  53. SampleType sample_type;
  54. int byteblockalign;
  55. int sampleblockalign;
  56. int block_count;
  57. /* The format of the output stream (sample rate is in sfinfo) */
  58. ALenum format;
  59. } StreamPlayer;
  60. static StreamPlayer *NewPlayer(void);
  61. static void DeletePlayer(StreamPlayer *player);
  62. static int OpenPlayerFile(StreamPlayer *player, const char *filename);
  63. static void ClosePlayerFile(StreamPlayer *player);
  64. static int StartPlayer(StreamPlayer *player);
  65. static int UpdatePlayer(StreamPlayer *player);
  66. /* Creates a new player object, and allocates the needed OpenAL source and
  67. * buffer objects. Error checking is simplified for the purposes of this
  68. * example, and will cause an abort if needed.
  69. */
  70. static StreamPlayer *NewPlayer(void)
  71. {
  72. StreamPlayer *player;
  73. player = calloc(1, sizeof(*player));
  74. assert(player != NULL);
  75. /* Generate the buffers and source */
  76. alGenBuffers(NumBuffers, player->buffers);
  77. assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
  78. alGenSources(1, &player->source);
  79. assert(alGetError() == AL_NO_ERROR && "Could not create source");
  80. /* Set parameters so mono sources play out the front-center speaker and
  81. * won't distance attenuate. */
  82. alSource3i(player->source, AL_POSITION, 0, 0, -1);
  83. alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE);
  84. alSourcei(player->source, AL_ROLLOFF_FACTOR, 0);
  85. assert(alGetError() == AL_NO_ERROR && "Could not set source parameters");
  86. return player;
  87. }
  88. /* Destroys a player object, deleting the source and buffers. No error handling
  89. * since these calls shouldn't fail with a properly-made player object. */
  90. static void DeletePlayer(StreamPlayer *player)
  91. {
  92. ClosePlayerFile(player);
  93. alDeleteSources(1, &player->source);
  94. alDeleteBuffers(NumBuffers, player->buffers);
  95. if(alGetError() != AL_NO_ERROR)
  96. fprintf(stderr, "Failed to delete object IDs\n");
  97. memset(player, 0, sizeof(*player)); /* NOLINT(clang-analyzer-security.insecureAPI.*) */
  98. free(player);
  99. }
  100. /* Opens the first audio stream of the named file. If a file is already open,
  101. * it will be closed first. */
  102. static int OpenPlayerFile(StreamPlayer *player, const char *filename)
  103. {
  104. int byteblockalign=0, splblockalign=0;
  105. ClosePlayerFile(player);
  106. /* Open the audio file and check that it's usable. */
  107. player->sndfile = sf_open(filename, SFM_READ, &player->sfinfo);
  108. if(!player->sndfile)
  109. {
  110. fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(NULL));
  111. return 0;
  112. }
  113. /* Detect a suitable format to load. Formats like Vorbis and Opus use float
  114. * natively, so load as float to avoid clipping when possible. Formats
  115. * larger than 16-bit can also use float to preserve a bit more precision.
  116. */
  117. switch((player->sfinfo.format&SF_FORMAT_SUBMASK))
  118. {
  119. case SF_FORMAT_PCM_24:
  120. case SF_FORMAT_PCM_32:
  121. case SF_FORMAT_FLOAT:
  122. case SF_FORMAT_DOUBLE:
  123. case SF_FORMAT_VORBIS:
  124. case SF_FORMAT_OPUS:
  125. case SF_FORMAT_ALAC_20:
  126. case SF_FORMAT_ALAC_24:
  127. case SF_FORMAT_ALAC_32:
  128. case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
  129. case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
  130. case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
  131. if(alIsExtensionPresent("AL_EXT_FLOAT32"))
  132. player->sample_type = Float;
  133. break;
  134. case SF_FORMAT_IMA_ADPCM:
  135. /* ADPCM formats require setting a block alignment as specified in the
  136. * file, which needs to be read from the wave 'fmt ' chunk manually
  137. * since libsndfile doesn't provide it in a format-agnostic way.
  138. */
  139. if(player->sfinfo.channels <= 2
  140. && (player->sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
  141. && alIsExtensionPresent("AL_EXT_IMA4")
  142. && alIsExtensionPresent("AL_SOFT_block_alignment"))
  143. player->sample_type = IMA4;
  144. break;
  145. case SF_FORMAT_MS_ADPCM:
  146. if(player->sfinfo.channels <= 2
  147. && (player->sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
  148. && alIsExtensionPresent("AL_SOFT_MSADPCM")
  149. && alIsExtensionPresent("AL_SOFT_block_alignment"))
  150. player->sample_type = MSADPCM;
  151. break;
  152. }
  153. if(player->sample_type == IMA4 || player->sample_type == MSADPCM)
  154. {
  155. /* For ADPCM, lookup the wave file's "fmt " chunk, which is a
  156. * WAVEFORMATEX-based structure for the audio format.
  157. */
  158. SF_CHUNK_INFO inf = { "fmt ", 4, 0, NULL };
  159. SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(player->sndfile, &inf);
  160. /* If there's an issue getting the chunk or block alignment, load as
  161. * 16-bit and have libsndfile do the conversion.
  162. */
  163. if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
  164. player->sample_type = Int16;
  165. else
  166. {
  167. ALubyte *fmtbuf = calloc(inf.datalen, 1);
  168. inf.data = fmtbuf;
  169. if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
  170. player->sample_type = Int16;
  171. else
  172. {
  173. /* Read the nBlockAlign field, and convert from bytes- to
  174. * samples-per-block (verifying it's valid by converting back
  175. * and comparing to the original value).
  176. */
  177. byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
  178. if(player->sample_type == IMA4)
  179. {
  180. splblockalign = (byteblockalign/player->sfinfo.channels - 4)/4*8 + 1;
  181. if(splblockalign < 1
  182. || ((splblockalign-1)/2 + 4)*player->sfinfo.channels != byteblockalign)
  183. player->sample_type = Int16;
  184. }
  185. else
  186. {
  187. splblockalign = (byteblockalign/player->sfinfo.channels - 7)*2 + 2;
  188. if(splblockalign < 2
  189. || ((splblockalign-2)/2 + 7)*player->sfinfo.channels != byteblockalign)
  190. player->sample_type = Int16;
  191. }
  192. }
  193. free(fmtbuf);
  194. }
  195. }
  196. if(player->sample_type == Int16)
  197. {
  198. player->sampleblockalign = 1;
  199. player->byteblockalign = player->sfinfo.channels * 2;
  200. }
  201. else if(player->sample_type == Float)
  202. {
  203. player->sampleblockalign = 1;
  204. player->byteblockalign = player->sfinfo.channels * 4;
  205. }
  206. else
  207. {
  208. player->sampleblockalign = splblockalign;
  209. player->byteblockalign = byteblockalign;
  210. }
  211. /* Figure out the OpenAL format from the file and desired sample type. */
  212. player->format = AL_NONE;
  213. if(player->sfinfo.channels == 1)
  214. {
  215. if(player->sample_type == Int16)
  216. player->format = AL_FORMAT_MONO16;
  217. else if(player->sample_type == Float)
  218. player->format = AL_FORMAT_MONO_FLOAT32;
  219. else if(player->sample_type == IMA4)
  220. player->format = AL_FORMAT_MONO_IMA4;
  221. else if(player->sample_type == MSADPCM)
  222. player->format = AL_FORMAT_MONO_MSADPCM_SOFT;
  223. }
  224. else if(player->sfinfo.channels == 2)
  225. {
  226. if(player->sample_type == Int16)
  227. player->format = AL_FORMAT_STEREO16;
  228. else if(player->sample_type == Float)
  229. player->format = AL_FORMAT_STEREO_FLOAT32;
  230. else if(player->sample_type == IMA4)
  231. player->format = AL_FORMAT_STEREO_IMA4;
  232. else if(player->sample_type == MSADPCM)
  233. player->format = AL_FORMAT_STEREO_MSADPCM_SOFT;
  234. }
  235. else if(player->sfinfo.channels == 3)
  236. {
  237. if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  238. {
  239. if(player->sample_type == Int16)
  240. player->format = AL_FORMAT_BFORMAT2D_16;
  241. else if(player->sample_type == Float)
  242. player->format = AL_FORMAT_BFORMAT2D_FLOAT32;
  243. }
  244. }
  245. else if(player->sfinfo.channels == 4)
  246. {
  247. if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  248. {
  249. if(player->sample_type == Int16)
  250. player->format = AL_FORMAT_BFORMAT3D_16;
  251. else if(player->sample_type == Float)
  252. player->format = AL_FORMAT_BFORMAT3D_FLOAT32;
  253. }
  254. }
  255. if(!player->format)
  256. {
  257. fprintf(stderr, "Unsupported channel count: %d\n", player->sfinfo.channels);
  258. sf_close(player->sndfile);
  259. player->sndfile = NULL;
  260. return 0;
  261. }
  262. player->block_count = player->sfinfo.samplerate / player->sampleblockalign;
  263. player->block_count = player->block_count * BufferMillisec / 1000;
  264. player->membuf = malloc((size_t)player->block_count * (size_t)player->byteblockalign);
  265. return 1;
  266. }
  267. /* Closes the audio file stream */
  268. static void ClosePlayerFile(StreamPlayer *player)
  269. {
  270. if(player->sndfile)
  271. sf_close(player->sndfile);
  272. player->sndfile = NULL;
  273. free(player->membuf);
  274. player->membuf = NULL;
  275. if(player->sampleblockalign > 1)
  276. {
  277. ALsizei i;
  278. for(i = 0;i < NumBuffers;i++)
  279. alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT, 0);
  280. player->sampleblockalign = 0;
  281. player->byteblockalign = 0;
  282. }
  283. }
  284. /* Prebuffers some audio from the file, and starts playing the source */
  285. static int StartPlayer(StreamPlayer *player)
  286. {
  287. ALsizei i;
  288. /* Rewind the source position and clear the buffer queue */
  289. alSourceRewind(player->source);
  290. alSourcei(player->source, AL_BUFFER, 0);
  291. /* Fill the buffer queue */
  292. for(i = 0;i < NumBuffers;i++)
  293. {
  294. sf_count_t slen;
  295. /* Get some data to give it to the buffer */
  296. if(player->sample_type == Int16)
  297. {
  298. slen = sf_readf_short(player->sndfile, player->membuf,
  299. (sf_count_t)player->block_count * player->sampleblockalign);
  300. if(slen < 1) break;
  301. slen *= player->byteblockalign;
  302. }
  303. else if(player->sample_type == Float)
  304. {
  305. slen = sf_readf_float(player->sndfile, player->membuf,
  306. (sf_count_t)player->block_count * player->sampleblockalign);
  307. if(slen < 1) break;
  308. slen *= player->byteblockalign;
  309. }
  310. else
  311. {
  312. slen = sf_read_raw(player->sndfile, player->membuf,
  313. (sf_count_t)player->block_count * player->byteblockalign);
  314. if(slen > 0) slen -= slen%player->byteblockalign;
  315. if(slen < 1) break;
  316. }
  317. if(player->sampleblockalign > 1)
  318. alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT,
  319. player->sampleblockalign);
  320. alBufferData(player->buffers[i], player->format, player->membuf, (ALsizei)slen,
  321. player->sfinfo.samplerate);
  322. }
  323. if(alGetError() != AL_NO_ERROR)
  324. {
  325. fprintf(stderr, "Error buffering for playback\n");
  326. return 0;
  327. }
  328. /* Now queue and start playback! */
  329. alSourceQueueBuffers(player->source, i, player->buffers);
  330. alSourcePlay(player->source);
  331. if(alGetError() != AL_NO_ERROR)
  332. {
  333. fprintf(stderr, "Error starting playback\n");
  334. return 0;
  335. }
  336. return 1;
  337. }
  338. static int UpdatePlayer(StreamPlayer *player)
  339. {
  340. ALint processed, state;
  341. /* Get relevant source info */
  342. alGetSourcei(player->source, AL_SOURCE_STATE, &state);
  343. alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed);
  344. if(alGetError() != AL_NO_ERROR)
  345. {
  346. fprintf(stderr, "Error checking source state\n");
  347. return 0;
  348. }
  349. /* Unqueue and handle each processed buffer */
  350. while(processed > 0)
  351. {
  352. ALuint bufid;
  353. sf_count_t slen;
  354. alSourceUnqueueBuffers(player->source, 1, &bufid);
  355. processed--;
  356. /* Read the next chunk of data, refill the buffer, and queue it
  357. * back on the source */
  358. if(player->sample_type == Int16)
  359. {
  360. slen = sf_readf_short(player->sndfile, player->membuf,
  361. (sf_count_t)player->block_count * player->sampleblockalign);
  362. if(slen > 0) slen *= player->byteblockalign;
  363. }
  364. else if(player->sample_type == Float)
  365. {
  366. slen = sf_readf_float(player->sndfile, player->membuf,
  367. (sf_count_t)player->block_count * player->sampleblockalign);
  368. if(slen > 0) slen *= player->byteblockalign;
  369. }
  370. else
  371. {
  372. slen = sf_read_raw(player->sndfile, player->membuf,
  373. (sf_count_t)player->block_count * player->byteblockalign);
  374. if(slen > 0) slen -= slen%player->byteblockalign;
  375. }
  376. if(slen > 0)
  377. {
  378. alBufferData(bufid, player->format, player->membuf, (ALsizei)slen,
  379. player->sfinfo.samplerate);
  380. alSourceQueueBuffers(player->source, 1, &bufid);
  381. }
  382. if(alGetError() != AL_NO_ERROR)
  383. {
  384. fprintf(stderr, "Error buffering data\n");
  385. return 0;
  386. }
  387. }
  388. /* Make sure the source hasn't underrun */
  389. if(state != AL_PLAYING && state != AL_PAUSED)
  390. {
  391. ALint queued;
  392. /* If no buffers are queued, playback is finished */
  393. alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
  394. if(queued == 0)
  395. return 0;
  396. alSourcePlay(player->source);
  397. if(alGetError() != AL_NO_ERROR)
  398. {
  399. fprintf(stderr, "Error restarting playback\n");
  400. return 0;
  401. }
  402. }
  403. return 1;
  404. }
  405. int main(int argc, char **argv)
  406. {
  407. StreamPlayer *player;
  408. int i;
  409. /* Print out usage if no arguments were specified */
  410. if(argc < 2)
  411. {
  412. fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
  413. return 1;
  414. }
  415. argv++; argc--;
  416. if(InitAL(&argv, &argc) != 0)
  417. return 1;
  418. player = NewPlayer();
  419. /* Play each file listed on the command line */
  420. for(i = 0;i < argc;i++)
  421. {
  422. const char *namepart;
  423. if(!OpenPlayerFile(player, argv[i]))
  424. continue;
  425. /* Get the name portion, without the path, for display. */
  426. namepart = strrchr(argv[i], '/');
  427. if(!namepart) namepart = strrchr(argv[i], '\\');
  428. if(!namepart) namepart = argv[i];
  429. else namepart++;
  430. printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
  431. player->sfinfo.samplerate);
  432. fflush(stdout);
  433. if(!StartPlayer(player))
  434. {
  435. ClosePlayerFile(player);
  436. continue;
  437. }
  438. while(UpdatePlayer(player))
  439. al_nssleep(10000000);
  440. /* All done with this file. Close it and go to the next */
  441. ClosePlayerFile(player);
  442. }
  443. printf("Done.\n");
  444. /* All files done. Delete the player, and close down OpenAL */
  445. DeletePlayer(player);
  446. player = NULL;
  447. CloseAL();
  448. return 0;
  449. }