Some cleanup in alspan.h
[openal-soft.git] / examples / alrecord.c
blob0e81eb76539525c65541cdbfafaed74e9f216546
1 /*
2 * OpenAL Recording 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 a relatively simple recorder. */
27 #include <string.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <errno.h>
32 #include "AL/al.h"
33 #include "AL/alc.h"
34 #include "AL/alext.h"
36 #include "common/alhelpers.h"
38 #include "win_main_utf8.h"
41 #if defined(_WIN64)
42 #define SZFMT "%I64u"
43 #elif defined(_WIN32)
44 #define SZFMT "%u"
45 #else
46 #define SZFMT "%zu"
47 #endif
50 #if defined(_MSC_VER) && (_MSC_VER < 1900)
51 static float msvc_strtof(const char *str, char **end)
52 { return (float)strtod(str, end); }
53 #define strtof msvc_strtof
54 #endif
57 static void fwrite16le(ALushort val, FILE *f)
59 ALubyte data[2] = { (ALubyte)(val&0xff), (ALubyte)((val>>8)&0xff) };
60 fwrite(data, 1, 2, f);
63 static void fwrite32le(ALuint val, FILE *f)
65 ALubyte data[4] = { (ALubyte)(val&0xff), (ALubyte)((val>>8)&0xff), (ALubyte)((val>>16)&0xff),
66 (ALubyte)((val>>24)&0xff) };
67 fwrite(data, 1, 4, f);
71 typedef struct Recorder {
72 ALCdevice *mDevice;
74 FILE *mFile;
75 long mDataSizeOffset;
76 ALuint mDataSize;
77 float mRecTime;
79 ALuint mChannels;
80 ALuint mBits;
81 ALuint mSampleRate;
82 ALuint mFrameSize;
83 ALbyte *mBuffer;
84 ALsizei mBufferSize;
85 } Recorder;
87 int main(int argc, char **argv)
89 static const char optlist[] =
90 " --channels/-c <channels> Set channel count (1 or 2)\n"
91 " --bits/-b <bits> Set channel count (8, 16, or 32)\n"
92 " --rate/-r <rate> Set sample rate (8000 to 96000)\n"
93 " --time/-t <time> Time in seconds to record (1 to 10)\n"
94 " --outfile/-o <filename> Output filename (default: record.wav)";
95 const char *fname = "record.wav";
96 const char *devname = NULL;
97 const char *progname;
98 Recorder recorder;
99 long total_size;
100 ALenum format;
101 ALCenum err;
103 progname = argv[0];
104 if(argc < 2)
106 fprintf(stderr, "Record from a device to a wav file.\n\n"
107 "Usage: %s [-device <name>] [options...]\n\n"
108 "Available options:\n%s\n", progname, optlist);
109 return 0;
112 recorder.mDevice = NULL;
113 recorder.mFile = NULL;
114 recorder.mDataSizeOffset = 0;
115 recorder.mDataSize = 0;
116 recorder.mRecTime = 4.0f;
117 recorder.mChannels = 1;
118 recorder.mBits = 16;
119 recorder.mSampleRate = 44100;
120 recorder.mFrameSize = recorder.mChannels * recorder.mBits / 8;
121 recorder.mBuffer = NULL;
122 recorder.mBufferSize = 0;
124 argv++; argc--;
125 if(argc > 1 && strcmp(argv[0], "-device") == 0)
127 devname = argv[1];
128 argv += 2;
129 argc -= 2;
132 while(argc > 0)
134 char *end;
135 if(strcmp(argv[0], "--") == 0)
136 break;
137 else if(strcmp(argv[0], "--channels") == 0 || strcmp(argv[0], "-c") == 0)
139 if(argc < 2)
141 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
142 return 1;
145 recorder.mChannels = (ALuint)strtoul(argv[1], &end, 0);
146 if((recorder.mChannels != 1 && recorder.mChannels != 2) || (end && *end != '\0'))
148 fprintf(stderr, "Invalid channels: %s\n", argv[1]);
149 return 1;
151 argv += 2;
152 argc -= 2;
154 else if(strcmp(argv[0], "--bits") == 0 || strcmp(argv[0], "-b") == 0)
156 if(argc < 2)
158 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
159 return 1;
162 recorder.mBits = (ALuint)strtoul(argv[1], &end, 0);
163 if((recorder.mBits != 8 && recorder.mBits != 16 && recorder.mBits != 32) ||
164 (end && *end != '\0'))
166 fprintf(stderr, "Invalid bit count: %s\n", argv[1]);
167 return 1;
169 argv += 2;
170 argc -= 2;
172 else if(strcmp(argv[0], "--rate") == 0 || strcmp(argv[0], "-r") == 0)
174 if(argc < 2)
176 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
177 return 1;
180 recorder.mSampleRate = (ALuint)strtoul(argv[1], &end, 0);
181 if(!(recorder.mSampleRate >= 8000 && recorder.mSampleRate <= 96000) || (end && *end != '\0'))
183 fprintf(stderr, "Invalid sample rate: %s\n", argv[1]);
184 return 1;
186 argv += 2;
187 argc -= 2;
189 else if(strcmp(argv[0], "--time") == 0 || strcmp(argv[0], "-t") == 0)
191 if(argc < 2)
193 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
194 return 1;
197 recorder.mRecTime = strtof(argv[1], &end);
198 if(!(recorder.mRecTime >= 1.0f && recorder.mRecTime <= 10.0f) || (end && *end != '\0'))
200 fprintf(stderr, "Invalid record time: %s\n", argv[1]);
201 return 1;
203 argv += 2;
204 argc -= 2;
206 else if(strcmp(argv[0], "--outfile") == 0 || strcmp(argv[0], "-o") == 0)
208 if(argc < 2)
210 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
211 return 1;
214 fname = argv[1];
215 argv += 2;
216 argc -= 2;
218 else if(strcmp(argv[0], "--help") == 0 || strcmp(argv[0], "-h") == 0)
220 fprintf(stderr, "Record from a device to a wav file.\n\n"
221 "Usage: %s [-device <name>] [options...]\n\n"
222 "Available options:\n%s\n", progname, optlist);
223 return 0;
225 else
227 fprintf(stderr, "Invalid option '%s'.\n\n"
228 "Usage: %s [-device <name>] [options...]\n\n"
229 "Available options:\n%s\n", argv[0], progname, optlist);
230 return 0;
234 recorder.mFrameSize = recorder.mChannels * recorder.mBits / 8;
236 format = AL_NONE;
237 if(recorder.mChannels == 1)
239 if(recorder.mBits == 8)
240 format = AL_FORMAT_MONO8;
241 else if(recorder.mBits == 16)
242 format = AL_FORMAT_MONO16;
243 else if(recorder.mBits == 32)
244 format = AL_FORMAT_MONO_FLOAT32;
246 else if(recorder.mChannels == 2)
248 if(recorder.mBits == 8)
249 format = AL_FORMAT_STEREO8;
250 else if(recorder.mBits == 16)
251 format = AL_FORMAT_STEREO16;
252 else if(recorder.mBits == 32)
253 format = AL_FORMAT_STEREO_FLOAT32;
256 recorder.mDevice = alcCaptureOpenDevice(devname, recorder.mSampleRate, format, 32768);
257 if(!recorder.mDevice)
259 fprintf(stderr, "Failed to open %s, %s %d-bit, %s, %dhz (%d samples)\n",
260 devname ? devname : "default device",
261 (recorder.mBits == 32) ? "Float" :
262 (recorder.mBits != 8) ? "Signed" : "Unsigned", recorder.mBits,
263 (recorder.mChannels == 1) ? "Mono" : "Stereo", recorder.mSampleRate,
264 32768
266 return 1;
268 fprintf(stderr, "Opened \"%s\"\n", alcGetString(
269 recorder.mDevice, ALC_CAPTURE_DEVICE_SPECIFIER
272 recorder.mFile = fopen(fname, "wb");
273 if(!recorder.mFile)
275 fprintf(stderr, "Failed to open '%s' for writing\n", fname);
276 alcCaptureCloseDevice(recorder.mDevice);
277 return 1;
280 fputs("RIFF", recorder.mFile);
281 fwrite32le(0xFFFFFFFF, recorder.mFile); // 'RIFF' header len; filled in at close
283 fputs("WAVE", recorder.mFile);
285 fputs("fmt ", recorder.mFile);
286 fwrite32le(18, recorder.mFile); // 'fmt ' header len
288 // 16-bit val, format type id (1 = integer PCM, 3 = float PCM)
289 fwrite16le((recorder.mBits == 32) ? 0x0003 : 0x0001, recorder.mFile);
290 // 16-bit val, channel count
291 fwrite16le((ALushort)recorder.mChannels, recorder.mFile);
292 // 32-bit val, frequency
293 fwrite32le(recorder.mSampleRate, recorder.mFile);
294 // 32-bit val, bytes per second
295 fwrite32le(recorder.mSampleRate * recorder.mFrameSize, recorder.mFile);
296 // 16-bit val, frame size
297 fwrite16le((ALushort)recorder.mFrameSize, recorder.mFile);
298 // 16-bit val, bits per sample
299 fwrite16le((ALushort)recorder.mBits, recorder.mFile);
300 // 16-bit val, extra byte count
301 fwrite16le(0, recorder.mFile);
303 fputs("data", recorder.mFile);
304 fwrite32le(0xFFFFFFFF, recorder.mFile); // 'data' header len; filled in at close
306 recorder.mDataSizeOffset = ftell(recorder.mFile) - 4;
307 if(ferror(recorder.mFile) || recorder.mDataSizeOffset < 0)
309 fprintf(stderr, "Error writing header: %s\n", strerror(errno));
310 fclose(recorder.mFile);
311 alcCaptureCloseDevice(recorder.mDevice);
312 return 1;
315 fprintf(stderr, "Recording '%s', %s %d-bit, %s, %dhz (%g second%s)\n", fname,
316 (recorder.mBits == 32) ? "Float" :
317 (recorder.mBits != 8) ? "Signed" : "Unsigned", recorder.mBits,
318 (recorder.mChannels == 1) ? "Mono" : "Stereo", recorder.mSampleRate,
319 recorder.mRecTime, (recorder.mRecTime != 1.0f) ? "s" : ""
322 err = ALC_NO_ERROR;
323 alcCaptureStart(recorder.mDevice);
324 while((double)recorder.mDataSize/(double)recorder.mSampleRate < recorder.mRecTime &&
325 (err=alcGetError(recorder.mDevice)) == ALC_NO_ERROR && !ferror(recorder.mFile))
327 ALCint count = 0;
328 fprintf(stderr, "\rCaptured %u samples", recorder.mDataSize);
329 alcGetIntegerv(recorder.mDevice, ALC_CAPTURE_SAMPLES, 1, &count);
330 if(count < 1)
332 al_nssleep(10000000);
333 continue;
335 if(count > recorder.mBufferSize)
337 ALbyte *data = calloc(recorder.mFrameSize, (ALuint)count);
338 free(recorder.mBuffer);
339 recorder.mBuffer = data;
340 recorder.mBufferSize = count;
342 alcCaptureSamples(recorder.mDevice, recorder.mBuffer, count);
343 #if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN
344 /* Byteswap multibyte samples on big-endian systems (wav needs little-
345 * endian, and OpenAL gives the system's native-endian).
347 if(recorder.mBits == 16)
349 ALCint i;
350 for(i = 0;i < count*recorder.mChannels;i++)
352 ALbyte b = recorder.mBuffer[i*2 + 0];
353 recorder.mBuffer[i*2 + 0] = recorder.mBuffer[i*2 + 1];
354 recorder.mBuffer[i*2 + 1] = b;
357 else if(recorder.mBits == 32)
359 ALCint i;
360 for(i = 0;i < count*recorder.mChannels;i++)
362 ALbyte b0 = recorder.mBuffer[i*4 + 0];
363 ALbyte b1 = recorder.mBuffer[i*4 + 1];
364 recorder.mBuffer[i*4 + 0] = recorder.mBuffer[i*4 + 3];
365 recorder.mBuffer[i*4 + 1] = recorder.mBuffer[i*4 + 2];
366 recorder.mBuffer[i*4 + 2] = b1;
367 recorder.mBuffer[i*4 + 3] = b0;
370 #endif
371 recorder.mDataSize += (ALuint)fwrite(recorder.mBuffer, recorder.mFrameSize, (ALuint)count,
372 recorder.mFile);
374 alcCaptureStop(recorder.mDevice);
375 fprintf(stderr, "\rCaptured %u samples\n", recorder.mDataSize);
376 if(err != ALC_NO_ERROR)
377 fprintf(stderr, "Got device error 0x%04x: %s\n", err, alcGetString(recorder.mDevice, err));
379 alcCaptureCloseDevice(recorder.mDevice);
380 recorder.mDevice = NULL;
382 free(recorder.mBuffer);
383 recorder.mBuffer = NULL;
384 recorder.mBufferSize = 0;
386 total_size = ftell(recorder.mFile);
387 if(fseek(recorder.mFile, recorder.mDataSizeOffset, SEEK_SET) == 0)
389 fwrite32le(recorder.mDataSize*recorder.mFrameSize, recorder.mFile);
390 if(fseek(recorder.mFile, 4, SEEK_SET) == 0)
391 fwrite32le((ALuint)total_size - 8, recorder.mFile);
394 fclose(recorder.mFile);
395 recorder.mFile = NULL;
397 return 0;