alstream.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 <string.h>
  26. #include <stdlib.h>
  27. #include <stdio.h>
  28. #include <signal.h>
  29. #include <assert.h>
  30. #include "AL/al.h"
  31. #include "AL/alc.h"
  32. #include "AL/alext.h"
  33. #include "common/alhelpers.h"
  34. #include "common/sdl_sound.h"
  35. static LPALBUFFERSAMPLESSOFT alBufferSamplesSOFT = wrap_BufferSamples;
  36. static LPALISBUFFERFORMATSUPPORTEDSOFT alIsBufferFormatSupportedSOFT;
  37. /* Define the number of buffers and buffer size (in milliseconds) to use. 4
  38. * buffers with 200ms each gives a nice per-chunk size, and lets the queue last
  39. * for almost one second. */
  40. #define NUM_BUFFERS 4
  41. #define BUFFER_TIME_MS 200
  42. typedef struct StreamPlayer {
  43. /* These are the buffers and source to play out through OpenAL with */
  44. ALuint buffers[NUM_BUFFERS];
  45. ALuint source;
  46. /* Handle for the audio file */
  47. FilePtr file;
  48. /* The format of the output stream */
  49. ALenum format;
  50. ALenum channels;
  51. ALenum type;
  52. ALuint rate;
  53. } StreamPlayer;
  54. static StreamPlayer *NewPlayer(void);
  55. static void DeletePlayer(StreamPlayer *player);
  56. static int OpenPlayerFile(StreamPlayer *player, const char *filename);
  57. static void ClosePlayerFile(StreamPlayer *player);
  58. static int StartPlayer(StreamPlayer *player);
  59. static int UpdatePlayer(StreamPlayer *player);
  60. /* Creates a new player object, and allocates the needed OpenAL source and
  61. * buffer objects. Error checking is simplified for the purposes of this
  62. * example, and will cause an abort if needed. */
  63. static StreamPlayer *NewPlayer(void)
  64. {
  65. StreamPlayer *player;
  66. player = malloc(sizeof(*player));
  67. assert(player != NULL);
  68. memset(player, 0, sizeof(*player));
  69. /* Generate the buffers and source */
  70. alGenBuffers(NUM_BUFFERS, player->buffers);
  71. assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
  72. alGenSources(1, &player->source);
  73. assert(alGetError() == AL_NO_ERROR && "Could not create source");
  74. /* Set parameters so mono sources play out the front-center speaker and
  75. * won't distance attenuate. */
  76. alSource3i(player->source, AL_POSITION, 0, 0, -1);
  77. alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE);
  78. alSourcei(player->source, AL_ROLLOFF_FACTOR, 0);
  79. assert(alGetError() == AL_NO_ERROR && "Could not set source parameters");
  80. return player;
  81. }
  82. /* Destroys a player object, deleting the source and buffers. No error handling
  83. * since these calls shouldn't fail with a properly-made player object. */
  84. static void DeletePlayer(StreamPlayer *player)
  85. {
  86. ClosePlayerFile(player);
  87. alDeleteSources(1, &player->source);
  88. alDeleteBuffers(NUM_BUFFERS, player->buffers);
  89. if(alGetError() != AL_NO_ERROR)
  90. fprintf(stderr, "Failed to delete object IDs\n");
  91. memset(player, 0, sizeof(*player));
  92. free(player);
  93. }
  94. /* Opens the first audio stream of the named file. If a file is already open,
  95. * it will be closed first. */
  96. static int OpenPlayerFile(StreamPlayer *player, const char *filename)
  97. {
  98. ClosePlayerFile(player);
  99. /* Open the file and get the first stream from it */
  100. player->file = openAudioFile(filename, BUFFER_TIME_MS);
  101. if(!player->file)
  102. {
  103. fprintf(stderr, "Could not open audio in %s\n", filename);
  104. goto error;
  105. }
  106. /* Get the stream format, and figure out the OpenAL format */
  107. if(getAudioInfo(player->file, &player->rate, &player->channels, &player->type) != 0)
  108. {
  109. fprintf(stderr, "Error getting audio info for %s\n", filename);
  110. goto error;
  111. }
  112. player->format = GetFormat(player->channels, player->type, alIsBufferFormatSupportedSOFT);
  113. if(player->format == 0)
  114. {
  115. fprintf(stderr, "Unsupported format (%s, %s) for %s\n",
  116. ChannelsName(player->channels), TypeName(player->type),
  117. filename);
  118. goto error;
  119. }
  120. return 1;
  121. error:
  122. closeAudioFile(player->file);
  123. player->file = NULL;
  124. return 0;
  125. }
  126. /* Closes the audio file stream */
  127. static void ClosePlayerFile(StreamPlayer *player)
  128. {
  129. closeAudioFile(player->file);
  130. player->file = NULL;
  131. }
  132. /* Prebuffers some audio from the file, and starts playing the source */
  133. static int StartPlayer(StreamPlayer *player)
  134. {
  135. size_t i;
  136. /* Rewind the source position and clear the buffer queue */
  137. alSourceRewind(player->source);
  138. alSourcei(player->source, AL_BUFFER, 0);
  139. /* Fill the buffer queue */
  140. for(i = 0;i < NUM_BUFFERS;i++)
  141. {
  142. uint8_t *data;
  143. size_t got;
  144. /* Get some data to give it to the buffer */
  145. data = getAudioData(player->file, &got);
  146. if(!data) break;
  147. alBufferSamplesSOFT(player->buffers[i], player->rate, player->format,
  148. BytesToFrames(got, player->channels, player->type),
  149. player->channels, player->type, data);
  150. }
  151. if(alGetError() != AL_NO_ERROR)
  152. {
  153. fprintf(stderr, "Error buffering for playback\n");
  154. return 0;
  155. }
  156. /* Now queue and start playback! */
  157. alSourceQueueBuffers(player->source, i, player->buffers);
  158. alSourcePlay(player->source);
  159. if(alGetError() != AL_NO_ERROR)
  160. {
  161. fprintf(stderr, "Error starting playback\n");
  162. return 0;
  163. }
  164. return 1;
  165. }
  166. static int UpdatePlayer(StreamPlayer *player)
  167. {
  168. ALint processed, state;
  169. /* Get relevant source info */
  170. alGetSourcei(player->source, AL_SOURCE_STATE, &state);
  171. alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed);
  172. if(alGetError() != AL_NO_ERROR)
  173. {
  174. fprintf(stderr, "Error checking source state\n");
  175. return 0;
  176. }
  177. /* Unqueue and handle each processed buffer */
  178. while(processed > 0)
  179. {
  180. ALuint bufid;
  181. uint8_t *data;
  182. size_t got;
  183. alSourceUnqueueBuffers(player->source, 1, &bufid);
  184. processed--;
  185. /* Read the next chunk of data, refill the buffer, and queue it
  186. * back on the source */
  187. data = getAudioData(player->file, &got);
  188. if(data != NULL)
  189. {
  190. alBufferSamplesSOFT(bufid, player->rate, player->format,
  191. BytesToFrames(got, player->channels, player->type),
  192. player->channels, player->type, data);
  193. alSourceQueueBuffers(player->source, 1, &bufid);
  194. }
  195. if(alGetError() != AL_NO_ERROR)
  196. {
  197. fprintf(stderr, "Error buffering data\n");
  198. return 0;
  199. }
  200. }
  201. /* Make sure the source hasn't underrun */
  202. if(state != AL_PLAYING && state != AL_PAUSED)
  203. {
  204. ALint queued;
  205. /* If no buffers are queued, playback is finished */
  206. alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
  207. if(queued == 0)
  208. return 0;
  209. alSourcePlay(player->source);
  210. if(alGetError() != AL_NO_ERROR)
  211. {
  212. fprintf(stderr, "Error restarting playback\n");
  213. return 0;
  214. }
  215. }
  216. return 1;
  217. }
  218. int main(int argc, char **argv)
  219. {
  220. StreamPlayer *player;
  221. int i;
  222. /* Print out usage if no file was specified */
  223. if(argc < 2)
  224. {
  225. fprintf(stderr, "Usage: %s <filenames...>\n", argv[0]);
  226. return 1;
  227. }
  228. if(InitAL() != 0)
  229. return 1;
  230. if(alIsExtensionPresent("AL_SOFT_buffer_samples"))
  231. {
  232. printf("AL_SOFT_buffer_samples supported!\n");
  233. alBufferSamplesSOFT = alGetProcAddress("alBufferSamplesSOFT");
  234. alIsBufferFormatSupportedSOFT = alGetProcAddress("alIsBufferFormatSupportedSOFT");
  235. }
  236. else
  237. printf("AL_SOFT_buffer_samples not supported\n");
  238. player = NewPlayer();
  239. /* Play each file listed on the command line */
  240. for(i = 1;i < argc;i++)
  241. {
  242. const char *namepart;
  243. if(!OpenPlayerFile(player, argv[i]))
  244. continue;
  245. /* Get the name portion, without the path, for display. */
  246. namepart = strrchr(argv[i], '/');
  247. if(namepart || (namepart=strrchr(argv[i], '\\')))
  248. namepart++;
  249. else
  250. namepart = argv[i];
  251. printf("Playing: %s (%s, %s, %dhz)\n", namepart,
  252. TypeName(player->type), ChannelsName(player->channels),
  253. player->rate);
  254. fflush(stdout);
  255. if(!StartPlayer(player))
  256. {
  257. ClosePlayerFile(player);
  258. continue;
  259. }
  260. while(UpdatePlayer(player))
  261. Sleep(10);
  262. /* All done with this file. Close it and go to the next */
  263. ClosePlayerFile(player);
  264. }
  265. printf("Done.\n");
  266. /* All files done. Delete the player, and close OpenAL */
  267. DeletePlayer(player);
  268. player = NULL;
  269. CloseAL();
  270. return 0;
  271. }