Combine two function calls into one
[openal-soft.git] / examples / alstream.c
blob56505ddbe8fe5180c44fba08dcd10e3fa570ce2f
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 <assert.h>
32 #include "SDL_sound.h"
33 #include "SDL_audio.h"
34 #include "SDL_stdinc.h"
36 #include "AL/al.h"
38 #include "common/alhelpers.h"
41 #ifndef SDL_AUDIO_MASK_BITSIZE
42 #define SDL_AUDIO_MASK_BITSIZE (0xFF)
43 #endif
44 #ifndef SDL_AUDIO_BITSIZE
45 #define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
46 #endif
48 /* Define the number of buffers and buffer size (in milliseconds) to use. 4
49 * buffers with 200ms each gives a nice per-chunk size, and lets the queue last
50 * for almost one second. */
51 #define NUM_BUFFERS 4
52 #define BUFFER_TIME_MS 200
54 typedef struct StreamPlayer {
55 /* These are the buffers and source to play out through OpenAL with */
56 ALuint buffers[NUM_BUFFERS];
57 ALuint source;
59 /* Handle for the audio file */
60 Sound_Sample *sample;
62 /* The format of the output stream */
63 ALenum format;
64 ALsizei srate;
65 } StreamPlayer;
67 static StreamPlayer *NewPlayer(void);
68 static void DeletePlayer(StreamPlayer *player);
69 static int OpenPlayerFile(StreamPlayer *player, const char *filename);
70 static void ClosePlayerFile(StreamPlayer *player);
71 static int StartPlayer(StreamPlayer *player);
72 static int UpdatePlayer(StreamPlayer *player);
74 /* Creates a new player object, and allocates the needed OpenAL source and
75 * buffer objects. Error checking is simplified for the purposes of this
76 * example, and will cause an abort if needed. */
77 static StreamPlayer *NewPlayer(void)
79 StreamPlayer *player;
81 player = calloc(1, sizeof(*player));
82 assert(player != NULL);
84 /* Generate the buffers and source */
85 alGenBuffers(NUM_BUFFERS, player->buffers);
86 assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
88 alGenSources(1, &player->source);
89 assert(alGetError() == AL_NO_ERROR && "Could not create source");
91 /* Set parameters so mono sources play out the front-center speaker and
92 * won't distance attenuate. */
93 alSource3i(player->source, AL_POSITION, 0, 0, -1);
94 alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE);
95 alSourcei(player->source, AL_ROLLOFF_FACTOR, 0);
96 assert(alGetError() == AL_NO_ERROR && "Could not set source parameters");
98 return player;
101 /* Destroys a player object, deleting the source and buffers. No error handling
102 * since these calls shouldn't fail with a properly-made player object. */
103 static void DeletePlayer(StreamPlayer *player)
105 ClosePlayerFile(player);
107 alDeleteSources(1, &player->source);
108 alDeleteBuffers(NUM_BUFFERS, player->buffers);
109 if(alGetError() != AL_NO_ERROR)
110 fprintf(stderr, "Failed to delete object IDs\n");
112 memset(player, 0, sizeof(*player));
113 free(player);
117 /* Opens the first audio stream of the named file. If a file is already open,
118 * it will be closed first. */
119 static int OpenPlayerFile(StreamPlayer *player, const char *filename)
121 Uint32 frame_size;
123 ClosePlayerFile(player);
125 /* Open the file and get the first stream from it */
126 player->sample = Sound_NewSampleFromFile(filename, NULL, 0);
127 if(!player->sample)
129 fprintf(stderr, "Could not open audio in %s\n", filename);
130 goto error;
133 /* Get the stream format, and figure out the OpenAL format */
134 if(player->sample->actual.channels == 1)
136 if(player->sample->actual.format == AUDIO_U8)
137 player->format = AL_FORMAT_MONO8;
138 else if(player->sample->actual.format == AUDIO_S16SYS)
139 player->format = AL_FORMAT_MONO16;
140 else
142 fprintf(stderr, "Unsupported sample format: 0x%04x\n", player->sample->actual.format);
143 goto error;
146 else if(player->sample->actual.channels == 2)
148 if(player->sample->actual.format == AUDIO_U8)
149 player->format = AL_FORMAT_STEREO8;
150 else if(player->sample->actual.format == AUDIO_S16SYS)
151 player->format = AL_FORMAT_STEREO16;
152 else
154 fprintf(stderr, "Unsupported sample format: 0x%04x\n", player->sample->actual.format);
155 goto error;
158 else
160 fprintf(stderr, "Unsupported channel count: %d\n", player->sample->actual.channels);
161 goto error;
163 player->srate = (ALsizei)player->sample->actual.rate;
165 frame_size = player->sample->actual.channels *
166 SDL_AUDIO_BITSIZE(player->sample->actual.format) / 8;
168 /* Set the buffer size, given the desired millisecond length. */
169 Sound_SetBufferSize(player->sample, (Uint32)((Uint64)player->srate*BUFFER_TIME_MS/1000) *
170 frame_size);
172 return 1;
174 error:
175 if(player->sample)
176 Sound_FreeSample(player->sample);
177 player->sample = NULL;
179 return 0;
182 /* Closes the audio file stream */
183 static void ClosePlayerFile(StreamPlayer *player)
185 if(player->sample)
186 Sound_FreeSample(player->sample);
187 player->sample = NULL;
191 /* Prebuffers some audio from the file, and starts playing the source */
192 static int StartPlayer(StreamPlayer *player)
194 ALsizei i;
196 /* Rewind the source position and clear the buffer queue */
197 alSourceRewind(player->source);
198 alSourcei(player->source, AL_BUFFER, 0);
200 /* Fill the buffer queue */
201 for(i = 0;i < NUM_BUFFERS;i++)
203 /* Get some data to give it to the buffer */
204 Uint32 slen = Sound_Decode(player->sample);
205 if(slen == 0) break;
207 alBufferData(player->buffers[i], player->format, player->sample->buffer, (ALsizei)slen,
208 player->srate);
210 if(alGetError() != AL_NO_ERROR)
212 fprintf(stderr, "Error buffering for playback\n");
213 return 0;
216 /* Now queue and start playback! */
217 alSourceQueueBuffers(player->source, i, player->buffers);
218 alSourcePlay(player->source);
219 if(alGetError() != AL_NO_ERROR)
221 fprintf(stderr, "Error starting playback\n");
222 return 0;
225 return 1;
228 static int UpdatePlayer(StreamPlayer *player)
230 ALint processed, state;
232 /* Get relevant source info */
233 alGetSourcei(player->source, AL_SOURCE_STATE, &state);
234 alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed);
235 if(alGetError() != AL_NO_ERROR)
237 fprintf(stderr, "Error checking source state\n");
238 return 0;
241 /* Unqueue and handle each processed buffer */
242 while(processed > 0)
244 ALuint bufid;
245 Uint32 slen;
247 alSourceUnqueueBuffers(player->source, 1, &bufid);
248 processed--;
250 if((player->sample->flags&(SOUND_SAMPLEFLAG_EOF|SOUND_SAMPLEFLAG_ERROR)))
251 continue;
253 /* Read the next chunk of data, refill the buffer, and queue it
254 * back on the source */
255 slen = Sound_Decode(player->sample);
256 if(slen > 0)
258 alBufferData(bufid, player->format, player->sample->buffer, (ALsizei)slen,
259 player->srate);
260 alSourceQueueBuffers(player->source, 1, &bufid);
262 if(alGetError() != AL_NO_ERROR)
264 fprintf(stderr, "Error buffering data\n");
265 return 0;
269 /* Make sure the source hasn't underrun */
270 if(state != AL_PLAYING && state != AL_PAUSED)
272 ALint queued;
274 /* If no buffers are queued, playback is finished */
275 alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
276 if(queued == 0)
277 return 0;
279 alSourcePlay(player->source);
280 if(alGetError() != AL_NO_ERROR)
282 fprintf(stderr, "Error restarting playback\n");
283 return 0;
287 return 1;
291 int main(int argc, char **argv)
293 StreamPlayer *player;
294 int i;
296 /* Print out usage if no arguments were specified */
297 if(argc < 2)
299 fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
300 return 1;
303 argv++; argc--;
304 if(InitAL(&argv, &argc) != 0)
305 return 1;
307 Sound_Init();
309 player = NewPlayer();
311 /* Play each file listed on the command line */
312 for(i = 0;i < argc;i++)
314 const char *namepart;
316 if(!OpenPlayerFile(player, argv[i]))
317 continue;
319 /* Get the name portion, without the path, for display. */
320 namepart = strrchr(argv[i], '/');
321 if(namepart || (namepart=strrchr(argv[i], '\\')))
322 namepart++;
323 else
324 namepart = argv[i];
326 printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format), player->srate);
327 fflush(stdout);
329 if(!StartPlayer(player))
331 ClosePlayerFile(player);
332 continue;
335 while(UpdatePlayer(player))
336 al_nssleep(10000000);
338 /* All done with this file. Close it and go to the next */
339 ClosePlayerFile(player);
341 printf("Done.\n");
343 /* All files done. Delete the player, and close down SDL_sound and OpenAL */
344 DeletePlayer(player);
345 player = NULL;
347 Sound_Quit();
348 CloseAL();
350 return 0;