Forward Sample_ALuint to Sample_ALint
[openal-soft.git] / examples / alstream.c
blob68115e8dcbe73e7fe7cbcf3982597a9f661ee2cf
1 /*
2 * OpenAL Audio Stream Example
4 * Copyright (c) 2011 by Chris Robinson <chris.kcat@gmail.com>
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
25 /* This file contains a relatively simple streaming audio player. */
27 #include <string.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <signal.h>
31 #include <assert.h>
33 #include <SDL_sound.h>
35 #include "AL/al.h"
36 #include "AL/alc.h"
37 #include "AL/alext.h"
39 #include "common/alhelpers.h"
42 #ifndef SDL_AUDIO_MASK_BITSIZE
43 #define SDL_AUDIO_MASK_BITSIZE (0xFF)
44 #endif
45 #ifndef SDL_AUDIO_BITSIZE
46 #define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
47 #endif
49 /* Define the number of buffers and buffer size (in milliseconds) to use. 4
50 * buffers with 200ms each gives a nice per-chunk size, and lets the queue last
51 * for almost one second. */
52 #define NUM_BUFFERS 4
53 #define BUFFER_TIME_MS 200
55 typedef struct StreamPlayer {
56 /* These are the buffers and source to play out through OpenAL with */
57 ALuint buffers[NUM_BUFFERS];
58 ALuint source;
60 /* Handle for the audio file */
61 Sound_Sample *sample;
63 /* The format of the output stream */
64 ALenum format;
65 ALsizei srate;
66 } StreamPlayer;
68 static StreamPlayer *NewPlayer(void);
69 static void DeletePlayer(StreamPlayer *player);
70 static int OpenPlayerFile(StreamPlayer *player, const char *filename);
71 static void ClosePlayerFile(StreamPlayer *player);
72 static int StartPlayer(StreamPlayer *player);
73 static int UpdatePlayer(StreamPlayer *player);
75 /* Creates a new player object, and allocates the needed OpenAL source and
76 * buffer objects. Error checking is simplified for the purposes of this
77 * example, and will cause an abort if needed. */
78 static StreamPlayer *NewPlayer(void)
80 StreamPlayer *player;
82 player = calloc(1, sizeof(*player));
83 assert(player != NULL);
85 /* Generate the buffers and source */
86 alGenBuffers(NUM_BUFFERS, player->buffers);
87 assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
89 alGenSources(1, &player->source);
90 assert(alGetError() == AL_NO_ERROR && "Could not create source");
92 /* Set parameters so mono sources play out the front-center speaker and
93 * won't distance attenuate. */
94 alSource3i(player->source, AL_POSITION, 0, 0, -1);
95 alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE);
96 alSourcei(player->source, AL_ROLLOFF_FACTOR, 0);
97 assert(alGetError() == AL_NO_ERROR && "Could not set source parameters");
99 return player;
102 /* Destroys a player object, deleting the source and buffers. No error handling
103 * since these calls shouldn't fail with a properly-made player object. */
104 static void DeletePlayer(StreamPlayer *player)
106 ClosePlayerFile(player);
108 alDeleteSources(1, &player->source);
109 alDeleteBuffers(NUM_BUFFERS, player->buffers);
110 if(alGetError() != AL_NO_ERROR)
111 fprintf(stderr, "Failed to delete object IDs\n");
113 memset(player, 0, sizeof(*player));
114 free(player);
118 /* Opens the first audio stream of the named file. If a file is already open,
119 * it will be closed first. */
120 static int OpenPlayerFile(StreamPlayer *player, const char *filename)
122 Uint32 frame_size;
124 ClosePlayerFile(player);
126 /* Open the file and get the first stream from it */
127 player->sample = Sound_NewSampleFromFile(filename, NULL, 0);
128 if(!player->sample)
130 fprintf(stderr, "Could not open audio in %s\n", filename);
131 goto error;
134 /* Get the stream format, and figure out the OpenAL format */
135 if(player->sample->actual.channels == 1)
137 if(player->sample->actual.format == AUDIO_U8)
138 player->format = AL_FORMAT_MONO8;
139 else if(player->sample->actual.format == AUDIO_S16SYS)
140 player->format = AL_FORMAT_MONO16;
141 else
143 fprintf(stderr, "Unsupported sample format: 0x%04x\n", player->sample->actual.format);
144 goto error;
147 else if(player->sample->actual.channels == 2)
149 if(player->sample->actual.format == AUDIO_U8)
150 player->format = AL_FORMAT_STEREO8;
151 else if(player->sample->actual.format == AUDIO_S16SYS)
152 player->format = AL_FORMAT_STEREO16;
153 else
155 fprintf(stderr, "Unsupported sample format: 0x%04x\n", player->sample->actual.format);
156 goto error;
159 else
161 fprintf(stderr, "Unsupported channel count: %d\n", player->sample->actual.channels);
162 goto error;
164 player->srate = player->sample->actual.rate;
166 frame_size = player->sample->actual.channels *
167 SDL_AUDIO_BITSIZE(player->sample->actual.format) / 8;
169 /* Set the buffer size, given the desired millisecond length. */
170 Sound_SetBufferSize(player->sample, (Uint32)((Uint64)player->srate*BUFFER_TIME_MS/1000) *
171 frame_size);
173 return 1;
175 error:
176 if(player->sample)
177 Sound_FreeSample(player->sample);
178 player->sample = NULL;
180 return 0;
183 /* Closes the audio file stream */
184 static void ClosePlayerFile(StreamPlayer *player)
186 if(player->sample)
187 Sound_FreeSample(player->sample);
188 player->sample = NULL;
192 /* Prebuffers some audio from the file, and starts playing the source */
193 static int StartPlayer(StreamPlayer *player)
195 size_t i;
197 /* Rewind the source position and clear the buffer queue */
198 alSourceRewind(player->source);
199 alSourcei(player->source, AL_BUFFER, 0);
201 /* Fill the buffer queue */
202 for(i = 0;i < NUM_BUFFERS;i++)
204 /* Get some data to give it to the buffer */
205 Uint32 slen = Sound_Decode(player->sample);
206 if(slen == 0) break;
208 alBufferData(player->buffers[i], player->format,
209 player->sample->buffer, slen, player->srate);
211 if(alGetError() != AL_NO_ERROR)
213 fprintf(stderr, "Error buffering for playback\n");
214 return 0;
217 /* Now queue and start playback! */
218 alSourceQueueBuffers(player->source, i, player->buffers);
219 alSourcePlay(player->source);
220 if(alGetError() != AL_NO_ERROR)
222 fprintf(stderr, "Error starting playback\n");
223 return 0;
226 return 1;
229 static int UpdatePlayer(StreamPlayer *player)
231 ALint processed, state;
233 /* Get relevant source info */
234 alGetSourcei(player->source, AL_SOURCE_STATE, &state);
235 alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed);
236 if(alGetError() != AL_NO_ERROR)
238 fprintf(stderr, "Error checking source state\n");
239 return 0;
242 /* Unqueue and handle each processed buffer */
243 while(processed > 0)
245 ALuint bufid;
246 Uint32 slen;
248 alSourceUnqueueBuffers(player->source, 1, &bufid);
249 processed--;
251 if((player->sample->flags&(SOUND_SAMPLEFLAG_EOF|SOUND_SAMPLEFLAG_ERROR)))
252 continue;
254 /* Read the next chunk of data, refill the buffer, and queue it
255 * back on the source */
256 slen = Sound_Decode(player->sample);
257 if(slen > 0)
259 alBufferData(bufid, player->format, player->sample->buffer, slen,
260 player->srate);
261 alSourceQueueBuffers(player->source, 1, &bufid);
263 if(alGetError() != AL_NO_ERROR)
265 fprintf(stderr, "Error buffering data\n");
266 return 0;
270 /* Make sure the source hasn't underrun */
271 if(state != AL_PLAYING && state != AL_PAUSED)
273 ALint queued;
275 /* If no buffers are queued, playback is finished */
276 alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
277 if(queued == 0)
278 return 0;
280 alSourcePlay(player->source);
281 if(alGetError() != AL_NO_ERROR)
283 fprintf(stderr, "Error restarting playback\n");
284 return 0;
288 return 1;
292 int main(int argc, char **argv)
294 StreamPlayer *player;
295 int i;
297 /* Print out usage if no arguments were specified */
298 if(argc < 2)
300 fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
301 return 1;
304 argv++; argc--;
305 if(InitAL(&argv, &argc) != 0)
306 return 1;
308 Sound_Init();
310 player = NewPlayer();
312 /* Play each file listed on the command line */
313 for(i = 0;i < argc;i++)
315 const char *namepart;
317 if(!OpenPlayerFile(player, argv[i]))
318 continue;
320 /* Get the name portion, without the path, for display. */
321 namepart = strrchr(argv[i], '/');
322 if(namepart || (namepart=strrchr(argv[i], '\\')))
323 namepart++;
324 else
325 namepart = argv[i];
327 printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
328 player->srate);
329 fflush(stdout);
331 if(!StartPlayer(player))
333 ClosePlayerFile(player);
334 continue;
337 while(UpdatePlayer(player))
338 al_nssleep(10000000);
340 /* All done with this file. Close it and go to the next */
341 ClosePlayerFile(player);
343 printf("Done.\n");
345 /* All files done. Delete the player, and close down SDL_sound and OpenAL */
346 DeletePlayer(player);
347 player = NULL;
349 Sound_Quit();
350 CloseAL();
352 return 0;