alstream.c 10 KB

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