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