]> git.tdb.fi Git - ext/openal.git/blob - examples/alstream.c
Tweak some types to work around an MSVC compile error
[ext/openal.git] / examples / alstream.c
1 /*
2  * OpenAL Audio Stream Example
3  *
4  * Copyright (c) 2011 by Chris Robinson <chris.kcat@gmail.com>
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
25 /* This file contains a relatively simple streaming audio player. */
26
27 #include <assert.h>
28 #include <inttypes.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #include "sndfile.h"
34
35 #include "AL/al.h"
36 #include "AL/alext.h"
37
38 #include "common/alhelpers.h"
39
40
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.
44  */
45 #define NUM_BUFFERS 4
46 #define BUFFER_MILLISEC 200
47
48 typedef enum SampleType {
49     Int16, Float, IMA4, MSADPCM
50 } SampleType;
51
52 typedef struct StreamPlayer {
53     /* These are the buffers and source to play out through OpenAL with. */
54     ALuint buffers[NUM_BUFFERS];
55     ALuint source;
56
57     /* Handle for the audio file */
58     SNDFILE *sndfile;
59     SF_INFO sfinfo;
60     void *membuf;
61
62     /* The sample type and block/frame size being read for the buffer. */
63     SampleType sample_type;
64     int byteblockalign;
65     int sampleblockalign;
66     int block_count;
67
68     /* The format of the output stream (sample rate is in sfinfo) */
69     ALenum format;
70 } StreamPlayer;
71
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);
78
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.
82  */
83 static StreamPlayer *NewPlayer(void)
84 {
85     StreamPlayer *player;
86
87     player = calloc(1, sizeof(*player));
88     assert(player != NULL);
89
90     /* Generate the buffers and source */
91     alGenBuffers(NUM_BUFFERS, player->buffers);
92     assert(alGetError() == AL_NO_ERROR && "Could not create buffers");
93
94     alGenSources(1, &player->source);
95     assert(alGetError() == AL_NO_ERROR && "Could not create source");
96
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");
103
104     return player;
105 }
106
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)
110 {
111     ClosePlayerFile(player);
112
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");
117
118     memset(player, 0, sizeof(*player));
119     free(player);
120 }
121
122
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)
126 {
127     int byteblockalign=0, splblockalign=0;
128
129     ClosePlayerFile(player);
130
131     /* Open the audio file and check that it's usable. */
132     player->sndfile = sf_open(filename, SFM_READ, &player->sfinfo);
133     if(!player->sndfile)
134     {
135         fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(NULL));
136         return 0;
137     }
138
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.
142      */
143     switch((player->sfinfo.format&SF_FORMAT_SUBMASK))
144     {
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:
150     case SF_FORMAT_OPUS:
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;
159         break;
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.
164          */
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;
170         break;
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;
177         break;
178     }
179
180     if(player->sample_type == IMA4 || player->sample_type == MSADPCM)
181     {
182         /* For ADPCM, lookup the wave file's "fmt " chunk, which is a
183          * WAVEFORMATEX-based structure for the audio format.
184          */
185         SF_CHUNK_INFO inf = { "fmt ", 4, 0, NULL };
186         SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(player->sndfile, &inf);
187
188         /* If there's an issue getting the chunk or block alignment, load as
189          * 16-bit and have libsndfile do the conversion.
190          */
191         if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
192             player->sample_type = Int16;
193         else
194         {
195             ALubyte *fmtbuf = calloc(inf.datalen, 1);
196             inf.data = fmtbuf;
197             if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
198                 player->sample_type = Int16;
199             else
200             {
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).
204                  */
205                 byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
206                 if(player->sample_type == IMA4)
207                 {
208                     splblockalign = (byteblockalign/player->sfinfo.channels - 4)/4*8 + 1;
209                     if(splblockalign < 1
210                         || ((splblockalign-1)/2 + 4)*player->sfinfo.channels != byteblockalign)
211                         player->sample_type = Int16;
212                 }
213                 else
214                 {
215                     splblockalign = (byteblockalign/player->sfinfo.channels - 7)*2 + 2;
216                     if(splblockalign < 2
217                         || ((splblockalign-2)/2 + 7)*player->sfinfo.channels != byteblockalign)
218                         player->sample_type = Int16;
219                 }
220             }
221             free(fmtbuf);
222         }
223     }
224
225     if(player->sample_type == Int16)
226     {
227         player->sampleblockalign = 1;
228         player->byteblockalign = player->sfinfo.channels * 2;
229     }
230     else if(player->sample_type == Float)
231     {
232         player->sampleblockalign = 1;
233         player->byteblockalign = player->sfinfo.channels * 4;
234     }
235     else
236     {
237         player->sampleblockalign = splblockalign;
238         player->byteblockalign = byteblockalign;
239     }
240
241     /* Figure out the OpenAL format from the file and desired sample type. */
242     player->format = AL_NONE;
243     if(player->sfinfo.channels == 1)
244     {
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;
253     }
254     else if(player->sfinfo.channels == 2)
255     {
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;
264     }
265     else if(player->sfinfo.channels == 3)
266     {
267         if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
268         {
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;
273         }
274     }
275     else if(player->sfinfo.channels == 4)
276     {
277         if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
278         {
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;
283         }
284     }
285     if(!player->format)
286     {
287         fprintf(stderr, "Unsupported channel count: %d\n", player->sfinfo.channels);
288         sf_close(player->sndfile);
289         player->sndfile = NULL;
290         return 0;
291     }
292
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));
296
297     return 1;
298 }
299
300 /* Closes the audio file stream */
301 static void ClosePlayerFile(StreamPlayer *player)
302 {
303     if(player->sndfile)
304         sf_close(player->sndfile);
305     player->sndfile = NULL;
306
307     free(player->membuf);
308     player->membuf = NULL;
309
310     if(player->sampleblockalign > 1)
311     {
312         ALsizei i;
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;
317     }
318 }
319
320
321 /* Prebuffers some audio from the file, and starts playing the source */
322 static int StartPlayer(StreamPlayer *player)
323 {
324     ALsizei i;
325
326     /* Rewind the source position and clear the buffer queue */
327     alSourceRewind(player->source);
328     alSourcei(player->source, AL_BUFFER, 0);
329
330     /* Fill the buffer queue */
331     for(i = 0;i < NUM_BUFFERS;i++)
332     {
333         sf_count_t slen;
334
335         /* Get some data to give it to the buffer */
336         if(player->sample_type == Int16)
337         {
338             slen = sf_readf_short(player->sndfile, player->membuf,
339                 player->block_count * player->sampleblockalign);
340             if(slen < 1) break;
341             slen *= player->byteblockalign;
342         }
343         else if(player->sample_type == Float)
344         {
345             slen = sf_readf_float(player->sndfile, player->membuf,
346                 player->block_count * player->sampleblockalign);
347             if(slen < 1) break;
348             slen *= player->byteblockalign;
349         }
350         else
351         {
352             slen = sf_read_raw(player->sndfile, player->membuf,
353                 player->block_count * player->byteblockalign);
354             if(slen > 0) slen -= slen%player->byteblockalign;
355             if(slen < 1) break;
356         }
357
358         if(player->sampleblockalign > 1)
359             alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT,
360                 player->sampleblockalign);
361
362         alBufferData(player->buffers[i], player->format, player->membuf, (ALsizei)slen,
363             player->sfinfo.samplerate);
364     }
365     if(alGetError() != AL_NO_ERROR)
366     {
367         fprintf(stderr, "Error buffering for playback\n");
368         return 0;
369     }
370
371     /* Now queue and start playback! */
372     alSourceQueueBuffers(player->source, i, player->buffers);
373     alSourcePlay(player->source);
374     if(alGetError() != AL_NO_ERROR)
375     {
376         fprintf(stderr, "Error starting playback\n");
377         return 0;
378     }
379
380     return 1;
381 }
382
383 static int UpdatePlayer(StreamPlayer *player)
384 {
385     ALint processed, state;
386
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)
391     {
392         fprintf(stderr, "Error checking source state\n");
393         return 0;
394     }
395
396     /* Unqueue and handle each processed buffer */
397     while(processed > 0)
398     {
399         ALuint bufid;
400         sf_count_t slen;
401
402         alSourceUnqueueBuffers(player->source, 1, &bufid);
403         processed--;
404
405         /* Read the next chunk of data, refill the buffer, and queue it
406          * back on the source */
407         if(player->sample_type == Int16)
408         {
409             slen = sf_readf_short(player->sndfile, player->membuf,
410                 player->block_count * player->sampleblockalign);
411             if(slen > 0) slen *= player->byteblockalign;
412         }
413         else if(player->sample_type == Float)
414         {
415             slen = sf_readf_float(player->sndfile, player->membuf,
416                 player->block_count * player->sampleblockalign);
417             if(slen > 0) slen *= player->byteblockalign;
418         }
419         else
420         {
421             slen = sf_read_raw(player->sndfile, player->membuf,
422                 player->block_count * player->byteblockalign);
423             if(slen > 0) slen -= slen%player->byteblockalign;
424         }
425
426         if(slen > 0)
427         {
428             alBufferData(bufid, player->format, player->membuf, (ALsizei)slen,
429                 player->sfinfo.samplerate);
430             alSourceQueueBuffers(player->source, 1, &bufid);
431         }
432         if(alGetError() != AL_NO_ERROR)
433         {
434             fprintf(stderr, "Error buffering data\n");
435             return 0;
436         }
437     }
438
439     /* Make sure the source hasn't underrun */
440     if(state != AL_PLAYING && state != AL_PAUSED)
441     {
442         ALint queued;
443
444         /* If no buffers are queued, playback is finished */
445         alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
446         if(queued == 0)
447             return 0;
448
449         alSourcePlay(player->source);
450         if(alGetError() != AL_NO_ERROR)
451         {
452             fprintf(stderr, "Error restarting playback\n");
453             return 0;
454         }
455     }
456
457     return 1;
458 }
459
460
461 int main(int argc, char **argv)
462 {
463     StreamPlayer *player;
464     int i;
465
466     /* Print out usage if no arguments were specified */
467     if(argc < 2)
468     {
469         fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
470         return 1;
471     }
472
473     argv++; argc--;
474     if(InitAL(&argv, &argc) != 0)
475         return 1;
476
477     player = NewPlayer();
478
479     /* Play each file listed on the command line */
480     for(i = 0;i < argc;i++)
481     {
482         const char *namepart;
483
484         if(!OpenPlayerFile(player, argv[i]))
485             continue;
486
487         /* Get the name portion, without the path, for display. */
488         namepart = strrchr(argv[i], '/');
489         if(namepart || (namepart=strrchr(argv[i], '\\')))
490             namepart++;
491         else
492             namepart = argv[i];
493
494         printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
495             player->sfinfo.samplerate);
496         fflush(stdout);
497
498         if(!StartPlayer(player))
499         {
500             ClosePlayerFile(player);
501             continue;
502         }
503
504         while(UpdatePlayer(player))
505             al_nssleep(10000000);
506
507         /* All done with this file. Close it and go to the next */
508         ClosePlayerFile(player);
509     }
510     printf("Done.\n");
511
512     /* All files done. Delete the player, and close down OpenAL */
513     DeletePlayer(player);
514     player = NULL;
515
516     CloseAL();
517
518     return 0;
519 }