]> git.tdb.fi Git - ext/openal.git/blob - examples/alplay.c
Tweak some types to work around an MSVC compile error
[ext/openal.git] / examples / alplay.c
1 /*
2  * OpenAL Source Play Example
3  *
4  * Copyright (c) 2017 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 an example for playing a sound buffer. */
26
27 #include <assert.h>
28 #include <inttypes.h>
29 #include <limits.h>
30 #include <stdio.h>
31 #include <stdlib.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 enum FormatType {
42     Int16,
43     Float,
44     IMA4,
45     MSADPCM
46 };
47
48 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
49  * returns the new buffer ID.
50  */
51 static ALuint LoadSound(const char *filename)
52 {
53     enum FormatType sample_format = Int16;
54     ALint byteblockalign = 0;
55     ALint splblockalign = 0;
56     sf_count_t num_frames;
57     ALenum err, format;
58     ALsizei num_bytes;
59     SNDFILE *sndfile;
60     SF_INFO sfinfo;
61     ALuint buffer;
62     void *membuf;
63
64     /* Open the audio file and check that it's usable. */
65     sndfile = sf_open(filename, SFM_READ, &sfinfo);
66     if(!sndfile)
67     {
68         fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
69         return 0;
70     }
71     if(sfinfo.frames < 1)
72     {
73         fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
74         sf_close(sndfile);
75         return 0;
76     }
77
78     /* Detect a suitable format to load. Formats like Vorbis and Opus use float
79      * natively, so load as float to avoid clipping when possible. Formats
80      * larger than 16-bit can also use float to preserve a bit more precision.
81      */
82     switch((sfinfo.format&SF_FORMAT_SUBMASK))
83     {
84     case SF_FORMAT_PCM_24:
85     case SF_FORMAT_PCM_32:
86     case SF_FORMAT_FLOAT:
87     case SF_FORMAT_DOUBLE:
88     case SF_FORMAT_VORBIS:
89     case SF_FORMAT_OPUS:
90     case SF_FORMAT_ALAC_20:
91     case SF_FORMAT_ALAC_24:
92     case SF_FORMAT_ALAC_32:
93     case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
94     case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
95     case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
96         if(alIsExtensionPresent("AL_EXT_FLOAT32"))
97             sample_format = Float;
98         break;
99     case SF_FORMAT_IMA_ADPCM:
100         /* ADPCM formats require setting a block alignment as specified in the
101          * file, which needs to be read from the wave 'fmt ' chunk manually
102          * since libsndfile doesn't provide it in a format-agnostic way.
103          */
104         if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
105             && alIsExtensionPresent("AL_EXT_IMA4")
106             && alIsExtensionPresent("AL_SOFT_block_alignment"))
107             sample_format = IMA4;
108         break;
109     case SF_FORMAT_MS_ADPCM:
110         if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
111             && alIsExtensionPresent("AL_SOFT_MSADPCM")
112             && alIsExtensionPresent("AL_SOFT_block_alignment"))
113             sample_format = MSADPCM;
114         break;
115     }
116
117     if(sample_format == IMA4 || sample_format == MSADPCM)
118     {
119         /* For ADPCM, lookup the wave file's "fmt " chunk, which is a
120          * WAVEFORMATEX-based structure for the audio format.
121          */
122         SF_CHUNK_INFO inf = { "fmt ", 4, 0, NULL };
123         SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(sndfile, &inf);
124
125         /* If there's an issue getting the chunk or block alignment, load as
126          * 16-bit and have libsndfile do the conversion.
127          */
128         if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
129             sample_format = Int16;
130         else
131         {
132             ALubyte *fmtbuf = calloc(inf.datalen, 1);
133             inf.data = fmtbuf;
134             if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
135                 sample_format = Int16;
136             else
137             {
138                 /* Read the nBlockAlign field, and convert from bytes- to
139                  * samples-per-block (verifying it's valid by converting back
140                  * and comparing to the original value).
141                  */
142                 byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
143                 if(sample_format == IMA4)
144                 {
145                     splblockalign = (byteblockalign/sfinfo.channels - 4)/4*8 + 1;
146                     if(splblockalign < 1
147                         || ((splblockalign-1)/2 + 4)*sfinfo.channels != byteblockalign)
148                         sample_format = Int16;
149                 }
150                 else
151                 {
152                     splblockalign = (byteblockalign/sfinfo.channels - 7)*2 + 2;
153                     if(splblockalign < 2
154                         || ((splblockalign-2)/2 + 7)*sfinfo.channels != byteblockalign)
155                         sample_format = Int16;
156                 }
157             }
158             free(fmtbuf);
159         }
160     }
161
162     if(sample_format == Int16)
163     {
164         splblockalign = 1;
165         byteblockalign = sfinfo.channels * 2;
166     }
167     else if(sample_format == Float)
168     {
169         splblockalign = 1;
170         byteblockalign = sfinfo.channels * 4;
171     }
172
173     /* Figure out the OpenAL format from the file and desired sample type. */
174     format = AL_NONE;
175     if(sfinfo.channels == 1)
176     {
177         if(sample_format == Int16)
178             format = AL_FORMAT_MONO16;
179         else if(sample_format == Float)
180             format = AL_FORMAT_MONO_FLOAT32;
181         else if(sample_format == IMA4)
182             format = AL_FORMAT_MONO_IMA4;
183         else if(sample_format == MSADPCM)
184             format = AL_FORMAT_MONO_MSADPCM_SOFT;
185     }
186     else if(sfinfo.channels == 2)
187     {
188         if(sample_format == Int16)
189             format = AL_FORMAT_STEREO16;
190         else if(sample_format == Float)
191             format = AL_FORMAT_STEREO_FLOAT32;
192         else if(sample_format == IMA4)
193             format = AL_FORMAT_STEREO_IMA4;
194         else if(sample_format == MSADPCM)
195             format = AL_FORMAT_STEREO_MSADPCM_SOFT;
196     }
197     else if(sfinfo.channels == 3)
198     {
199         if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
200         {
201             if(sample_format == Int16)
202                 format = AL_FORMAT_BFORMAT2D_16;
203             else if(sample_format == Float)
204                 format = AL_FORMAT_BFORMAT2D_FLOAT32;
205         }
206     }
207     else if(sfinfo.channels == 4)
208     {
209         if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
210         {
211             if(sample_format == Int16)
212                 format = AL_FORMAT_BFORMAT3D_16;
213             else if(sample_format == Float)
214                 format = AL_FORMAT_BFORMAT3D_FLOAT32;
215         }
216     }
217     if(!format)
218     {
219         fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
220         sf_close(sndfile);
221         return 0;
222     }
223
224     if(sfinfo.frames/splblockalign > (sf_count_t)(INT_MAX/byteblockalign))
225     {
226         fprintf(stderr, "Too many samples in %s (%" PRId64 ")\n", filename, sfinfo.frames);
227         sf_close(sndfile);
228         return 0;
229     }
230
231     /* Decode the whole audio file to a buffer. */
232     membuf = malloc((size_t)(sfinfo.frames / splblockalign * byteblockalign));
233
234     if(sample_format == Int16)
235         num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
236     else if(sample_format == Float)
237         num_frames = sf_readf_float(sndfile, membuf, sfinfo.frames);
238     else
239     {
240         sf_count_t count = sfinfo.frames / splblockalign * byteblockalign;
241         num_frames = sf_read_raw(sndfile, membuf, count);
242         if(num_frames > 0)
243             num_frames = num_frames / byteblockalign * splblockalign;
244     }
245     if(num_frames < 1)
246     {
247         free(membuf);
248         sf_close(sndfile);
249         fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
250         return 0;
251     }
252     num_bytes = (ALsizei)(num_frames / splblockalign * byteblockalign);
253
254     printf("Loading: %s (%s, %dhz)\n", filename, FormatName(format), sfinfo.samplerate);
255     fflush(stdout);
256
257     /* Buffer the audio data into a new buffer object, then free the data and
258      * close the file.
259      */
260     buffer = 0;
261     alGenBuffers(1, &buffer);
262     if(splblockalign > 1)
263         alBufferi(buffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, splblockalign);
264     alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
265
266     free(membuf);
267     sf_close(sndfile);
268
269     /* Check if an error occured, and clean up if so. */
270     err = alGetError();
271     if(err != AL_NO_ERROR)
272     {
273         fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
274         if(buffer && alIsBuffer(buffer))
275             alDeleteBuffers(1, &buffer);
276         return 0;
277     }
278
279     return buffer;
280 }
281
282
283 int main(int argc, char **argv)
284 {
285     ALuint source, buffer;
286     ALfloat offset;
287     ALenum state;
288
289     /* Print out usage if no arguments were specified */
290     if(argc < 2)
291     {
292         fprintf(stderr, "Usage: %s [-device <name>] <filename>\n", argv[0]);
293         return 1;
294     }
295
296     /* Initialize OpenAL. */
297     argv++; argc--;
298     if(InitAL(&argv, &argc) != 0)
299         return 1;
300
301     /* Load the sound into a buffer. */
302     buffer = LoadSound(argv[0]);
303     if(!buffer)
304     {
305         CloseAL();
306         return 1;
307     }
308
309     /* Create the source to play the sound with. */
310     source = 0;
311     alGenSources(1, &source);
312     alSourcei(source, AL_BUFFER, (ALint)buffer);
313     assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
314
315     /* Play the sound until it finishes. */
316     alSourcePlay(source);
317     do {
318         al_nssleep(10000000);
319         alGetSourcei(source, AL_SOURCE_STATE, &state);
320
321         /* Get the source offset. */
322         alGetSourcef(source, AL_SEC_OFFSET, &offset);
323         printf("\rOffset: %f  ", offset);
324         fflush(stdout);
325     } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
326     printf("\n");
327
328     /* All done. Delete resources, and close down OpenAL. */
329     alDeleteSources(1, &source);
330     alDeleteBuffers(1, &buffer);
331
332     CloseAL();
333
334     return 0;
335 }