sndfile-play.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. /*
  2. ** Copyright (C) 1999-2018 Erik de Castro Lopo <[email protected]>
  3. **
  4. ** All rights reserved.
  5. **
  6. ** Redistribution and use in source and binary forms, with or without
  7. ** modification, are permitted provided that the following conditions are
  8. ** met:
  9. **
  10. ** * Redistributions of source code must retain the above copyright
  11. ** notice, this list of conditions and the following disclaimer.
  12. ** * Redistributions in binary form must reproduce the above copyright
  13. ** notice, this list of conditions and the following disclaimer in
  14. ** the documentation and/or other materials provided with the
  15. ** distribution.
  16. ** * Neither the author nor the names of any contributors may be used
  17. ** to endorse or promote products derived from this software without
  18. ** specific prior written permission.
  19. **
  20. ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  22. ** TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. ** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  24. ** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  25. ** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. ** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  27. ** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  28. ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  29. ** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  30. ** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. #include "sfconfig.h"
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <errno.h>
  37. #if HAVE_UNISTD_H
  38. #include <unistd.h>
  39. #else
  40. #include "sf_unistd.h"
  41. #endif
  42. #include <sndfile.h>
  43. #include "common.h"
  44. #if HAVE_ALSA_ASOUNDLIB_H
  45. #define ALSA_PCM_NEW_HW_PARAMS_API
  46. #define ALSA_PCM_NEW_SW_PARAMS_API
  47. #include <alsa/asoundlib.h>
  48. #include <sys/time.h>
  49. #endif
  50. #if defined (__ANDROID__)
  51. #elif defined (__linux__) || defined (__FreeBSD_kernel__) || defined (__FreeBSD__) || defined (__riscos__)
  52. #include <fcntl.h>
  53. #include <sys/ioctl.h>
  54. #include <sys/soundcard.h>
  55. #elif HAVE_SNDIO_H
  56. #include <sndio.h>
  57. #elif (defined (sun) && defined (unix)) || defined(__NetBSD__)
  58. #include <fcntl.h>
  59. #include <sys/ioctl.h>
  60. #include <sys/audioio.h>
  61. #elif (OS_IS_WIN32 == 1)
  62. #include <windows.h>
  63. #include <mmsystem.h>
  64. #endif
  65. #define SIGNED_SIZEOF(x) ((int) sizeof (x))
  66. #define BUFFER_LEN (2048)
  67. /*------------------------------------------------------------------------------
  68. ** Linux/OSS functions for playing a sound.
  69. */
  70. #if HAVE_ALSA_ASOUNDLIB_H
  71. static snd_pcm_t * alsa_open (int channels, unsigned srate, int realtime) ;
  72. static int alsa_write_float (snd_pcm_t *alsa_dev, float *data, int frames, int channels) ;
  73. static void
  74. alsa_play (int argc, char *argv [])
  75. { static float buffer [BUFFER_LEN] ;
  76. SNDFILE *sndfile ;
  77. SF_INFO sfinfo ;
  78. snd_pcm_t * alsa_dev ;
  79. int k, readcount, subformat ;
  80. for (k = 1 ; k < argc ; k++)
  81. { memset (&sfinfo, 0, sizeof (sfinfo)) ;
  82. printf ("Playing %s\n", argv [k]) ;
  83. if (! (sndfile = sf_open (argv [k], SFM_READ, &sfinfo)))
  84. { puts (sf_strerror (NULL)) ;
  85. continue ;
  86. } ;
  87. if (sfinfo.channels < 1 || sfinfo.channels > 2)
  88. { printf ("Error : channels = %d.\n", sfinfo.channels) ;
  89. continue ;
  90. } ;
  91. if ((alsa_dev = alsa_open (sfinfo.channels, (unsigned) sfinfo.samplerate, SF_FALSE)) == NULL)
  92. continue ;
  93. subformat = sfinfo.format & SF_FORMAT_SUBMASK ;
  94. if (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE)
  95. { double scale ;
  96. int m ;
  97. sf_command (sndfile, SFC_CALC_SIGNAL_MAX, &scale, sizeof (scale)) ;
  98. if (scale > 1.0)
  99. scale = 1.0 / scale ;
  100. else
  101. scale = 1.0 ;
  102. while ((readcount = sf_read_float (sndfile, buffer, BUFFER_LEN)))
  103. { for (m = 0 ; m < readcount ; m++)
  104. buffer [m] *= scale ;
  105. alsa_write_float (alsa_dev, buffer, BUFFER_LEN / sfinfo.channels, sfinfo.channels) ;
  106. } ;
  107. }
  108. else
  109. { while ((readcount = sf_read_float (sndfile, buffer, BUFFER_LEN)))
  110. alsa_write_float (alsa_dev, buffer, BUFFER_LEN / sfinfo.channels, sfinfo.channels) ;
  111. } ;
  112. snd_pcm_drain (alsa_dev) ;
  113. snd_pcm_close (alsa_dev) ;
  114. sf_close (sndfile) ;
  115. } ;
  116. return ;
  117. } /* alsa_play */
  118. static snd_pcm_t *
  119. alsa_open (int channels, unsigned samplerate, int realtime)
  120. { const char * device = "default" ;
  121. snd_pcm_t *alsa_dev = NULL ;
  122. snd_pcm_hw_params_t *hw_params ;
  123. snd_pcm_uframes_t buffer_size ;
  124. snd_pcm_uframes_t alsa_period_size, alsa_buffer_frames ;
  125. snd_pcm_sw_params_t *sw_params ;
  126. int err ;
  127. if (realtime)
  128. { alsa_period_size = 256 ;
  129. alsa_buffer_frames = 3 * alsa_period_size ;
  130. }
  131. else
  132. { alsa_period_size = 1024 ;
  133. alsa_buffer_frames = 4 * alsa_period_size ;
  134. } ;
  135. if ((err = snd_pcm_open (&alsa_dev, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0)
  136. { fprintf (stderr, "cannot open audio device \"%s\" (%s)\n", device, snd_strerror (err)) ;
  137. goto catch_error ;
  138. } ;
  139. snd_pcm_nonblock (alsa_dev, 0) ;
  140. if ((err = snd_pcm_hw_params_malloc (&hw_params)) < 0)
  141. { fprintf (stderr, "cannot allocate hardware parameter structure (%s)\n", snd_strerror (err)) ;
  142. goto catch_error ;
  143. } ;
  144. if ((err = snd_pcm_hw_params_any (alsa_dev, hw_params)) < 0)
  145. { fprintf (stderr, "cannot initialize hardware parameter structure (%s)\n", snd_strerror (err)) ;
  146. goto catch_error ;
  147. } ;
  148. if ((err = snd_pcm_hw_params_set_access (alsa_dev, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
  149. { fprintf (stderr, "cannot set access type (%s)\n", snd_strerror (err)) ;
  150. goto catch_error ;
  151. } ;
  152. if ((err = snd_pcm_hw_params_set_format (alsa_dev, hw_params, SND_PCM_FORMAT_FLOAT)) < 0)
  153. { fprintf (stderr, "cannot set sample format (%s)\n", snd_strerror (err)) ;
  154. goto catch_error ;
  155. } ;
  156. if ((err = snd_pcm_hw_params_set_rate_near (alsa_dev, hw_params, &samplerate, 0)) < 0)
  157. { fprintf (stderr, "cannot set sample rate (%s)\n", snd_strerror (err)) ;
  158. goto catch_error ;
  159. } ;
  160. if ((err = snd_pcm_hw_params_set_channels (alsa_dev, hw_params, channels)) < 0)
  161. { fprintf (stderr, "cannot set channel count (%s)\n", snd_strerror (err)) ;
  162. goto catch_error ;
  163. } ;
  164. if ((err = snd_pcm_hw_params_set_buffer_size_near (alsa_dev, hw_params, &alsa_buffer_frames)) < 0)
  165. { fprintf (stderr, "cannot set buffer size (%s)\n", snd_strerror (err)) ;
  166. goto catch_error ;
  167. } ;
  168. if ((err = snd_pcm_hw_params_set_period_size_near (alsa_dev, hw_params, &alsa_period_size, 0)) < 0)
  169. { fprintf (stderr, "cannot set period size (%s)\n", snd_strerror (err)) ;
  170. goto catch_error ;
  171. } ;
  172. if ((err = snd_pcm_hw_params (alsa_dev, hw_params)) < 0)
  173. { fprintf (stderr, "cannot set parameters (%s)\n", snd_strerror (err)) ;
  174. goto catch_error ;
  175. } ;
  176. /* extra check: if we have only one period, this code won't work */
  177. snd_pcm_hw_params_get_period_size (hw_params, &alsa_period_size, 0) ;
  178. snd_pcm_hw_params_get_buffer_size (hw_params, &buffer_size) ;
  179. if (alsa_period_size == buffer_size)
  180. { fprintf (stderr, "Can't use period equal to buffer size (%lu == %lu)", alsa_period_size, buffer_size) ;
  181. goto catch_error ;
  182. } ;
  183. snd_pcm_hw_params_free (hw_params) ;
  184. if ((err = snd_pcm_sw_params_malloc (&sw_params)) != 0)
  185. { fprintf (stderr, "%s: snd_pcm_sw_params_malloc: %s", __func__, snd_strerror (err)) ;
  186. goto catch_error ;
  187. } ;
  188. if ((err = snd_pcm_sw_params_current (alsa_dev, sw_params)) != 0)
  189. { fprintf (stderr, "%s: snd_pcm_sw_params_current: %s", __func__, snd_strerror (err)) ;
  190. goto catch_error ;
  191. } ;
  192. /* note: set start threshold to delay start until the ring buffer is full */
  193. snd_pcm_sw_params_current (alsa_dev, sw_params) ;
  194. if ((err = snd_pcm_sw_params_set_start_threshold (alsa_dev, sw_params, buffer_size)) < 0)
  195. { fprintf (stderr, "cannot set start threshold (%s)\n", snd_strerror (err)) ;
  196. goto catch_error ;
  197. } ;
  198. if ((err = snd_pcm_sw_params (alsa_dev, sw_params)) != 0)
  199. { fprintf (stderr, "%s: snd_pcm_sw_params: %s", __func__, snd_strerror (err)) ;
  200. goto catch_error ;
  201. } ;
  202. snd_pcm_sw_params_free (sw_params) ;
  203. snd_pcm_reset (alsa_dev) ;
  204. catch_error :
  205. if (err < 0 && alsa_dev != NULL)
  206. { snd_pcm_close (alsa_dev) ;
  207. return NULL ;
  208. } ;
  209. return alsa_dev ;
  210. } /* alsa_open */
  211. static int
  212. alsa_write_float (snd_pcm_t *alsa_dev, float *data, int frames, int channels)
  213. { static int epipe_count = 0 ;
  214. int total = 0 ;
  215. int retval ;
  216. if (epipe_count > 0)
  217. epipe_count -- ;
  218. while (total < frames)
  219. { retval = snd_pcm_writei (alsa_dev, data + total * channels, frames - total) ;
  220. if (retval >= 0)
  221. { total += retval ;
  222. if (total == frames)
  223. return total ;
  224. continue ;
  225. } ;
  226. switch (retval)
  227. { case -EAGAIN :
  228. puts ("alsa_write_float: EAGAIN") ;
  229. continue ;
  230. break ;
  231. case -EPIPE :
  232. if (epipe_count > 0)
  233. { printf ("alsa_write_float: EPIPE %d\n", epipe_count) ;
  234. if (epipe_count > 140)
  235. return retval ;
  236. } ;
  237. epipe_count += 100 ;
  238. #if 0
  239. if (0)
  240. { snd_pcm_status_t *status ;
  241. snd_pcm_status_alloca (&status) ;
  242. if ((retval = snd_pcm_status (alsa_dev, status)) < 0)
  243. fprintf (stderr, "alsa_out: xrun. can't determine length\n") ;
  244. else if (snd_pcm_status_get_state (status) == SND_PCM_STATE_XRUN)
  245. { struct timeval now, diff, tstamp ;
  246. gettimeofday (&now, 0) ;
  247. snd_pcm_status_get_trigger_tstamp (status, &tstamp) ;
  248. timersub (&now, &tstamp, &diff) ;
  249. fprintf (stderr, "alsa_write_float xrun: of at least %.3f msecs. resetting stream\n",
  250. diff.tv_sec * 1000 + diff.tv_usec / 1000.0) ;
  251. }
  252. else
  253. fprintf (stderr, "alsa_write_float: xrun. can't determine length\n") ;
  254. } ;
  255. #endif
  256. snd_pcm_prepare (alsa_dev) ;
  257. break ;
  258. case -EBADFD :
  259. fprintf (stderr, "alsa_write_float: Bad PCM state.n") ;
  260. return 0 ;
  261. break ;
  262. #if defined ESTRPIPE && ESTRPIPE != EPIPE
  263. case -ESTRPIPE :
  264. fprintf (stderr, "alsa_write_float: Suspend event.n") ;
  265. return 0 ;
  266. break ;
  267. #endif
  268. case -EIO :
  269. puts ("alsa_write_float: EIO") ;
  270. return 0 ;
  271. default :
  272. fprintf (stderr, "alsa_write_float: retval = %d\n", retval) ;
  273. return 0 ;
  274. break ;
  275. } ; /* switch */
  276. } ; /* while */
  277. return total ;
  278. } /* alsa_write_float */
  279. #endif /* HAVE_ALSA_ASOUNDLIB_H */
  280. /*------------------------------------------------------------------------------
  281. ** Linux/OSS functions for playing a sound.
  282. */
  283. #if !defined (__ANDROID__) && (defined (__linux__) || defined (__FreeBSD_kernel__) || defined (__FreeBSD__) || defined (__riscos__))
  284. static int opensoundsys_open_device (int channels, int srate) ;
  285. static int
  286. opensoundsys_play (int argc, char *argv [])
  287. { static short buffer [BUFFER_LEN] ;
  288. SNDFILE *sndfile ;
  289. SF_INFO sfinfo ;
  290. int k, audio_device, readcount, writecount, subformat ;
  291. for (k = 1 ; k < argc ; k++)
  292. { memset (&sfinfo, 0, sizeof (sfinfo)) ;
  293. printf ("Playing %s\n", argv [k]) ;
  294. if (! (sndfile = sf_open (argv [k], SFM_READ, &sfinfo)))
  295. { puts (sf_strerror (NULL)) ;
  296. continue ;
  297. } ;
  298. if (sfinfo.channels < 1 || sfinfo.channels > 2)
  299. { printf ("Error : channels = %d.\n", sfinfo.channels) ;
  300. continue ;
  301. } ;
  302. audio_device = opensoundsys_open_device (sfinfo.channels, sfinfo.samplerate) ;
  303. subformat = sfinfo.format & SF_FORMAT_SUBMASK ;
  304. if (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE)
  305. { static float float_buffer [BUFFER_LEN] ;
  306. double scale ;
  307. int m ;
  308. sf_command (sndfile, SFC_CALC_SIGNAL_MAX, &scale, sizeof (scale)) ;
  309. if (scale < 1e-10)
  310. scale = 1.0 ;
  311. else
  312. scale = 32700.0 / scale ;
  313. while ((readcount = sf_read_float (sndfile, float_buffer, BUFFER_LEN)))
  314. { for (m = 0 ; m < readcount ; m++)
  315. buffer [m] = scale * float_buffer [m] ;
  316. writecount = write (audio_device, buffer, readcount * sizeof (short)) ;
  317. } ;
  318. }
  319. else
  320. { while ((readcount = sf_read_short (sndfile, buffer, BUFFER_LEN)))
  321. writecount = write (audio_device, buffer, readcount * sizeof (short)) ;
  322. } ;
  323. if (ioctl (audio_device, SNDCTL_DSP_POST, 0) == -1)
  324. perror ("ioctl (SNDCTL_DSP_POST) ") ;
  325. if (ioctl (audio_device, SNDCTL_DSP_SYNC, 0) == -1)
  326. perror ("ioctl (SNDCTL_DSP_SYNC) ") ;
  327. close (audio_device) ;
  328. sf_close (sndfile) ;
  329. } ;
  330. return writecount ;
  331. } /* opensoundsys_play */
  332. static int
  333. opensoundsys_open_device (int channels, int srate)
  334. { int fd, stereo, fmt ;
  335. if ((fd = open ("/dev/dsp", O_WRONLY, 0)) == -1 &&
  336. (fd = open ("/dev/sound/dsp", O_WRONLY, 0)) == -1)
  337. { perror ("opensoundsys_open_device : open ") ;
  338. exit (1) ;
  339. } ;
  340. stereo = 0 ;
  341. if (ioctl (fd, SNDCTL_DSP_STEREO, &stereo) == -1)
  342. { /* Fatal error */
  343. perror ("opensoundsys_open_device : stereo ") ;
  344. exit (1) ;
  345. } ;
  346. if (ioctl (fd, SNDCTL_DSP_RESET, 0))
  347. { perror ("opensoundsys_open_device : reset ") ;
  348. exit (1) ;
  349. } ;
  350. fmt = CPU_IS_BIG_ENDIAN ? AFMT_S16_BE : AFMT_S16_LE ;
  351. if (ioctl (fd, SNDCTL_DSP_SETFMT, &fmt) != 0)
  352. { perror ("opensoundsys_open_device : set format ") ;
  353. exit (1) ;
  354. } ;
  355. if (ioctl (fd, SNDCTL_DSP_CHANNELS, &channels) != 0)
  356. { perror ("opensoundsys_open_device : channels ") ;
  357. exit (1) ;
  358. } ;
  359. if (ioctl (fd, SNDCTL_DSP_SPEED, &srate) != 0)
  360. { perror ("opensoundsys_open_device : sample rate ") ;
  361. exit (1) ;
  362. } ;
  363. if (ioctl (fd, SNDCTL_DSP_SYNC, 0) != 0)
  364. { perror ("opensoundsys_open_device : sync ") ;
  365. exit (1) ;
  366. } ;
  367. return fd ;
  368. } /* opensoundsys_open_device */
  369. #endif /* __linux__ */
  370. /*------------------------------------------------------------------------------
  371. ** Mac OS X functions for playing a sound.
  372. */
  373. /* MacOSX 10.8 use a new Audio API. Someone needs to write some code for it. */
  374. /*------------------------------------------------------------------------------
  375. ** Win32 functions for playing a sound.
  376. **
  377. ** This API sucks. Its needlessly complicated and is *WAY* too loose with
  378. ** passing pointers around in integers and using char* pointers to
  379. ** point to data instead of short*. It plain sucks!
  380. */
  381. #if (OS_IS_WIN32 == 1)
  382. #define WIN32_BUFFER_LEN (1 << 15)
  383. typedef struct
  384. { HWAVEOUT hwave ;
  385. WAVEHDR whdr [2] ;
  386. CRITICAL_SECTION mutex ; /* to control access to BuffersInUSe */
  387. HANDLE Event ; /* signal that a buffer is free */
  388. short buffer [WIN32_BUFFER_LEN / sizeof (short)] ;
  389. int current, bufferlen ;
  390. int BuffersInUse ;
  391. SNDFILE *sndfile ;
  392. SF_INFO sfinfo ;
  393. sf_count_t remaining ;
  394. } Win32_Audio_Data ;
  395. static void
  396. win32_play_data (Win32_Audio_Data *audio_data)
  397. { int thisread, readcount ;
  398. /* fill a buffer if there is more data and we can read it sucessfully */
  399. readcount = (audio_data->remaining > audio_data->bufferlen) ? audio_data->bufferlen : (int) audio_data->remaining ;
  400. short *lpData = (short *) (void *) audio_data->whdr [audio_data->current].lpData ;
  401. thisread = (int) sf_read_short (audio_data->sndfile, lpData, readcount) ;
  402. audio_data->remaining -= thisread ;
  403. if (thisread > 0)
  404. { /* Fix buffer length if this is only a partial block. */
  405. if (thisread < audio_data->bufferlen)
  406. audio_data->whdr [audio_data->current].dwBufferLength = thisread * sizeof (short) ;
  407. /* Queue the WAVEHDR */
  408. waveOutWrite (audio_data->hwave, (LPWAVEHDR) &(audio_data->whdr [audio_data->current]), sizeof (WAVEHDR)) ;
  409. /* count another buffer in use */
  410. EnterCriticalSection (&audio_data->mutex) ;
  411. audio_data->BuffersInUse ++ ;
  412. LeaveCriticalSection (&audio_data->mutex) ;
  413. /* use the other buffer next time */
  414. audio_data->current = (audio_data->current + 1) % 2 ;
  415. } ;
  416. return ;
  417. } /* win32_play_data */
  418. static void CALLBACK
  419. win32_audio_out_callback (HWAVEOUT hwave, UINT msg, DWORD_PTR data, DWORD param1, DWORD param2)
  420. { Win32_Audio_Data *audio_data ;
  421. /* Prevent compiler warnings. */
  422. (void) hwave ;
  423. (void) param1 ;
  424. (void) param2 ;
  425. if (data == 0)
  426. return ;
  427. /*
  428. ** I consider this technique of passing a pointer via an integer as
  429. ** fundamentally broken but thats the way microsoft has defined the
  430. ** interface.
  431. */
  432. audio_data = (Win32_Audio_Data*) data ;
  433. /* let main loop know a buffer is free */
  434. if (msg == MM_WOM_DONE)
  435. { EnterCriticalSection (&audio_data->mutex) ;
  436. audio_data->BuffersInUse -- ;
  437. LeaveCriticalSection (&audio_data->mutex) ;
  438. SetEvent (audio_data->Event) ;
  439. } ;
  440. return ;
  441. } /* win32_audio_out_callback */
  442. static void
  443. win32_play (int argc, char *argv [])
  444. { Win32_Audio_Data audio_data ;
  445. WAVEFORMATEX wf ;
  446. int k, error ;
  447. audio_data.sndfile = NULL ;
  448. audio_data.hwave = 0 ;
  449. for (k = 1 ; k < argc ; k++)
  450. { printf ("Playing %s\n", argv [k]) ;
  451. if (! (audio_data.sndfile = sf_open (argv [k], SFM_READ, &(audio_data.sfinfo))))
  452. { puts (sf_strerror (NULL)) ;
  453. continue ;
  454. } ;
  455. audio_data.remaining = audio_data.sfinfo.frames * audio_data.sfinfo.channels ;
  456. audio_data.current = 0 ;
  457. InitializeCriticalSection (&audio_data.mutex) ;
  458. audio_data.Event = CreateEvent (0, FALSE, FALSE, 0) ;
  459. wf.nChannels = audio_data.sfinfo.channels ;
  460. wf.wFormatTag = WAVE_FORMAT_PCM ;
  461. wf.cbSize = 0 ;
  462. wf.wBitsPerSample = 16 ;
  463. wf.nSamplesPerSec = audio_data.sfinfo.samplerate ;
  464. wf.nBlockAlign = audio_data.sfinfo.channels * sizeof (short) ;
  465. wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec ;
  466. error = waveOutOpen (&(audio_data.hwave), WAVE_MAPPER, &wf, (DWORD_PTR) win32_audio_out_callback,
  467. (DWORD_PTR) &audio_data, CALLBACK_FUNCTION) ;
  468. if (error)
  469. { puts ("waveOutOpen failed.") ;
  470. audio_data.hwave = 0 ;
  471. continue ;
  472. } ;
  473. audio_data.whdr [0].lpData = (char*) audio_data.buffer ;
  474. audio_data.whdr [1].lpData = ((char*) audio_data.buffer) + sizeof (audio_data.buffer) / 2 ;
  475. audio_data.whdr [0].dwBufferLength = sizeof (audio_data.buffer) / 2 ;
  476. audio_data.whdr [1].dwBufferLength = sizeof (audio_data.buffer) / 2 ;
  477. audio_data.whdr [0].dwFlags = 0 ;
  478. audio_data.whdr [1].dwFlags = 0 ;
  479. /* length of each audio buffer in samples */
  480. audio_data.bufferlen = sizeof (audio_data.buffer) / 2 / sizeof (short) ;
  481. /* Prepare the WAVEHDRs */
  482. if ((error = waveOutPrepareHeader (audio_data.hwave, &(audio_data.whdr [0]), sizeof (WAVEHDR))))
  483. { printf ("waveOutPrepareHeader [0] failed : %08X\n", error) ;
  484. waveOutClose (audio_data.hwave) ;
  485. continue ;
  486. } ;
  487. if ((error = waveOutPrepareHeader (audio_data.hwave, &(audio_data.whdr [1]), sizeof (WAVEHDR))))
  488. { printf ("waveOutPrepareHeader [1] failed : %08X\n", error) ;
  489. waveOutUnprepareHeader (audio_data.hwave, &(audio_data.whdr [0]), sizeof (WAVEHDR)) ;
  490. waveOutClose (audio_data.hwave) ;
  491. continue ;
  492. } ;
  493. /* Fill up both buffers with audio data */
  494. audio_data.BuffersInUse = 0 ;
  495. win32_play_data (&audio_data) ;
  496. win32_play_data (&audio_data) ;
  497. /* loop until both buffers are released */
  498. while (audio_data.BuffersInUse > 0)
  499. {
  500. /* wait for buffer to be released */
  501. WaitForSingleObject (audio_data.Event, INFINITE) ;
  502. /* refill the buffer if there is more data to play */
  503. win32_play_data (&audio_data) ;
  504. } ;
  505. waveOutUnprepareHeader (audio_data.hwave, &(audio_data.whdr [0]), sizeof (WAVEHDR)) ;
  506. waveOutUnprepareHeader (audio_data.hwave, &(audio_data.whdr [1]), sizeof (WAVEHDR)) ;
  507. waveOutClose (audio_data.hwave) ;
  508. audio_data.hwave = 0 ;
  509. DeleteCriticalSection (&audio_data.mutex) ;
  510. sf_close (audio_data.sndfile) ;
  511. } ;
  512. } /* win32_play */
  513. #endif /* Win32 */
  514. /*------------------------------------------------------------------------------
  515. ** OpenBSD's sndio.
  516. */
  517. #if HAVE_SNDIO_H
  518. static void
  519. sndio_play (int argc, char *argv [])
  520. { struct sio_hdl *hdl ;
  521. struct sio_par par ;
  522. short buffer [BUFFER_LEN] ;
  523. SNDFILE *sndfile ;
  524. SF_INFO sfinfo ;
  525. int k, readcount ;
  526. for (k = 1 ; k < argc ; k++)
  527. { printf ("Playing %s\n", argv [k]) ;
  528. if (! (sndfile = sf_open (argv [k], SFM_READ, &sfinfo)))
  529. { puts (sf_strerror (NULL)) ;
  530. continue ;
  531. } ;
  532. if (sfinfo.channels < 1 || sfinfo.channels > 2)
  533. { printf ("Error : channels = %d.\n", sfinfo.channels) ;
  534. continue ;
  535. } ;
  536. if ((hdl = sio_open (NULL, SIO_PLAY, 0)) == NULL)
  537. { fprintf (stderr, "open sndio device failed") ;
  538. return ;
  539. } ;
  540. sio_initpar (&par) ;
  541. par.rate = sfinfo.samplerate ;
  542. par.pchan = sfinfo.channels ;
  543. par.bits = 16 ;
  544. par.sig = 1 ;
  545. par.le = SIO_LE_NATIVE ;
  546. if (! sio_setpar (hdl, &par) || ! sio_getpar (hdl, &par))
  547. { fprintf (stderr, "set sndio params failed") ;
  548. return ;
  549. } ;
  550. if (! sio_start (hdl))
  551. { fprintf (stderr, "sndio start failed") ;
  552. return ;
  553. } ;
  554. while ((readcount = sf_read_short (sndfile, buffer, BUFFER_LEN)))
  555. sio_write (hdl, buffer, readcount * sizeof (short)) ;
  556. sio_close (hdl) ;
  557. } ;
  558. return ;
  559. } /* sndio_play */
  560. #endif /* sndio */
  561. /*------------------------------------------------------------------------------
  562. ** Solaris.
  563. */
  564. #if (defined (sun) && defined (unix)) || defined(__NetBSD__)
  565. static void
  566. solaris_play (int argc, char *argv [])
  567. { static short buffer [BUFFER_LEN] ;
  568. audio_info_t audio_info ;
  569. SNDFILE *sndfile ;
  570. SF_INFO sfinfo ;
  571. unsigned long delay_time ;
  572. long k, start_count, output_count, write_count, read_count ;
  573. int audio_fd, error, done ;
  574. for (k = 1 ; k < argc ; k++)
  575. { printf ("Playing %s\n", argv [k]) ;
  576. if (! (sndfile = sf_open (argv [k], SFM_READ, &sfinfo)))
  577. { puts (sf_strerror (NULL)) ;
  578. continue ;
  579. } ;
  580. if (sfinfo.channels < 1 || sfinfo.channels > 2)
  581. { printf ("Error : channels = %d.\n", sfinfo.channels) ;
  582. continue ;
  583. } ;
  584. /* open the audio device - write only, non-blocking */
  585. if ((audio_fd = open ("/dev/audio", O_WRONLY | O_NONBLOCK)) < 0)
  586. { perror ("open (/dev/audio) failed") ;
  587. return ;
  588. } ;
  589. /* Retrive standard values. */
  590. AUDIO_INITINFO (&audio_info) ;
  591. audio_info.play.sample_rate = sfinfo.samplerate ;
  592. audio_info.play.channels = sfinfo.channels ;
  593. audio_info.play.precision = 16 ;
  594. audio_info.play.encoding = AUDIO_ENCODING_LINEAR ;
  595. if ((error = ioctl (audio_fd, AUDIO_SETINFO, &audio_info)))
  596. { perror ("ioctl (AUDIO_SETINFO) failed") ;
  597. return ;
  598. } ;
  599. /* Delay time equal to 1/4 of a buffer in microseconds. */
  600. delay_time = (BUFFER_LEN * 1000000) / (audio_info.play.sample_rate * 4) ;
  601. done = 0 ;
  602. while (! done)
  603. { read_count = sf_read_short (sndfile, buffer, BUFFER_LEN) ;
  604. if (read_count < BUFFER_LEN)
  605. { memset (&(buffer [read_count]), 0, (BUFFER_LEN - read_count) * sizeof (short)) ;
  606. /* Tell the main application to terminate. */
  607. done = SF_TRUE ;
  608. } ;
  609. start_count = 0 ;
  610. output_count = BUFFER_LEN * sizeof (short) ;
  611. while (output_count > 0)
  612. { /* write as much data as possible */
  613. write_count = write (audio_fd, &(buffer [start_count]), output_count) ;
  614. if (write_count > 0)
  615. { output_count -= write_count ;
  616. start_count += write_count ;
  617. }
  618. else
  619. { /* Give the audio output time to catch up. */
  620. usleep (delay_time) ;
  621. } ;
  622. } ; /* while (outpur_count > 0) */
  623. } ; /* while (! done) */
  624. close (audio_fd) ;
  625. } ;
  626. return ;
  627. } /* solaris_play */
  628. #endif /* Solaris or NetBSD */
  629. /*==============================================================================
  630. ** Main function.
  631. */
  632. int
  633. main (int argc, char *argv [])
  634. {
  635. if (argc < 2)
  636. {
  637. printf ("\nUsage : %s <input sound file>\n\n", program_name (argv [0])) ;
  638. printf ("Using %s.\n\n", sf_version_string ()) ;
  639. #if (OS_IS_WIN32 == 1)
  640. printf ("This is a Unix style command line application which\n"
  641. "should be run in a MSDOS box or Command Shell window.\n\n") ;
  642. printf ("Sleeping for 5 seconds before exiting.\n\n") ;
  643. Sleep (5 * 1000) ;
  644. #endif
  645. return 1 ;
  646. } ;
  647. #if defined (__ANDROID__)
  648. puts ("*** Playing sound not yet supported on Android.") ;
  649. puts ("*** Please feel free to submit a patch.") ;
  650. return 1 ;
  651. #elif defined (__linux__)
  652. #if HAVE_ALSA_ASOUNDLIB_H
  653. if (access ("/proc/asound/cards", R_OK) == 0)
  654. alsa_play (argc, argv) ;
  655. else
  656. #endif
  657. opensoundsys_play (argc, argv) ;
  658. #elif defined (__FreeBSD_kernel__) || defined (__FreeBSD__) || defined (__riscos__)
  659. opensoundsys_play (argc, argv) ;
  660. #elif HAVE_SNDIO_H
  661. sndio_play (argc, argv) ;
  662. #elif (defined (sun) && defined (unix)) || defined(__NetBSD__)
  663. solaris_play (argc, argv) ;
  664. #elif (OS_IS_WIN32 == 1)
  665. win32_play (argc, argv) ;
  666. #else
  667. puts ("*** Playing sound not supported on this platform.") ;
  668. puts ("*** Please feel free to submit a patch.") ;
  669. return 1 ;
  670. #endif
  671. return 0 ;
  672. } /* main */