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
25 /* This file contains a relatively simple streaming audio player. */
38 #include "common/alhelpers.h"
41 /* Define the number of buffers and buffer size (in milliseconds) to use. 4
42 * buffers at 200ms each gives a nice per-chunk size, and lets the queue last
43 * for almost one second.
46 #define BUFFER_MILLISEC 200
48 typedef enum SampleType {
49 Int16, Float, IMA4, MSADPCM
52 typedef struct StreamPlayer {
53 /* These are the buffers and source to play out through OpenAL with. */
54 ALuint buffers[NUM_BUFFERS];
57 /* Handle for the audio file */
62 /* The sample type and block/frame size being read for the buffer. */
63 SampleType sample_type;
68 /* The format of the output stream (sample rate is in sfinfo) */
72 static StreamPlayer *NewPlayer(void);
73 static void DeletePlayer(StreamPlayer *player);
74 static int OpenPlayerFile(StreamPlayer *player, const char *filename);
75 static void ClosePlayerFile(StreamPlayer *player);
76 static int StartPlayer(StreamPlayer *player);
77 static int UpdatePlayer(StreamPlayer *player);
79 /* Creates a new player object, and allocates the needed OpenAL source and
80 * buffer objects. Error checking is simplified for the purposes of this
81 * example, and will cause an abort if needed.
83 static StreamPlayer *NewPlayer(void)
87 player = calloc(1, sizeof(*player));
88 assert(player != NULL);
90 /* Generate the buffers and source */
91 alGenBuffers(NUM_BUFFERS, player->buffers);
92 assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
94 alGenSources(1, &player->source);
95 assert(alGetError() == AL_NO_ERROR && "Could not create source");
97 /* Set parameters so mono sources play out the front-center speaker and
98 * won't distance attenuate. */
99 alSource3i(player->source, AL_POSITION, 0, 0, -1);
100 alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE);
101 alSourcei(player->source, AL_ROLLOFF_FACTOR, 0);
102 assert(alGetError() == AL_NO_ERROR && "Could not set source parameters");
107 /* Destroys a player object, deleting the source and buffers. No error handling
108 * since these calls shouldn't fail with a properly-made player object. */
109 static void DeletePlayer(StreamPlayer *player)
111 ClosePlayerFile(player);
113 alDeleteSources(1, &player->source);
114 alDeleteBuffers(NUM_BUFFERS, player->buffers);
115 if(alGetError() != AL_NO_ERROR)
116 fprintf(stderr, "Failed to delete object IDs\n");
118 memset(player, 0, sizeof(*player));
123 /* Opens the first audio stream of the named file. If a file is already open,
124 * it will be closed first. */
125 static int OpenPlayerFile(StreamPlayer *player, const char *filename)
127 int byteblockalign=0, splblockalign=0;
129 ClosePlayerFile(player);
131 /* Open the audio file and check that it's usable. */
132 player->sndfile = sf_open(filename, SFM_READ, &player->sfinfo);
135 fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(NULL));
139 /* Detect a suitable format to load. Formats like Vorbis and Opus use float
140 * natively, so load as float to avoid clipping when possible. Formats
141 * larger than 16-bit can also use float to preserve a bit more precision.
143 switch((player->sfinfo.format&SF_FORMAT_SUBMASK))
145 case SF_FORMAT_PCM_24:
146 case SF_FORMAT_PCM_32:
147 case SF_FORMAT_FLOAT:
148 case SF_FORMAT_DOUBLE:
149 case SF_FORMAT_VORBIS:
151 case SF_FORMAT_ALAC_20:
152 case SF_FORMAT_ALAC_24:
153 case SF_FORMAT_ALAC_32:
154 case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
155 case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
156 case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
157 if(alIsExtensionPresent("AL_EXT_FLOAT32"))
158 player->sample_type = Float;
160 case SF_FORMAT_IMA_ADPCM:
161 /* ADPCM formats require setting a block alignment as specified in the
162 * file, which needs to be read from the wave 'fmt ' chunk manually
163 * since libsndfile doesn't provide it in a format-agnostic way.
165 if(player->sfinfo.channels <= 2
166 && (player->sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
167 && alIsExtensionPresent("AL_EXT_IMA4")
168 && alIsExtensionPresent("AL_SOFT_block_alignment"))
169 player->sample_type = IMA4;
171 case SF_FORMAT_MS_ADPCM:
172 if(player->sfinfo.channels <= 2
173 && (player->sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
174 && alIsExtensionPresent("AL_SOFT_MSADPCM")
175 && alIsExtensionPresent("AL_SOFT_block_alignment"))
176 player->sample_type = MSADPCM;
180 if(player->sample_type == IMA4 || player->sample_type == MSADPCM)
182 /* For ADPCM, lookup the wave file's "fmt " chunk, which is a
183 * WAVEFORMATEX-based structure for the audio format.
185 SF_CHUNK_INFO inf = { "fmt ", 4, 0, NULL };
186 SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(player->sndfile, &inf);
188 /* If there's an issue getting the chunk or block alignment, load as
189 * 16-bit and have libsndfile do the conversion.
191 if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
192 player->sample_type = Int16;
195 ALubyte *fmtbuf = calloc(inf.datalen, 1);
197 if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
198 player->sample_type = Int16;
201 /* Read the nBlockAlign field, and convert from bytes- to
202 * samples-per-block (verifying it's valid by converting back
203 * and comparing to the original value).
205 byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
206 if(player->sample_type == IMA4)
208 splblockalign = (byteblockalign/player->sfinfo.channels - 4)/4*8 + 1;
210 || ((splblockalign-1)/2 + 4)*player->sfinfo.channels != byteblockalign)
211 player->sample_type = Int16;
215 splblockalign = (byteblockalign/player->sfinfo.channels - 7)*2 + 2;
217 || ((splblockalign-2)/2 + 7)*player->sfinfo.channels != byteblockalign)
218 player->sample_type = Int16;
225 if(player->sample_type == Int16)
227 player->sampleblockalign = 1;
228 player->byteblockalign = player->sfinfo.channels * 2;
230 else if(player->sample_type == Float)
232 player->sampleblockalign = 1;
233 player->byteblockalign = player->sfinfo.channels * 4;
237 player->sampleblockalign = splblockalign;
238 player->byteblockalign = byteblockalign;
241 /* Figure out the OpenAL format from the file and desired sample type. */
242 player->format = AL_NONE;
243 if(player->sfinfo.channels == 1)
245 if(player->sample_type == Int16)
246 player->format = AL_FORMAT_MONO16;
247 else if(player->sample_type == Float)
248 player->format = AL_FORMAT_MONO_FLOAT32;
249 else if(player->sample_type == IMA4)
250 player->format = AL_FORMAT_MONO_IMA4;
251 else if(player->sample_type == MSADPCM)
252 player->format = AL_FORMAT_MONO_MSADPCM_SOFT;
254 else if(player->sfinfo.channels == 2)
256 if(player->sample_type == Int16)
257 player->format = AL_FORMAT_STEREO16;
258 else if(player->sample_type == Float)
259 player->format = AL_FORMAT_STEREO_FLOAT32;
260 else if(player->sample_type == IMA4)
261 player->format = AL_FORMAT_STEREO_IMA4;
262 else if(player->sample_type == MSADPCM)
263 player->format = AL_FORMAT_STEREO_MSADPCM_SOFT;
265 else if(player->sfinfo.channels == 3)
267 if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
269 if(player->sample_type == Int16)
270 player->format = AL_FORMAT_BFORMAT2D_16;
271 else if(player->sample_type == Float)
272 player->format = AL_FORMAT_BFORMAT2D_FLOAT32;
275 else if(player->sfinfo.channels == 4)
277 if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
279 if(player->sample_type == Int16)
280 player->format = AL_FORMAT_BFORMAT3D_16;
281 else if(player->sample_type == Float)
282 player->format = AL_FORMAT_BFORMAT3D_FLOAT32;
287 fprintf(stderr, "Unsupported channel count: %d\n", player->sfinfo.channels);
288 sf_close(player->sndfile);
289 player->sndfile = NULL;
293 player->block_count = player->sfinfo.samplerate / player->sampleblockalign;
294 player->block_count = player->block_count * BUFFER_MILLISEC / 1000;
295 player->membuf = malloc((size_t)(player->block_count * player->byteblockalign));
300 /* Closes the audio file stream */
301 static void ClosePlayerFile(StreamPlayer *player)
304 sf_close(player->sndfile);
305 player->sndfile = NULL;
307 free(player->membuf);
308 player->membuf = NULL;
310 if(player->sampleblockalign > 1)
313 for(i = 0;i < NUM_BUFFERS;i++)
314 alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT, 0);
315 player->sampleblockalign = 0;
316 player->byteblockalign = 0;
321 /* Prebuffers some audio from the file, and starts playing the source */
322 static int StartPlayer(StreamPlayer *player)
326 /* Rewind the source position and clear the buffer queue */
327 alSourceRewind(player->source);
328 alSourcei(player->source, AL_BUFFER, 0);
330 /* Fill the buffer queue */
331 for(i = 0;i < NUM_BUFFERS;i++)
335 /* Get some data to give it to the buffer */
336 if(player->sample_type == Int16)
338 slen = sf_readf_short(player->sndfile, player->membuf,
339 player->block_count * player->sampleblockalign);
341 slen *= player->byteblockalign;
343 else if(player->sample_type == Float)
345 slen = sf_readf_float(player->sndfile, player->membuf,
346 player->block_count * player->sampleblockalign);
348 slen *= player->byteblockalign;
352 slen = sf_read_raw(player->sndfile, player->membuf,
353 player->block_count * player->byteblockalign);
354 if(slen > 0) slen -= slen%player->byteblockalign;
358 if(player->sampleblockalign > 1)
359 alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT,
360 player->sampleblockalign);
362 alBufferData(player->buffers[i], player->format, player->membuf, (ALsizei)slen,
363 player->sfinfo.samplerate);
365 if(alGetError() != AL_NO_ERROR)
367 fprintf(stderr, "Error buffering for playback\n");
371 /* Now queue and start playback! */
372 alSourceQueueBuffers(player->source, i, player->buffers);
373 alSourcePlay(player->source);
374 if(alGetError() != AL_NO_ERROR)
376 fprintf(stderr, "Error starting playback\n");
383 static int UpdatePlayer(StreamPlayer *player)
385 ALint processed, state;
387 /* Get relevant source info */
388 alGetSourcei(player->source, AL_SOURCE_STATE, &state);
389 alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed);
390 if(alGetError() != AL_NO_ERROR)
392 fprintf(stderr, "Error checking source state\n");
396 /* Unqueue and handle each processed buffer */
402 alSourceUnqueueBuffers(player->source, 1, &bufid);
405 /* Read the next chunk of data, refill the buffer, and queue it
406 * back on the source */
407 if(player->sample_type == Int16)
409 slen = sf_readf_short(player->sndfile, player->membuf,
410 player->block_count * player->sampleblockalign);
411 if(slen > 0) slen *= player->byteblockalign;
413 else if(player->sample_type == Float)
415 slen = sf_readf_float(player->sndfile, player->membuf,
416 player->block_count * player->sampleblockalign);
417 if(slen > 0) slen *= player->byteblockalign;
421 slen = sf_read_raw(player->sndfile, player->membuf,
422 player->block_count * player->byteblockalign);
423 if(slen > 0) slen -= slen%player->byteblockalign;
428 alBufferData(bufid, player->format, player->membuf, (ALsizei)slen,
429 player->sfinfo.samplerate);
430 alSourceQueueBuffers(player->source, 1, &bufid);
432 if(alGetError() != AL_NO_ERROR)
434 fprintf(stderr, "Error buffering data\n");
439 /* Make sure the source hasn't underrun */
440 if(state != AL_PLAYING && state != AL_PAUSED)
444 /* If no buffers are queued, playback is finished */
445 alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
449 alSourcePlay(player->source);
450 if(alGetError() != AL_NO_ERROR)
452 fprintf(stderr, "Error restarting playback\n");
461 int main(int argc, char **argv)
463 StreamPlayer *player;
466 /* Print out usage if no arguments were specified */
469 fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
474 if(InitAL(&argv, &argc) != 0)
477 player = NewPlayer();
479 /* Play each file listed on the command line */
480 for(i = 0;i < argc;i++)
482 const char *namepart;
484 if(!OpenPlayerFile(player, argv[i]))
487 /* Get the name portion, without the path, for display. */
488 namepart = strrchr(argv[i], '/');
489 if(namepart || (namepart=strrchr(argv[i], '\\')))
494 printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
495 player->sfinfo.samplerate);
498 if(!StartPlayer(player))
500 ClosePlayerFile(player);
504 while(UpdatePlayer(player))
505 al_nssleep(10000000);
507 /* All done with this file. Close it and go to the next */
508 ClosePlayerFile(player);
512 /* All files done. Delete the player, and close down OpenAL */
513 DeletePlayer(player);