Set the proper block align for callback buffers
[openal-soft.git] / examples / alplay.c
blobe1b7c5f03a8cabd0261737da3b9f827b8b42a583
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"
41 enum FormatType {
42 Int16,
43 Float,
44 IMA4,
45 MSADPCM
48 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
49 * returns the new buffer ID.
51 static ALuint LoadSound(const char *filename)
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;
64 /* Open the audio file and check that it's usable. */
65 sndfile = sf_open(filename, SFM_READ, &sfinfo);
66 if(!sndfile)
68 fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile));
69 return 0;
71 if(sfinfo.frames < 1)
73 fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames);
74 sf_close(sndfile);
75 return 0;
78 /* Detect a suitable format to load. Formats like Vorbis and Opus use float
79 * natively, so load as float to avoid clipping. Formats larger than 16-bit
80 * can also use float to preserve a bit more precision.
82 switch((sfinfo.format&SF_FORMAT_SUBMASK))
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_MPEG_LAYER_I:
91 case SF_FORMAT_MPEG_LAYER_II:
92 case SF_FORMAT_MPEG_LAYER_III:
93 if(alIsExtensionPresent("AL_EXT_FLOAT32"))
94 sample_format = Float;
95 break;
96 case SF_FORMAT_IMA_ADPCM:
97 /* ADPCM formats require setting a block alignment, which libsndfile
98 * doesn't explicitly provide and needs to be read from the wave 'fmt '
99 * chunk manually.
101 if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
102 && alIsExtensionPresent("AL_EXT_IMA4")
103 && alIsExtensionPresent("AL_SOFT_block_alignment"))
104 sample_format = IMA4;
105 break;
106 case SF_FORMAT_MS_ADPCM:
107 if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
108 && alIsExtensionPresent("AL_SOFT_MSADPCM")
109 && alIsExtensionPresent("AL_SOFT_block_alignment"))
110 sample_format = MSADPCM;
111 break;
114 if(sample_format == IMA4 || sample_format == MSADPCM)
116 SF_CHUNK_INFO inf = { "fmt ", 4, 0, NULL };
117 SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(sndfile, &inf);
118 if(iter)
120 if(sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR)
121 iter = NULL;
122 else
124 ALubyte *fmtbuf = calloc(inf.datalen, 1);
125 inf.data = fmtbuf;
126 if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
127 iter = NULL;
128 else
130 /* Read the nBlockAlign field, and convert from bytes- to
131 * samples-per-block (verifying it's valid by converting
132 * back and comparing to the original value).
134 byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
135 if(sample_format == IMA4)
137 splblockalign = (byteblockalign/sfinfo.channels - 4)/4*8 + 1;
138 if(((splblockalign-1)/2 + 4)*sfinfo.channels != byteblockalign)
139 iter = NULL;
141 else
143 splblockalign = (byteblockalign/sfinfo.channels - 7)*2 + 2;
144 if(((splblockalign-2)/2 + 7)*sfinfo.channels != byteblockalign)
145 iter = NULL;
148 free(fmtbuf);
152 /* If there was an issue getting the block alignment, have libsndfile
153 * do the conversion and load as 16-bit.
155 if(!iter)
156 sample_format = Int16;
159 if(sample_format == Int16)
161 splblockalign = 1;
162 byteblockalign = sfinfo.channels * 2;
164 else if(sample_format == Float)
166 splblockalign = 1;
167 byteblockalign = sfinfo.channels * 4;
170 /* Get the sound format, and figure out the OpenAL format */
171 format = AL_NONE;
172 if(sfinfo.channels == 1)
174 if(sample_format == Int16)
175 format = AL_FORMAT_MONO16;
176 else if(sample_format == Float)
177 format = AL_FORMAT_MONO_FLOAT32;
178 else if(sample_format == IMA4)
179 format = AL_FORMAT_MONO_IMA4;
180 else if(sample_format == MSADPCM)
181 format = AL_FORMAT_MONO_MSADPCM_SOFT;
183 else if(sfinfo.channels == 2)
185 if(sample_format == Int16)
186 format = AL_FORMAT_STEREO16;
187 else if(sample_format == Float)
188 format = AL_FORMAT_STEREO_FLOAT32;
189 else if(sample_format == IMA4)
190 format = AL_FORMAT_STEREO_IMA4;
191 else if(sample_format == MSADPCM)
192 format = AL_FORMAT_STEREO_MSADPCM_SOFT;
194 else if(sfinfo.channels == 3)
196 if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
198 if(sample_format == Int16)
199 format = AL_FORMAT_BFORMAT2D_16;
200 else if(sample_format == Float)
201 format = AL_FORMAT_BFORMAT2D_FLOAT32;
204 else if(sfinfo.channels == 4)
206 if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
208 if(sample_format == Int16)
209 format = AL_FORMAT_BFORMAT3D_16;
210 else if(sample_format == Float)
211 format = AL_FORMAT_BFORMAT3D_FLOAT32;
214 if(!format)
216 fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels);
217 sf_close(sndfile);
218 return 0;
221 if(sfinfo.frames/splblockalign > (sf_count_t)(INT_MAX/byteblockalign))
223 fprintf(stderr, "Too many samples in %s (%" PRId64 ")\n", filename, sfinfo.frames);
224 sf_close(sndfile);
225 return 0;
228 /* Decode the whole audio file to a buffer. */
229 membuf = malloc((size_t)(sfinfo.frames / splblockalign * byteblockalign));
231 if(sample_format == Int16)
232 num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames);
233 else if(sample_format == Float)
234 num_frames = sf_readf_float(sndfile, membuf, sfinfo.frames);
235 else
237 sf_count_t count = sfinfo.frames / splblockalign * byteblockalign;
238 num_frames = sf_read_raw(sndfile, membuf, count);
239 if(num_frames > 0)
240 num_frames = num_frames / byteblockalign * splblockalign;
242 if(num_frames < 1)
244 free(membuf);
245 sf_close(sndfile);
246 fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames);
247 return 0;
249 num_bytes = (ALsizei)(num_frames / splblockalign * byteblockalign);
251 printf("Loading: %s (%s, %dhz)\n", filename, FormatName(format), sfinfo.samplerate);
252 fflush(stdout);
254 /* Buffer the audio data into a new buffer object, then free the data and
255 * close the file.
257 buffer = 0;
258 alGenBuffers(1, &buffer);
259 if(splblockalign > 1)
260 alBufferi(buffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, splblockalign);
261 alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate);
263 free(membuf);
264 sf_close(sndfile);
266 /* Check if an error occured, and clean up if so. */
267 err = alGetError();
268 if(err != AL_NO_ERROR)
270 fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
271 if(buffer && alIsBuffer(buffer))
272 alDeleteBuffers(1, &buffer);
273 return 0;
276 return buffer;
280 int main(int argc, char **argv)
282 ALuint source, buffer;
283 ALfloat offset;
284 ALenum state;
286 /* Print out usage if no arguments were specified */
287 if(argc < 2)
289 fprintf(stderr, "Usage: %s [-device <name>] <filename>\n", argv[0]);
290 return 1;
293 /* Initialize OpenAL. */
294 argv++; argc--;
295 if(InitAL(&argv, &argc) != 0)
296 return 1;
298 /* Load the sound into a buffer. */
299 buffer = LoadSound(argv[0]);
300 if(!buffer)
302 CloseAL();
303 return 1;
306 /* Create the source to play the sound with. */
307 source = 0;
308 alGenSources(1, &source);
309 alSourcei(source, AL_BUFFER, (ALint)buffer);
310 assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
312 /* Play the sound until it finishes. */
313 alSourcePlay(source);
314 do {
315 al_nssleep(10000000);
316 alGetSourcei(source, AL_SOURCE_STATE, &state);
318 /* Get the source offset. */
319 alGetSourcef(source, AL_SEC_OFFSET, &offset);
320 printf("\rOffset: %f ", offset);
321 fflush(stdout);
322 } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
323 printf("\n");
325 /* All done. Delete resources, and close down OpenAL. */
326 alDeleteSources(1, &source);
327 alDeleteBuffers(1, &buffer);
329 CloseAL();
331 return 0;