Make bformatdec_free and ambiup_free clear the freed pointer
[openal-soft.git] / examples / alrecord.c
blobc21ba30b17db8fc96777f2da07387e0bb2f44483
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 <math.h>
32 #include "AL/al.h"
33 #include "AL/alc.h"
34 #include "AL/alext.h"
36 #include "common/alhelpers.h"
39 #if defined(_WIN64)
40 #define SZFMT "%I64u"
41 #elif defined(_WIN32)
42 #define SZFMT "%u"
43 #else
44 #define SZFMT "%zu"
45 #endif
48 static void fwrite16le(ALushort val, FILE *f)
50 ALubyte data[2] = { val&0xff, (val>>8)&0xff };
51 fwrite(data, 1, 2, f);
54 static void fwrite32le(ALuint val, FILE *f)
56 ALubyte data[4] = { val&0xff, (val>>8)&0xff, (val>>16)&0xff, (val>>24)&0xff };
57 fwrite(data, 1, 4, f);
61 typedef struct Recorder {
62 ALCdevice *mDevice;
64 FILE *mFile;
65 long mDataSizeOffset;
66 ALuint mDataSize;
67 float mRecTime;
69 int mChannels;
70 int mBits;
71 int mSampleRate;
72 ALuint mFrameSize;
73 ALbyte *mBuffer;
74 ALsizei mBufferSize;
75 } Recorder;
77 int main(int argc, char **argv)
79 static const char optlist[] =
80 " --channels/-c <channels> Set channel count (1 or 2)\n"
81 " --bits/-b <bits> Set channel count (8, 16, or 32)\n"
82 " --rate/-r <rate> Set sample rate (8000 to 96000)\n"
83 " --time/-t <time> Time in seconds to record (1 to 10)\n"
84 " --outfile/-o <filename> Output filename (default: record.wav)";
85 const char *fname = "record.wav";
86 const char *devname = NULL;
87 const char *progname;
88 Recorder recorder;
89 long total_size;
90 ALenum format;
91 ALCenum err;
93 progname = argv[0];
94 if(argc < 2)
96 fprintf(stderr, "Record from a device to a wav file.\n\n"
97 "Usage: %s [-device <name>] [options...]\n\n"
98 "Available options:\n%s\n", progname, optlist);
99 return 0;
102 recorder.mDevice = NULL;
103 recorder.mFile = NULL;
104 recorder.mDataSizeOffset = 0;
105 recorder.mDataSize = 0;
106 recorder.mRecTime = 4.0f;
107 recorder.mChannels = 1;
108 recorder.mBits = 16;
109 recorder.mSampleRate = 44100;
110 recorder.mFrameSize = recorder.mChannels * recorder.mBits / 8;
111 recorder.mBuffer = NULL;
112 recorder.mBufferSize = 0;
114 argv++; argc--;
115 if(argc > 1 && strcmp(argv[0], "-device") == 0)
117 devname = argv[1];
118 argv += 2;
119 argc -= 2;
122 while(argc > 0)
124 char *end;
125 if(strcmp(argv[0], "--") == 0)
126 break;
127 else if(strcmp(argv[0], "--channels") == 0 || strcmp(argv[0], "-c") == 0)
129 if(!(argc > 1))
131 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
132 return 1;
135 recorder.mChannels = strtol(argv[1], &end, 0);
136 if((recorder.mChannels != 1 && recorder.mChannels != 2) || (end && *end != '\0'))
138 fprintf(stderr, "Invalid channels: %s\n", argv[1]);
139 return 1;
141 argv += 2;
142 argc -= 2;
144 else if(strcmp(argv[0], "--bits") == 0 || strcmp(argv[0], "-b") == 0)
146 if(!(argc > 1))
148 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
149 return 1;
152 recorder.mBits = strtol(argv[1], &end, 0);
153 if((recorder.mBits != 8 && recorder.mBits != 16 && recorder.mBits != 32) ||
154 (end && *end != '\0'))
156 fprintf(stderr, "Invalid bit count: %s\n", argv[1]);
157 return 1;
159 argv += 2;
160 argc -= 2;
162 else if(strcmp(argv[0], "--rate") == 0 || strcmp(argv[0], "-r") == 0)
164 if(!(argc > 1))
166 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
167 return 1;
170 recorder.mSampleRate = strtol(argv[1], &end, 0);
171 if(!(recorder.mSampleRate >= 8000 && recorder.mSampleRate <= 96000) || (end && *end != '\0'))
173 fprintf(stderr, "Invalid sample rate: %s\n", argv[1]);
174 return 1;
176 argv += 2;
177 argc -= 2;
179 else if(strcmp(argv[0], "--time") == 0 || strcmp(argv[0], "-t") == 0)
181 if(!(argc > 1))
183 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
184 return 1;
187 recorder.mRecTime = strtof(argv[1], &end);
188 if(!(recorder.mRecTime >= 1.0f && recorder.mRecTime <= 10.0f) || (end && *end != '\0'))
190 fprintf(stderr, "Invalid record time: %s\n", argv[1]);
191 return 1;
193 argv += 2;
194 argc -= 2;
196 else if(strcmp(argv[0], "--outfile") == 0 || strcmp(argv[0], "-o") == 0)
198 if(!(argc > 1))
200 fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
201 return 1;
204 fname = argv[1];
205 argv += 2;
206 argc -= 2;
208 else if(strcmp(argv[0], "--help") == 0 || strcmp(argv[0], "-h") == 0)
210 fprintf(stderr, "Record from a device to a wav file.\n\n"
211 "Usage: %s [-device <name>] [options...]\n\n"
212 "Available options:\n%s\n", progname, optlist);
213 return 0;
215 else
217 fprintf(stderr, "Invalid option '%s'.\n\n"
218 "Usage: %s [-device <name>] [options...]\n\n"
219 "Available options:\n%s\n", argv[0], progname, optlist);
220 return 0;
224 recorder.mFrameSize = recorder.mChannels * recorder.mBits / 8;
226 format = AL_NONE;
227 if(recorder.mChannels == 1)
229 if(recorder.mBits == 8)
230 format = AL_FORMAT_MONO8;
231 else if(recorder.mBits == 16)
232 format = AL_FORMAT_MONO16;
233 else if(recorder.mBits == 32)
234 format = AL_FORMAT_MONO_FLOAT32;
236 else if(recorder.mChannels == 2)
238 if(recorder.mBits == 8)
239 format = AL_FORMAT_STEREO8;
240 else if(recorder.mBits == 16)
241 format = AL_FORMAT_STEREO16;
242 else if(recorder.mBits == 32)
243 format = AL_FORMAT_STEREO_FLOAT32;
246 recorder.mDevice = alcCaptureOpenDevice(devname, recorder.mSampleRate, format, 32768);
247 if(!recorder.mDevice)
249 fprintf(stderr, "Failed to open %s, %s %d-bit, %s, %dhz (%d samples)\n",
250 devname ? devname : "default device",
251 (recorder.mBits == 32) ? "Float" :
252 (recorder.mBits != 8) ? "Signed" : "Unsigned", recorder.mBits,
253 (recorder.mChannels == 1) ? "Mono" : "Stereo", recorder.mSampleRate,
254 32768
256 return 1;
258 fprintf(stderr, "Opened \"%s\"\n", alcGetString(
259 recorder.mDevice, ALC_CAPTURE_DEVICE_SPECIFIER
262 recorder.mFile = fopen(fname, "wb");
263 if(!recorder.mFile)
265 fprintf(stderr, "Failed to open '%s' for writing\n", fname);
266 alcCaptureCloseDevice(recorder.mDevice);
267 return 1;
270 fputs("RIFF", recorder.mFile);
271 fwrite32le(0xFFFFFFFF, recorder.mFile); // 'RIFF' header len; filled in at close
273 fputs("WAVE", recorder.mFile);
275 fputs("fmt ", recorder.mFile);
276 fwrite32le(18, recorder.mFile); // 'fmt ' header len
278 // 16-bit val, format type id (1 = integer PCM, 3 = float PCM)
279 fwrite16le((recorder.mBits == 32) ? 0x0003 : 0x0001, recorder.mFile);
280 // 16-bit val, channel count
281 fwrite16le(recorder.mChannels, recorder.mFile);
282 // 32-bit val, frequency
283 fwrite32le(recorder.mSampleRate, recorder.mFile);
284 // 32-bit val, bytes per second
285 fwrite32le(recorder.mSampleRate * recorder.mFrameSize, recorder.mFile);
286 // 16-bit val, frame size
287 fwrite16le(recorder.mFrameSize, recorder.mFile);
288 // 16-bit val, bits per sample
289 fwrite16le(recorder.mBits, recorder.mFile);
290 // 16-bit val, extra byte count
291 fwrite16le(0, recorder.mFile);
293 fputs("data", recorder.mFile);
294 fwrite32le(0xFFFFFFFF, recorder.mFile); // 'data' header len; filled in at close
296 recorder.mDataSizeOffset = ftell(recorder.mFile) - 4;
297 if(ferror(recorder.mFile) || recorder.mDataSizeOffset < 0)
299 fprintf(stderr, "Error writing header: %s\n", strerror(errno));
300 fclose(recorder.mFile);
301 alcCaptureCloseDevice(recorder.mDevice);
302 return 1;
305 fprintf(stderr, "Recording '%s', %s %d-bit, %s, %dhz (%g second%s)\n", fname,
306 (recorder.mBits == 32) ? "Float" :
307 (recorder.mBits != 8) ? "Signed" : "Unsigned", recorder.mBits,
308 (recorder.mChannels == 1) ? "Mono" : "Stereo", recorder.mSampleRate,
309 recorder.mRecTime, (recorder.mRecTime != 1.0f) ? "s" : ""
312 alcCaptureStart(recorder.mDevice);
313 while((double)recorder.mDataSize/(double)recorder.mSampleRate < recorder.mRecTime &&
314 (err=alcGetError(recorder.mDevice)) == ALC_NO_ERROR && !ferror(recorder.mFile))
316 ALCint count = 0;
317 fprintf(stderr, "\rCaptured %u samples", recorder.mDataSize);
318 alcGetIntegerv(recorder.mDevice, ALC_CAPTURE_SAMPLES, 1, &count);
319 if(count < 1)
321 al_nssleep(10000000);
322 continue;
324 if(count > recorder.mBufferSize)
326 ALbyte *data = calloc(recorder.mFrameSize, count);
327 free(recorder.mBuffer);
328 recorder.mBuffer = data;
329 recorder.mBufferSize = count;
331 alcCaptureSamples(recorder.mDevice, recorder.mBuffer, count);
332 #if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN
333 /* Byteswap multibyte samples on big-endian systems (wav needs little-
334 * endian, and OpenAL gives the system's native-endian).
336 if(recorder.mBits == 16)
338 ALCint i;
339 for(i = 0;i < count*recorder.mChannels;i++)
341 ALbyte b = recorder.mBuffer[i*2 + 0];
342 recorder.mBuffer[i*2 + 0] = recorder.mBuffer[i*2 + 1];
343 recorder.mBuffer[i*2 + 1] = b;
346 else if(recorder.mBits == 32)
348 ALCint i;
349 for(i = 0;i < count*recorder.mChannels;i++)
351 ALbyte b0 = recorder.mBuffer[i*4 + 0];
352 ALbyte b1 = recorder.mBuffer[i*4 + 1];
353 recorder.mBuffer[i*4 + 0] = recorder.mBuffer[i*4 + 3];
354 recorder.mBuffer[i*4 + 1] = recorder.mBuffer[i*4 + 2];
355 recorder.mBuffer[i*4 + 2] = b1;
356 recorder.mBuffer[i*4 + 3] = b0;
359 #endif
360 recorder.mDataSize += (ALuint)fwrite(recorder.mBuffer, recorder.mFrameSize, count,
361 recorder.mFile);
363 alcCaptureStop(recorder.mDevice);
364 fprintf(stderr, "\rCaptured %u samples\n", recorder.mDataSize);
365 if(err != ALC_NO_ERROR)
366 fprintf(stderr, "Got device error 0x%04x: %s\n", err, alcGetString(recorder.mDevice, err));
368 alcCaptureCloseDevice(recorder.mDevice);
369 recorder.mDevice = NULL;
371 free(recorder.mBuffer);
372 recorder.mBuffer = NULL;
373 recorder.mBufferSize = 0;
375 total_size = ftell(recorder.mFile);
376 if(fseek(recorder.mFile, recorder.mDataSizeOffset, SEEK_SET) == 0)
378 fwrite32le(recorder.mDataSize*recorder.mFrameSize, recorder.mFile);
379 if(fseek(recorder.mFile, 4, SEEK_SET) == 0)
380 fwrite32le(total_size - 8, recorder.mFile);
383 fclose(recorder.mFile);
384 recorder.mFile = NULL;
386 return 0;