alplay.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /*
  2. * OpenAL Source Play Example
  3. *
  4. * Copyright (c) 2017 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 an example for playing a sound buffer. */
  25. #include <assert.h>
  26. #include <inttypes.h>
  27. #include <limits.h>
  28. #include <stdio.h>
  29. #include <stdlib.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. enum FormatType {
  36. Int16,
  37. Float,
  38. IMA4,
  39. MSADPCM
  40. };
  41. /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
  42. * returns the new buffer ID.
  43. */
  44. static ALuint LoadSound(const char *filename)
  45. {
  46. enum FormatType sample_format = Int16;
  47. ALint byteblockalign = 0;
  48. ALint splblockalign = 0;
  49. sf_count_t num_frames;
  50. ALenum err, format;
  51. ALsizei num_bytes;
  52. SNDFILE *sndfile;
  53. SF_INFO sfinfo;
  54. ALuint buffer;
  55. void *membuf;
  56. /* Open the audio file and check that it's usable. */
  57. sndfile = sf_open(filename, SFM_READ, &sfinfo);
  58. if(!sndfile)
  59. {
  60. fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
  61. return 0;
  62. }
  63. if(sfinfo.frames < 1)
  64. {
  65. fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
  66. sf_close(sndfile);
  67. return 0;
  68. }
  69. /* Detect a suitable format to load. Formats like Vorbis and Opus use float
  70. * natively, so load as float to avoid clipping when possible. Formats
  71. * larger than 16-bit can also use float to preserve a bit more precision.
  72. */
  73. switch((sfinfo.format&SF_FORMAT_SUBMASK))
  74. {
  75. case SF_FORMAT_PCM_24:
  76. case SF_FORMAT_PCM_32:
  77. case SF_FORMAT_FLOAT:
  78. case SF_FORMAT_DOUBLE:
  79. case SF_FORMAT_VORBIS:
  80. case SF_FORMAT_OPUS:
  81. case SF_FORMAT_ALAC_20:
  82. case SF_FORMAT_ALAC_24:
  83. case SF_FORMAT_ALAC_32:
  84. case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
  85. case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
  86. case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
  87. if(alIsExtensionPresent("AL_EXT_FLOAT32"))
  88. sample_format = Float;
  89. break;
  90. case SF_FORMAT_IMA_ADPCM:
  91. /* ADPCM formats require setting a block alignment as specified in the
  92. * file, which needs to be read from the wave 'fmt ' chunk manually
  93. * since libsndfile doesn't provide it in a format-agnostic way.
  94. */
  95. if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
  96. && alIsExtensionPresent("AL_EXT_IMA4")
  97. && alIsExtensionPresent("AL_SOFT_block_alignment"))
  98. sample_format = IMA4;
  99. break;
  100. case SF_FORMAT_MS_ADPCM:
  101. if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
  102. && alIsExtensionPresent("AL_SOFT_MSADPCM")
  103. && alIsExtensionPresent("AL_SOFT_block_alignment"))
  104. sample_format = MSADPCM;
  105. break;
  106. }
  107. if(sample_format == IMA4 || sample_format == MSADPCM)
  108. {
  109. /* For ADPCM, lookup the wave file's "fmt " chunk, which is a
  110. * WAVEFORMATEX-based structure for the audio format.
  111. */
  112. SF_CHUNK_INFO inf = { "fmt ", 4, 0, NULL };
  113. SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(sndfile, &inf);
  114. /* If there's an issue getting the chunk or block alignment, load as
  115. * 16-bit and have libsndfile do the conversion.
  116. */
  117. if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
  118. sample_format = Int16;
  119. else
  120. {
  121. ALubyte *fmtbuf = calloc(inf.datalen, 1);
  122. inf.data = fmtbuf;
  123. if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
  124. sample_format = Int16;
  125. else
  126. {
  127. /* Read the nBlockAlign field, and convert from bytes- to
  128. * samples-per-block (verifying it's valid by converting back
  129. * and comparing to the original value).
  130. */
  131. byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
  132. if(sample_format == IMA4)
  133. {
  134. splblockalign = (byteblockalign/sfinfo.channels - 4)/4*8 + 1;
  135. if(splblockalign < 1
  136. || ((splblockalign-1)/2 + 4)*sfinfo.channels != byteblockalign)
  137. sample_format = Int16;
  138. }
  139. else
  140. {
  141. splblockalign = (byteblockalign/sfinfo.channels - 7)*2 + 2;
  142. if(splblockalign < 2
  143. || ((splblockalign-2)/2 + 7)*sfinfo.channels != byteblockalign)
  144. sample_format = Int16;
  145. }
  146. }
  147. free(fmtbuf);
  148. }
  149. }
  150. if(sample_format == Int16)
  151. {
  152. splblockalign = 1;
  153. byteblockalign = sfinfo.channels * 2;
  154. }
  155. else if(sample_format == Float)
  156. {
  157. splblockalign = 1;
  158. byteblockalign = sfinfo.channels * 4;
  159. }
  160. /* Figure out the OpenAL format from the file and desired sample type. */
  161. format = AL_NONE;
  162. if(sfinfo.channels == 1)
  163. {
  164. if(sample_format == Int16)
  165. format = AL_FORMAT_MONO16;
  166. else if(sample_format == Float)
  167. format = AL_FORMAT_MONO_FLOAT32;
  168. else if(sample_format == IMA4)
  169. format = AL_FORMAT_MONO_IMA4;
  170. else if(sample_format == MSADPCM)
  171. format = AL_FORMAT_MONO_MSADPCM_SOFT;
  172. }
  173. else if(sfinfo.channels == 2)
  174. {
  175. if(sample_format == Int16)
  176. format = AL_FORMAT_STEREO16;
  177. else if(sample_format == Float)
  178. format = AL_FORMAT_STEREO_FLOAT32;
  179. else if(sample_format == IMA4)
  180. format = AL_FORMAT_STEREO_IMA4;
  181. else if(sample_format == MSADPCM)
  182. format = AL_FORMAT_STEREO_MSADPCM_SOFT;
  183. }
  184. else if(sfinfo.channels == 3)
  185. {
  186. if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  187. {
  188. if(sample_format == Int16)
  189. format = AL_FORMAT_BFORMAT2D_16;
  190. else if(sample_format == Float)
  191. format = AL_FORMAT_BFORMAT2D_FLOAT32;
  192. }
  193. }
  194. else if(sfinfo.channels == 4)
  195. {
  196. if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
  197. {
  198. if(sample_format == Int16)
  199. format = AL_FORMAT_BFORMAT3D_16;
  200. else if(sample_format == Float)
  201. format = AL_FORMAT_BFORMAT3D_FLOAT32;
  202. }
  203. }
  204. if(!format)
  205. {
  206. fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
  207. sf_close(sndfile);
  208. return 0;
  209. }
  210. if(sfinfo.frames/splblockalign > (sf_count_t)(INT_MAX/byteblockalign))
  211. {
  212. fprintf(stderr, "Too many samples in %s (%" PRId64 ")\n", filename, sfinfo.frames);
  213. sf_close(sndfile);
  214. return 0;
  215. }
  216. /* Decode the whole audio file to a buffer. */
  217. membuf = malloc((size_t)(sfinfo.frames / splblockalign * byteblockalign));
  218. if(sample_format == Int16)
  219. num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
  220. else if(sample_format == Float)
  221. num_frames = sf_readf_float(sndfile, membuf, sfinfo.frames);
  222. else
  223. {
  224. sf_count_t count = sfinfo.frames / splblockalign * byteblockalign;
  225. num_frames = sf_read_raw(sndfile, membuf, count);
  226. if(num_frames > 0)
  227. num_frames = num_frames / byteblockalign * splblockalign;
  228. }
  229. if(num_frames < 1)
  230. {
  231. free(membuf);
  232. sf_close(sndfile);
  233. fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
  234. return 0;
  235. }
  236. num_bytes = (ALsizei)(num_frames / splblockalign * byteblockalign);
  237. printf("Loading: %s (%s, %dhz)\n", filename, FormatName(format), sfinfo.samplerate);
  238. fflush(stdout);
  239. /* Buffer the audio data into a new buffer object, then free the data and
  240. * close the file.
  241. */
  242. buffer = 0;
  243. alGenBuffers(1, &buffer);
  244. if(splblockalign > 1)
  245. alBufferi(buffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, splblockalign);
  246. alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
  247. free(membuf);
  248. sf_close(sndfile);
  249. /* Check if an error occurred, and clean up if so. */
  250. err = alGetError();
  251. if(err != AL_NO_ERROR)
  252. {
  253. fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
  254. if(buffer && alIsBuffer(buffer))
  255. alDeleteBuffers(1, &buffer);
  256. return 0;
  257. }
  258. return buffer;
  259. }
  260. int main(int argc, char **argv)
  261. {
  262. ALuint source, buffer;
  263. ALfloat offset;
  264. ALenum state;
  265. /* Print out usage if no arguments were specified */
  266. if(argc < 2)
  267. {
  268. fprintf(stderr, "Usage: %s [-device <name>] <filename>\n", argv[0]);
  269. return 1;
  270. }
  271. /* Initialize OpenAL. */
  272. argv++; argc--;
  273. if(InitAL(&argv, &argc) != 0)
  274. return 1;
  275. /* Load the sound into a buffer. */
  276. buffer = LoadSound(argv[0]);
  277. if(!buffer)
  278. {
  279. CloseAL();
  280. return 1;
  281. }
  282. /* Create the source to play the sound with. */
  283. source = 0;
  284. alGenSources(1, &source);
  285. alSourcei(source, AL_BUFFER, (ALint)buffer);
  286. assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
  287. /* Play the sound until it finishes. */
  288. alSourcePlay(source);
  289. do {
  290. al_nssleep(10000000);
  291. alGetSourcei(source, AL_SOURCE_STATE, &state);
  292. /* Get the source offset. */
  293. alGetSourcef(source, AL_SEC_OFFSET, &offset);
  294. printf("\rOffset: %f ", offset);
  295. fflush(stdout);
  296. } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
  297. printf("\n");
  298. /* All done. Delete resources, and close down OpenAL. */
  299. alDeleteSources(1, &source);
  300. alDeleteBuffers(1, &buffer);
  301. CloseAL();
  302. return 0;
  303. }