Add a whitenoise generator to altonegen
[openal-soft.git] / examples / altonegen.c
blob628e695de835412cfb0de12a448e6501e28c7b10
1 /*
2 * OpenAL Tone Generator Test
4 * Copyright (c) 2015 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 a test for generating waveforms and plays them for a
26 * given length of time. Intended to inspect the behavior of the mixer by
27 * checking the output with a spectrum analyzer and oscilloscope.
29 * TODO: This would actually be nicer as a GUI app with buttons to start and
30 * stop individual waveforms, include additional whitenoise and pinknoise
31 * generators, and have the ability to hook up EFX filters and effects.
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <assert.h>
38 #include <limits.h>
39 #include <math.h>
41 #include "AL/al.h"
42 #include "AL/alc.h"
43 #include "AL/alext.h"
45 #include "common/alhelpers.h"
47 #ifndef M_PI
48 #define M_PI (3.14159265358979323846)
49 #endif
51 enum WaveType {
52 WT_Sine,
53 WT_Square,
54 WT_Sawtooth,
55 WT_Triangle,
56 WT_Impulse,
57 WT_WhiteNoise,
60 static const char *GetWaveTypeName(enum WaveType type)
62 switch(type)
64 case WT_Sine: return "sine";
65 case WT_Square: return "square";
66 case WT_Sawtooth: return "sawtooth";
67 case WT_Triangle: return "triangle";
68 case WT_Impulse: return "impulse";
69 case WT_WhiteNoise: return "noise";
71 return "(unknown)";
74 static inline ALuint dither_rng(ALuint *seed)
76 *seed = (*seed * 96314165) + 907633515;
77 return *seed;
80 static void ApplySin(ALfloat *data, ALdouble g, ALuint srate, ALuint freq)
82 ALdouble smps_per_cycle = (ALdouble)srate / freq;
83 ALuint i;
84 for(i = 0;i < srate;i++)
85 data[i] += (ALfloat)(sin(i/smps_per_cycle * 2.0*M_PI) * g);
88 /* Generates waveforms using additive synthesis. Each waveform is constructed
89 * by summing one or more sine waves, up to (and excluding) nyquist.
91 static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate)
93 ALuint seed = 22222;
94 ALint data_size;
95 ALfloat *data;
96 ALuint buffer;
97 ALenum err;
98 ALuint i;
100 data_size = srate * sizeof(ALfloat);
101 data = calloc(1, data_size);
102 switch(type)
104 case WT_Sine:
105 ApplySin(data, 1.0, srate, freq);
106 break;
107 case WT_Square:
108 for(i = 1;freq*i < srate/2;i+=2)
109 ApplySin(data, 4.0/M_PI * 1.0/i, srate, freq*i);
110 break;
111 case WT_Sawtooth:
112 for(i = 1;freq*i < srate/2;i++)
113 ApplySin(data, 2.0/M_PI * ((i&1)*2 - 1.0) / i, srate, freq*i);
114 break;
115 case WT_Triangle:
116 for(i = 1;freq*i < srate/2;i+=2)
117 ApplySin(data, 8.0/(M_PI*M_PI) * (1.0 - (i&2)) / (i*i), srate, freq*i);
118 break;
119 case WT_Impulse:
120 /* NOTE: Impulse isn't handled using additive synthesis, and is
121 * instead just a non-0 sample at a given rate. This can still be
122 * useful to test (other than resampling, the ALSOFT_DEFAULT_REVERB
123 * environment variable can prove useful here to test the reverb
124 * response).
126 for(i = 0;i < srate;i++)
127 data[i] = (i%(srate/freq)) ? 0.0f : 1.0f;
128 break;
129 case WT_WhiteNoise:
130 /* NOTE: WhiteNoise is just uniform set of uncorrelated values, and
131 * is not influenced by the waveform frequency.
133 for(i = 0;i < srate;i++)
135 ALuint rng0 = dither_rng(&seed);
136 ALuint rng1 = dither_rng(&seed);
137 data[i] = (ALfloat)(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
139 break;
142 /* Buffer the audio data into a new buffer object. */
143 buffer = 0;
144 alGenBuffers(1, &buffer);
145 alBufferData(buffer, AL_FORMAT_MONO_FLOAT32, data, data_size, srate);
146 free(data);
148 /* Check if an error occured, and clean up if so. */
149 err = alGetError();
150 if(err != AL_NO_ERROR)
152 fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
153 if(alIsBuffer(buffer))
154 alDeleteBuffers(1, &buffer);
155 return 0;
158 return buffer;
162 int main(int argc, char *argv[])
164 enum WaveType wavetype = WT_Sine;
165 const char *appname = argv[0];
166 ALuint source, buffer;
167 ALint last_pos, num_loops;
168 ALint max_loops = 4;
169 ALint srate = -1;
170 ALint tone_freq = 1000;
171 ALCint dev_rate;
172 ALenum state;
173 int i;
175 argv++; argc--;
176 if(InitAL(&argv, &argc) != 0)
177 return 1;
179 if(!alIsExtensionPresent("AL_EXT_FLOAT32"))
181 fprintf(stderr, "Required AL_EXT_FLOAT32 extension not supported on this device!\n");
182 CloseAL();
183 return 1;
186 for(i = 0;i < argc;i++)
188 if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)
190 fprintf(stderr, "OpenAL Tone Generator\n"
191 "\n"
192 "Usage: %s [-device <name>] <options>\n"
193 "\n"
194 "Available options:\n"
195 " --help/-h This help text\n"
196 " -t <seconds> Time to play a tone (default 5 seconds)\n"
197 " --waveform/-w <type> Waveform type: sine (default), square, sawtooth,\n"
198 " triangle, impulse, noise\n"
199 " --freq/-f <hz> Tone frequency (default 1000 hz)\n"
200 " --srate/-s <sample rate> Sampling rate (default output rate)\n",
201 appname
203 CloseAL();
204 return 1;
206 else if(i+1 < argc && strcmp(argv[i], "-t") == 0)
208 i++;
209 max_loops = atoi(argv[i]) - 1;
211 else if(i+1 < argc && (strcmp(argv[i], "--waveform") == 0 || strcmp(argv[i], "-w") == 0))
213 i++;
214 if(strcmp(argv[i], "sine") == 0)
215 wavetype = WT_Sine;
216 else if(strcmp(argv[i], "square") == 0)
217 wavetype = WT_Square;
218 else if(strcmp(argv[i], "sawtooth") == 0)
219 wavetype = WT_Sawtooth;
220 else if(strcmp(argv[i], "triangle") == 0)
221 wavetype = WT_Triangle;
222 else if(strcmp(argv[i], "impulse") == 0)
223 wavetype = WT_Impulse;
224 else if(strcmp(argv[i], "noise") == 0)
225 wavetype = WT_WhiteNoise;
226 else
227 fprintf(stderr, "Unhandled waveform: %s\n", argv[i]);
229 else if(i+1 < argc && (strcmp(argv[i], "--freq") == 0 || strcmp(argv[i], "-f") == 0))
231 i++;
232 tone_freq = atoi(argv[i]);
233 if(tone_freq < 1)
235 fprintf(stderr, "Invalid tone frequency: %s (min: 1hz)\n", argv[i]);
236 tone_freq = 1;
239 else if(i+1 < argc && (strcmp(argv[i], "--srate") == 0 || strcmp(argv[i], "-s") == 0))
241 i++;
242 srate = atoi(argv[i]);
243 if(srate < 40)
245 fprintf(stderr, "Invalid sample rate: %s (min: 40hz)\n", argv[i]);
246 srate = 40;
252 ALCdevice *device = alcGetContextsDevice(alcGetCurrentContext());
253 alcGetIntegerv(device, ALC_FREQUENCY, 1, &dev_rate);
254 assert(alcGetError(device)==ALC_NO_ERROR && "Failed to get device sample rate");
256 if(srate < 0)
257 srate = dev_rate;
259 /* Load the sound into a buffer. */
260 buffer = CreateWave(wavetype, tone_freq, srate);
261 if(!buffer)
263 CloseAL();
264 return 1;
267 printf("Playing %dhz %s-wave tone with %dhz sample rate and %dhz output, for %d second%s...\n",
268 tone_freq, GetWaveTypeName(wavetype), srate, dev_rate, max_loops+1, max_loops?"s":"");
269 fflush(stdout);
271 /* Create the source to play the sound with. */
272 source = 0;
273 alGenSources(1, &source);
274 alSourcei(source, AL_BUFFER, buffer);
275 assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
277 /* Play the sound for a while. */
278 num_loops = 0;
279 last_pos = 0;
280 alSourcei(source, AL_LOOPING, (max_loops > 0) ? AL_TRUE : AL_FALSE);
281 alSourcePlay(source);
282 do {
283 ALint pos;
284 al_nssleep(10000000);
285 alGetSourcei(source, AL_SAMPLE_OFFSET, &pos);
286 alGetSourcei(source, AL_SOURCE_STATE, &state);
287 if(pos < last_pos && state == AL_PLAYING)
289 ++num_loops;
290 if(num_loops >= max_loops)
291 alSourcei(source, AL_LOOPING, AL_FALSE);
292 printf("%d...\n", max_loops - num_loops + 1);
293 fflush(stdout);
295 last_pos = pos;
296 } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
298 /* All done. Delete resources, and close OpenAL. */
299 alDeleteSources(1, &source);
300 alDeleteBuffers(1, &buffer);
302 /* Close up OpenAL. */
303 CloseAL();
305 return 0;